This commit is contained in:
Александр Тороп
2024-03-30 18:27:37 +03:00
commit 038bf44010
2765 changed files with 293753 additions and 0 deletions

5
Dockerfile Normal file
View File

@@ -0,0 +1,5 @@
FROM node
WORKDIR /bot
RUN npm install nodemon -g
COPY ./ ./
CMD ["nodemon", "telegram_support_bot.js"]

34
README.md Normal file
View File

@@ -0,0 +1,34 @@
1. Клонировать репозиторий
2. В файле data/conf.json заменить параметры:
telegramBotToken: токен телеграм бота
supportChatId: id чата для техподдержки
CompanyName: название компании (для приветствия)
glpiConfig:
apiurl: "http://[имя домена]/apirest.php"
app_token: это токен приложения, настраивается в админке
user_token: это "app-token" в настройках юзера
user_id: id юзера, через которого будет авторизироваться бот (видно в адресной строке)
3. В файле data/dataId.json в параметре "ticket" желательно указать номер последней заявки
4. Проверить в telegram_support.service путь к исполняемому файлу и добавить его в папку /etc/systemd/system/ (для debian)
5. Для работы бота должен быть установлен node.js (все остальные зависимости находятся в папке node_modules)
6. Обновить демоны командой:
> systemctl daemon-reload
Запустить его:
> systemctl start telegram_support.service --now
**Создание образа и запуск его в docker-контейнере**
1. Выполнить первые 3 пункта из инструкции выше
2. Перейти в папку telegram-support-bot
3. Запустить контейнер командой:
> docker compose up -d --build

11
data/conf.json Normal file
View File

@@ -0,0 +1,11 @@
{
"telegramBotToken": "",
"supportChatId": "",
"CompanyName": "",
"glpiConfig": {
"apiurl": "",
"app_token": "",
"user_token": "",
"user_id": ""
}
}

7
data/dataId.json Normal file
View File

@@ -0,0 +1,7 @@
{
"ticket": 0,
"comment": 0,
"history": {
}
}

3
data/threads.json Normal file
View File

@@ -0,0 +1,3 @@
{
}

13
docker-compose.yml Normal file
View File

@@ -0,0 +1,13 @@
version: '3'
services:
support_bot:
build: ../telegram-support-bot
restart: always
volumes:
- /bot/data
- ../telegram-support-bot:/bot
- data:/bot/data
volumes:
data:

38
lib/const.js Normal file
View File

@@ -0,0 +1,38 @@
const { Markup } = require('telegraf');
exports.colors = ['Чёрный', 'Синий', 'Жёлтый', "Розовый"];
exports.printers = ['Canon', 'Kyocera', 'Epson', 'SHARP', 'HP', "Brother", 'Lexmark']
exports.keyboards = {
main: Markup.keyboard(
[['Принтеры', 'Сброс пароля'], ["Физические устройства", "Сеть"], ['Программное обеспечение', "Отменить заявку"]]
).resize(),
printers: Markup.keyboard(
[['Замена картриджа', 'Настройка принтера'], ['Другие проблемы', "Назад"]]
).resize(),
applications: Markup.keyboard(
[['Загрузка сайтов', 'Локальное ПО'], ['Виртуальные машины', 'Назад']]
).resize(),
back: Markup.keyboard(
[['Назад']]
).resize(),
colors: Markup.keyboard(
[['Чёрный', 'Синий'], ['Жёлтый', "Розовый", 'Назад']]
).resize(),
printModels: Markup.keyboard(
[['Canon', 'Kyocera', 'Epson', 'SHARP'], ['HP', "Brother", 'Lexmark', 'Назад']]
).resize(),
final: Markup.keyboard(
[['Отправить заявку', 'Назад', 'Отменить заявку']]
).resize(),
start: Markup.keyboard([['Подать заявку']]).resize()
};
exports.inlineKeyboards = {
open: [[{text: '✅', callback_data: 'CloseTicket'}, {text: '💬', callback_data: 'AddComment'}]],
close: [[{text: '✔', callback_data: 'OpenTicket'}, {text: '💬', callback_data: 'AddComment'}]],
confirmOpen: [[{text: 'Открыть заявку', callback_data: 'ConfirmOpen'}, {text: 'Отмена', callback_data: 'RefreshStatus'}]],
confirmClose: [[{text: 'Закрыть заявку', callback_data: 'ConfirmClose'}, {text: 'Отмена', callback_data: 'RefreshStatus'}]],
userAddComment: [[{text: '❓ Добавить комментарий', callback_data: 'UserAddComment'}]],
threadPin: [[{text: 'Закрыть тему', callback_data: 'CloseThread'}]],
threadPinConfirm: [[{text: 'Подтвердить', callback_data: 'ConfirmCloseThread'}, {text: 'Отмена', callback_data: 'CancelCloseThread'}]]
};

152
lib/glpm.js Normal file
View File

@@ -0,0 +1,152 @@
const GlpiApi = require('glpi-api');
const axios = require('axios');
const fs = require('fs');
const conf = JSON.parse(fs.readFileSync(__dirname + "/../data/conf.json"));
const glpi = new GlpiApi(conf.glpiConfig);
exports.createTicket = async (title, description) => {
try{
const session = await glpi.initSession();
let token = session.data.session_token;
const response = await axios(conf.glpiConfig.apiurl + '/Ticket', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'App-Token': conf.glpiConfig.app_token,
'Authorization': conf.glpiConfig.user_token,
'Session-Token': token
},
data: JSON.stringify({
input: {
name: title,
content: description
}
})
});
return response.data.id;
}catch(error){
console.error('Failed to create ticket:', error);
}
}
exports.changeStatusTicket = async (ticketId, statusId) => {
try{
const session = await glpi.initSession();
let token = session.data.session_token;
const response = await axios(conf.glpiConfig.apiurl + '/Ticket', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'App-Token': conf.glpiConfig.app_token,
'Authorization': conf.glpiConfig.user_token,
'Session-Token': token
},
data: JSON.stringify({
input: {
id: ticketId,
status: statusId
}
})
});
return response;
}catch(error){
console.error('Failed to create ticket:', error);
}
}
exports.getItem = async(item, id) => { // ITILFollowup = комментарий
try{
const session = await glpi.initSession();
let token = session.data.session_token;
const response = await axios(`${conf.glpiConfig.apiurl}/${item}/${id}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'App-Token': conf.glpiConfig.app_token,
'Authorization': conf.glpiConfig.user_token,
'Session-Token': token
}
});
return response.data;
}catch(error){
return 0;
}
}
exports.getAllItems = async(item, cnt) => {
try{
const session = await glpi.initSession();
let token = session.data.session_token;
const response = await axios(`${conf.glpiConfig.apiurl}/${item}?order=DESC&range=0-${cnt}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'App-Token': conf.glpiConfig.app_token,
'Authorization': conf.glpiConfig.user_token,
'Session-Token': token
}
});
return response.data;
}catch(error){
return error;
}
}
exports.addComment = async(ticketId, comment) => {
const session = await glpi.initSession();
let token = session.data.session_token;
const response = await axios(conf.glpiConfig.apiurl + '/ITILFollowup/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'App-Token': conf.glpiConfig.app_token,
'Authorization': conf.glpiConfig.user_token,
'Session-Token': token
},
data: JSON.stringify({
input: {
items_id: ticketId,
itemtype: "Ticket",
content: comment
}
})
}).catch((err) => console.log(err));
return response.data;
}
exports.removeComment = async(ticketId, commentId) => {
const session = await glpi.initSession();
let token = session.data.session_token;
const response = await axios(conf.glpiConfig.apiurl + '/ITILFollowup/' + commentId, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'App-Token': conf.glpiConfig.app_token,
'Authorization': conf.glpiConfig.user_token,
'Session-Token': token
},
data: JSON.stringify({
input: {
items_id: ticketId,
itemtype: "Ticket"
}
})
}).catch((err) => console.log(err));
return response.data;
}
exports.getUsers = async(ticketId) => {
const session = await glpi.initSession();
let token = session.data.session_token;
const response = await axios(`${conf.glpiConfig.apiurl}/Ticket/${ticketId}/Ticket_User`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'App-Token': conf.glpiConfig.app_token,
'Authorization': conf.glpiConfig.user_token,
'Session-Token': token
}
}).catch((err) => console.log(err));
return response.data;
}

63
lib/utils.js Normal file
View File

@@ -0,0 +1,63 @@
const he = require('he');
const html = require('html-to-text');
const fs = require('fs');
const conf = JSON.parse(fs.readFileSync(__dirname + "/../data/conf.json"));
const glpiUrl = conf.glpiConfig.apiurl.replace("apirest.php", "");
exports.htmlToText = async(text) => {
let temp = html.convert(he.decode(text), {preserveNewlines: true});
textArray = temp.split('\n');
for(let i in textArray){
if(textArray[i].indexOf("[/front/document.send.php?docid=") >= 0){
delete textArray[i-1];
delete textArray[i];
}
}
let messageText = '';
for(let k in textArray){
if(textArray[k][0] != '>' && textArray[k].trim() && textArray[k].indexOf('cellpadding="0"') == -1){
messageText += textArray[k].trim().replace(/[<>]/g, '') + ' ';
}
}
return messageText.replace(/\[.*?\]/g, '');
}
exports.parseMessageText = async(message, addSilentInfo) => {
let color = '🟢';
if(message.hasOwnProperty('status')){
switch(message.status){
case 1: color = '🟢'; break;
case 2: color = '🔵'; break;
case 4: color = '🟠'; break;
case 6: color = '⚫'; break;
default: color = '⚫';
}
}
let ticketId = message.text.split('\n')[0].split('№')[1];
if(!addSilentInfo){
addSilentInfo = '';
}else addSilentInfo = '/' + addSilentInfo;
let silentInfo = `<a href="${message.entities[0].url}${addSilentInfo}">&#8203</a>`;
text = message.text.split('\n');
messageText = `${silentInfo}${color} <b>ЗАЯВКА <a href="${glpiUrl}front/ticket.form.php?id=${ticketId}">№${ticketId}</a></b>\n\n`;
for(let i = 2; i < text.length; i++){
if(text[i].indexOf(':') >= 0) messageText += `<b>${text[i].replace(':', ':</b>')}\n`;
}
for(let i in message.entities){
if(message.entities[i].type == 'text_link' && message.entities[i].url.indexOf(glpiUrl + 'front/document.send.php?docid=') > 0){
messageText = messageText.substring(0, messageText.length - 1).replace('screen', '');
messageText += `<a href="${message.entities[i].url}">screen</a>`;
}
}
if(text[text.length - 1].indexOf("Читать дальше") >= 0){
messageText = `${messageText.replace('Читать дальше', '')}\n<b><a href="${glpiUrl}front/ticket.form.php?id=${ticketId}">Читать дальше</a></b>`;
}
return messageText;
}
exports.sleep = async(ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

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

@@ -0,0 +1 @@
../he/bin/he

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

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

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

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

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

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

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

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

1
node_modules/.bin/sshpk-conv generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../sshpk/bin/sshpk-conv

1
node_modules/.bin/sshpk-sign generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../sshpk/bin/sshpk-sign

1
node_modules/.bin/sshpk-verify generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../sshpk/bin/sshpk-verify

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

@@ -0,0 +1 @@
../telegraf/lib/cli.mjs

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

@@ -0,0 +1 @@
../uuid/bin/uuid

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

File diff suppressed because it is too large Load Diff

33
node_modules/@selderee/plugin-htmlparser2/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,33 @@
# Changelog
## Version 0.11.0
* (`selderee`) Escape sequences in selectors.
## Version 0.10.0
* Targeting Node.js version 14 and ES2020;
* Bump dependencies.
## Version 0.9.0
* Bump dependencies - fix "./core module cannot be found" issue.
## Version 0.8.1
* Sync with `selderee` package version. Now all dependencies are TypeScript, dual CommonJS/ES module packages;
* Use `rollup-plugin-cleanup` to condition published files.
## Version 0.7.0
* Drop Node.js version 10 support. At least 12.22.x is required.
## Version 0.6.0
* `selderee` 0.6.0 - [changelog](https://github.com/mxxii/selderee/blob/main/packages/selderee/CHANGELOG.md).
## Version 0.5.0
Initial release.
Aiming at Node.js version 10 and up.

21
node_modules/@selderee/plugin-htmlparser2/LICENSE generated vendored Normal file
View File

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

15
node_modules/@selderee/plugin-htmlparser2/README.md generated vendored Normal file
View File

@@ -0,0 +1,15 @@
# selderee
![lint status badge](https://github.com/mxxii/selderee/workflows/lint/badge.svg)
![test status badge](https://github.com/mxxii/selderee/workflows/test/badge.svg)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/mxxii/selderee/blob/main/LICENSE)
[selderee](https://github.com/mxxii/selderee) plugin - selectors decision tree builder for [htmlparser2](https://github.com/fb55/htmlparser2) DOM AST.
(Technically, the package depends not on `htmlparser2` but on [domhandler](https://github.com/fb55/domhandler), underlying package of `htmlparser2`.)
----
[Changelog](https://github.com/mxxii/selderee/blob/main/packages/plugin-htmlparser2/CHANGELOG.md).
See [main README file](https://github.com/mxxii/selderee/blob/main/README.md) for more info.

View File

@@ -0,0 +1,94 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var domhandler = require('domhandler');
var selderee = require('selderee');
function hp2Builder(nodes) {
return new selderee.Picker(handleArray(nodes));
}
function handleArray(nodes) {
const matchers = nodes.map(handleNode);
return (el, ...tail) => matchers.flatMap(m => m(el, ...tail));
}
function handleNode(node) {
switch (node.type) {
case 'terminal': {
const result = [node.valueContainer];
return (el, ...tail) => result;
}
case 'tagName':
return handleTagName(node);
case 'attrValue':
return handleAttrValueName(node);
case 'attrPresence':
return handleAttrPresenceName(node);
case 'pushElement':
return handlePushElementNode(node);
case 'popElement':
return handlePopElementNode(node);
}
}
function handleTagName(node) {
const variants = {};
for (const variant of node.variants) {
variants[variant.value] = handleArray(variant.cont);
}
return (el, ...tail) => {
const continuation = variants[el.name];
return (continuation) ? continuation(el, ...tail) : [];
};
}
function handleAttrPresenceName(node) {
const attrName = node.name;
const continuation = handleArray(node.cont);
return (el, ...tail) => (Object.prototype.hasOwnProperty.call(el.attribs, attrName))
? continuation(el, ...tail)
: [];
}
function handleAttrValueName(node) {
const callbacks = [];
for (const matcher of node.matchers) {
const predicate = matcher.predicate;
const continuation = handleArray(matcher.cont);
callbacks.push((attr, el, ...tail) => (predicate(attr) ? continuation(el, ...tail) : []));
}
const attrName = node.name;
return (el, ...tail) => {
const attr = el.attribs[attrName];
return (attr || attr === '')
? callbacks.flatMap(cb => cb(attr, el, ...tail))
: [];
};
}
function handlePushElementNode(node) {
const continuation = handleArray(node.cont);
const leftElementGetter = (node.combinator === '+')
? getPrecedingElement
: getParentElement;
return (el, ...tail) => {
const next = leftElementGetter(el);
if (next === null) {
return [];
}
return continuation(next, el, ...tail);
};
}
const getPrecedingElement = (el) => {
const prev = el.prev;
if (prev === null) {
return null;
}
return (domhandler.isTag(prev)) ? prev : getPrecedingElement(prev);
};
const getParentElement = (el) => {
const parent = el.parent;
return (parent && domhandler.isTag(parent)) ? parent : null;
};
function handlePopElementNode(node) {
const continuation = handleArray(node.cont);
return (el, next, ...tail) => continuation(next, ...tail);
}
exports.hp2Builder = hp2Builder;

View File

@@ -0,0 +1,16 @@
import { Element } from 'domhandler';
import { Picker, Ast } from 'selderee';
/**
* A {@link BuilderFunction} implementation.
*
* Creates a function (in a {@link Picker} wrapper) that can run
* the decision tree against `htmlparser2` `Element` nodes.
*
* @typeParam V - the type of values associated with selectors.
*
* @param nodes - nodes ({@link DecisionTreeNode})
* from the root level of the decision tree.
*
* @returns a {@link Picker} object.
*/
export declare function hp2Builder<V>(nodes: Ast.DecisionTreeNode<V>[]): Picker<Element, V>;

View File

@@ -0,0 +1,90 @@
import { isTag } from 'domhandler';
import { Picker } from 'selderee';
function hp2Builder(nodes) {
return new Picker(handleArray(nodes));
}
function handleArray(nodes) {
const matchers = nodes.map(handleNode);
return (el, ...tail) => matchers.flatMap(m => m(el, ...tail));
}
function handleNode(node) {
switch (node.type) {
case 'terminal': {
const result = [node.valueContainer];
return (el, ...tail) => result;
}
case 'tagName':
return handleTagName(node);
case 'attrValue':
return handleAttrValueName(node);
case 'attrPresence':
return handleAttrPresenceName(node);
case 'pushElement':
return handlePushElementNode(node);
case 'popElement':
return handlePopElementNode(node);
}
}
function handleTagName(node) {
const variants = {};
for (const variant of node.variants) {
variants[variant.value] = handleArray(variant.cont);
}
return (el, ...tail) => {
const continuation = variants[el.name];
return (continuation) ? continuation(el, ...tail) : [];
};
}
function handleAttrPresenceName(node) {
const attrName = node.name;
const continuation = handleArray(node.cont);
return (el, ...tail) => (Object.prototype.hasOwnProperty.call(el.attribs, attrName))
? continuation(el, ...tail)
: [];
}
function handleAttrValueName(node) {
const callbacks = [];
for (const matcher of node.matchers) {
const predicate = matcher.predicate;
const continuation = handleArray(matcher.cont);
callbacks.push((attr, el, ...tail) => (predicate(attr) ? continuation(el, ...tail) : []));
}
const attrName = node.name;
return (el, ...tail) => {
const attr = el.attribs[attrName];
return (attr || attr === '')
? callbacks.flatMap(cb => cb(attr, el, ...tail))
: [];
};
}
function handlePushElementNode(node) {
const continuation = handleArray(node.cont);
const leftElementGetter = (node.combinator === '+')
? getPrecedingElement
: getParentElement;
return (el, ...tail) => {
const next = leftElementGetter(el);
if (next === null) {
return [];
}
return continuation(next, el, ...tail);
};
}
const getPrecedingElement = (el) => {
const prev = el.prev;
if (prev === null) {
return null;
}
return (isTag(prev)) ? prev : getPrecedingElement(prev);
};
const getParentElement = (el) => {
const parent = el.parent;
return (parent && isTag(parent)) ? parent : null;
};
function handlePopElementNode(node) {
const continuation = handleArray(node.cont);
return (el, next, ...tail) => continuation(next, ...tail);
}
export { hp2Builder };

47
node_modules/@selderee/plugin-htmlparser2/package.json generated vendored Normal file
View File

@@ -0,0 +1,47 @@
{
"name": "@selderee/plugin-htmlparser2",
"version": "0.11.0",
"description": "selderee plugin - selectors decision tree builder for htmlparser2 DOM.",
"keywords": [
"htmlparser2",
"selderee",
"plugin",
"selderee plugin"
],
"repository": {
"type": "git",
"url": "git+https://github.com/mxxii/selderee.git"
},
"bugs": {
"url": "https://github.com/mxxii/selderee/issues"
},
"homepage": "https://github.com/mxxii/selderee",
"author": "KillyMXI",
"funding": "https://ko-fi.com/killymxi",
"license": "MIT",
"exports": {
"import": "./lib/hp2-builder.mjs",
"require": "./lib/hp2-builder.cjs"
},
"type": "module",
"main": "./lib/hp2-builder.cjs",
"module": "./lib/hp2-builder.mjs",
"types": "./lib/hp2-builder.d.ts",
"typedocMain": "./src/hp2-builder.ts",
"files": [
"lib"
],
"scripts": {
"build:rollup": "rollup -c",
"build:types": "tsc -d --emitDeclarationOnly --declarationDir ./lib",
"build": "npm run clean && npm run build:rollup && npm run build:types",
"clean": "rimraf lib"
},
"dependencies": {
"domhandler": "^5.0.3",
"selderee": "^0.11.0"
},
"devDependencies": {
"htmlparser2": "^8.0.1"
}
}

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

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

113
node_modules/@telegraf/types/README.md generated vendored Normal file
View File

@@ -0,0 +1,113 @@
# Types for the Telegram Bot API [![Deno shield](https://img.shields.io/static/v1?label=Built%20for&message=Deno&style=flat-square&logo=deno&labelColor=000&color=fff)](https://deno.land/x/telegraf_types)
[![Bot API Version](https://img.shields.io/badge/Bot%20API-v6.9-f36caf.svg?style=flat-square&logo=Telegram&labelColor=white&color=blue)](https://core.telegram.org/bots/api) [![NPM version](https://img.shields.io/npm/v/@telegraf/types?style=flat-square&logo=npm&labelColor=fff&color=c53635)](https://npmjs.com/package/@telegraf/types)
This project is a fork of [@KnorpelSenf/typegram](https://github.com/KnorpelSenf/typegram), specialised for Telegraf. Typegram is legacy, and now backported from [@grammyjs/types](https://github.com/grammyjs/types).
This fork keeps Telegram Bot API types updated for Telegraf. This project provides TypeScript types for the entire [Telegram Bot API](https://core.telegram.org/bots/api).
It contains zero bytes of executable code.
## Installation
```bash
npm install --save-dev @telegraf/types
```
## Available Types
Generally, this package just exposes a huge load of `interface`s that correspond to the **types** used throughout the Telegram Bot API.
Note that the API specification sometimes only has one name for multiple variants of a type, e.g. there are a number of different `Update`s you can receive, but they're all just called `Update`.
This package represents such types as large unions of all possible options of what an `Update` could be, such that type narrowing can work as expected on your side.
If you need to access the individual variants of an `Update`, refer to `Update.MessageUpdate` and its siblings.
In fact, this pattern is used for various types, namely:
- `Update`
- `Message`
- `CallbackQuery`
- `Chat`
- `ChatFromGetChat`
- `InlineKeyboardButton`
- `KeyboardButton`
- `MessageEntity`
- `Location`
(Naturally, when the API specification is actually modelling types to be unions (e.g. `InlineQueryResult`), this is reflected here as a union type, too.)
## Using API Response objects
The Telegram Bot API does not return just the requested data in the body of the response objects.
Instead, they are wrapped inside an object that has an `ok: boolean` status flag, indicating success or failure of the preceding API request.
This outer object is modelled in `@telegraf/types` by the `ApiResponse` type.
## Customizing `InputFile` and accessing API methods
The Telegram Bot API lets bots send files in [three different ways](https://core.telegram.org/bots/api#sending-files).
Two of those ways are by specifying a `string`—either a `file_id` or a URL.
The third option, however, is by uploading files to the server using multipart/form-data.
The first two means to send a file are already covered by the type annotations across the library.
In all places where a `file_id` or a URL is permitted, the corresponding property allows a `string`.
We will now look at the type declarations that are relevant for uploading files directly.
Depending on the code you're using the types for, you may want to support different ways to specify the file to be uploaded.
As an example, you may want to be able to make calls to `sendDocument` with an object that conforms to `{ path: string }` in order to specify the location of a local file.
(Your code is then assumed to able to translate calls to `sendDocument` and the like to multipart/form-data uploads when supplied with an object alike `{ path: '/tmp/file.txt' }` in the `document` property of the argument object.)
This library cannot automatically know what objects you want to support as `InputFile`s.
However, you can specify your own version of what an `InputFile` is throughout all affected methods and interfaces.
For instance, let's stick with our example and say that you want to support `InputFile`s of the following type.
```ts
interface MyInputFile {
path: string;
}
```
You can then customize the types to fit your needs by passing your custom `InputFile` to the `ApiMethods` type.
```ts
import * as Telegram from "@telegraf/types";
type API = Telegram.ApiMethods<MyInputFile>;
```
You can now access all types that must respect `MyInputFile` through the `API` type:
```ts
// The utility types `Opts` and `Ret`:
type Opts<M extends keyof API> = Telegram.Opts<MyInputFile>[M];
type Ret<M extends keyof API> = Telegram.Ret<MyInputFile>[M];
```
Each method takes just a single argument with a structure that corresponds to the object expected by Telegram.
If you need to directly access that type, consider using `Opts<M>` where `M` is the method name (e.g. `Opts<'getMe'>`).
Each method returns the object that is specified by Telegram.
If you directly need to access the return type of a method, consider using `Ret<M>` where `M` is the method name (e.g. `Opts<'getMe'>`).
```ts
// The adjusted `InputMedia*` types:
type InputMedia = Telegram.InputMedia<MyInputFile>;
type InputMediaPhoto = Telegram.InputMediaPhoto<MyInputFile>;
type InputMediaVideo = Telegram.InputMediaVideo<MyInputFile>;
type InputMediaAnimation = Telegram.InputMediaAnimation<MyInputFile>;
type InputMediaAudio = Telegram.InputMediaAudio<MyInputFile>;
type InputMediaDocument = Telegram.InputMediaDocument<MyInputFile>;
```
Note that interfaces other than the ones mentioned above are unaffected by the customization through `MyInputFile`.
They can simply continue to be imported directly.
## Development
This project is written for Deno and built for Node. Running `npm prepare` runs the deno2node script to build for Node.
## Where do the types come from
They're handwritten. Typegram was started by [@KnorpelSenf](https://github.com/KnorpelSenf), who eventually used it as a starting point for [the grammY types package](https://github.com/grammyjs/types). `@telegraf/types` is based on both packages, and regularly syncs with them and the Bot API.

22
node_modules/@telegraf/types/api.d.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
export interface ApiError {
ok: false;
error_code: number;
description: string;
parameters?: ResponseParameters;
}
export interface ApiSuccess<T> {
ok: true;
result: T;
}
/** The response contains an object, which always has a Boolean field 'ok' and may have an optional String field 'description' with a human-readable description of the result. If 'ok' equals true, the request was successful and the result of the query can be found in the 'result' field. In case of an unsuccessful request, 'ok' equals false and the error is explained in the 'description'. An Integer 'error_code' field is also returned, but its contents are subject to change in the future. Some errors may also have an optional field 'parameters' of the type ResponseParameters, which can help to automatically handle the error.
All methods in the Bot API are case-insensitive.
All queries must be made using UTF-8. */
export type ApiResponse<T> = ApiError | ApiSuccess<T>;
/** Describes why a request was unsuccessful. */
export interface ResponseParameters {
/** The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. */
migrate_to_chat_id?: number;
/** In case of exceeding flood control, the number of seconds left to wait before the request can be repeated */
retry_after?: number;
}

40
node_modules/@telegraf/types/default.d.ts generated vendored Normal file
View File

@@ -0,0 +1,40 @@
import { Typegram } from "./proxied";
/** This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser. */
export type InputFile = never;
type DefaultTypegram = Typegram<InputFile>;
/** Wrapper type to bundle all methods of the Telegram API */
export type Telegram = DefaultTypegram["Telegram"];
/** Utility type providing the argument type for the given method name or `{}` if the method does not take any parameters */
export type Opts<M extends keyof DefaultTypegram["Telegram"]> =
DefaultTypegram["Opts"][M];
export type Ret<M extends keyof DefaultTypegram["Telegram"]> =
DefaultTypegram["Ret"][M];
/** Utility type providing a promisified version of Telegram */
export type TelegramP = DefaultTypegram["TelegramP"];
/** Utility type providing a version Telegram where all methods return ApiResponse objects instead of raw data */
export type TelegramR = DefaultTypegram["TelegramR"];
/** Utility type providing a version Telegram where all methods return Promises of ApiResponse objects, combination of TelegramP and TelegramR */
export type TelegramPR = DefaultTypegram["TelegramPR"];
/** This object represents the content of a media message to be sent. It should be one of
- InputMediaAnimation
- InputMediaDocument
- InputMediaAudio
- InputMediaPhoto
- InputMediaVideo */
export type InputMedia = DefaultTypegram["InputMedia"];
/** Represents a photo to be sent. */
export type InputMediaPhoto = DefaultTypegram["InputMediaPhoto"];
/** Represents a video to be sent. */
export type InputMediaVideo = DefaultTypegram["InputMediaVideo"];
/** Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. */
export type InputMediaAnimation = DefaultTypegram["InputMediaAnimation"];
/** Represents an audio file to be treated as music to be sent. */
export type InputMediaAudio = DefaultTypegram["InputMediaAudio"];
/** Represents a general file to be sent. */
export type InputMediaDocument = DefaultTypegram["InputMediaDocument"];

10
node_modules/@telegraf/types/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
export * from "./api.js";
export * from "./inline.js";
export * from "./manage.js";
export * from "./markup.js";
export * from "./message.js";
export * from "./methods.js";
export * from "./passport.js";
export * from "./payment.js";
export * from "./settings.js";
export * from "./update.js";

697
node_modules/@telegraf/types/inline.d.ts generated vendored Normal file
View File

@@ -0,0 +1,697 @@
import type { Chat, User } from "./manage.js";
import type { InlineKeyboardMarkup, WebAppInfo } from "./markup.js";
import type { Location, MessageEntity, ParseMode } from "./message.js";
import type { LabeledPrice } from "./payment.js";
/** This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. */
export interface InlineQuery {
/** Unique identifier for this query */
id: string;
/** Sender */
from: User;
/** Text of the query (up to 256 characters) */
query: string;
/** Offset of the results to be returned, can be controlled by the bot */
offset: string;
/** Type of the chat from which the inline query was sent. Can be either “sender” for a private chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”. The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat */
chat_type?: "sender" | Chat["type"];
/** Sender location, only for bots that request user location */
location?: Location;
}
/** This object represents one result of an inline query. Telegram clients currently support results of the following 20 types:
- InlineQueryResultCachedAudio
- InlineQueryResultCachedDocument
- InlineQueryResultCachedGif
- InlineQueryResultCachedMpeg4Gif
- InlineQueryResultCachedPhoto
- InlineQueryResultCachedSticker
- InlineQueryResultCachedVideo
- InlineQueryResultCachedVoice
- InlineQueryResultArticle
- InlineQueryResultAudio
- InlineQueryResultContact
- InlineQueryResultGame
- InlineQueryResultDocument
- InlineQueryResultGif
- InlineQueryResultLocation
- InlineQueryResultMpeg4Gif
- InlineQueryResultPhoto
- InlineQueryResultVenue
- InlineQueryResultVideo
- InlineQueryResultVoice
Note: All URLs passed in inline query results will be available to end users and therefore must be assumed to be public. */
export type InlineQueryResult = InlineQueryResultCachedAudio | InlineQueryResultCachedDocument | InlineQueryResultCachedGif | InlineQueryResultCachedMpeg4Gif | InlineQueryResultCachedPhoto | InlineQueryResultCachedSticker | InlineQueryResultCachedVideo | InlineQueryResultCachedVoice | InlineQueryResultArticle | InlineQueryResultAudio | InlineQueryResultContact | InlineQueryResultGame | InlineQueryResultDocument | InlineQueryResultGif | InlineQueryResultLocation | InlineQueryResultMpeg4Gif | InlineQueryResultPhoto | InlineQueryResultVenue | InlineQueryResultVideo | InlineQueryResultVoice;
/** Represents a link to an article or web page. */
export interface InlineQueryResultArticle {
/** Type of the result, must be article */
type: "article";
/** Unique identifier for this result, 1-64 Bytes */
id: string;
/** Title of the result */
title: string;
/** Content of the message to be sent */
input_message_content: InputMessageContent;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** URL of the result */
url?: string;
/** Pass True if you don't want the URL to be shown in the message */
hide_url?: boolean;
/** Short description of the result */
description?: string;
/** Url of the thumbnail for the result */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. */
export interface InlineQueryResultPhoto {
/** Type of the result, must be photo */
type: "photo";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB */
photo_url: string;
/** URL of the thumbnail for the photo */
thumbnail_url: string;
/** Width of the photo */
photo_width?: number;
/** Height of the photo */
photo_height?: number;
/** Title for the result */
title?: string;
/** Short description of the result */
description?: string;
/** Caption of the photo to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the photo caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the photo */
input_message_content?: InputMessageContent;
}
/** Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. */
export interface InlineQueryResultGif {
/** Type of the result, must be gif */
type: "gif";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the GIF file. File size must not exceed 1MB */
gif_url: string;
/** Width of the GIF */
gif_width?: number;
/** Height of the GIF */
gif_height?: number;
/** Duration of the GIF in seconds */
gif_duration?: number;
/** URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result */
thumbnail_url: string;
/** MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” */
thumbnail_mime_type?: "image/jpeg" | "image/gif" | "video/mp4";
/** Title for the result */
title?: string;
/** Caption of the GIF file to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the GIF animation */
input_message_content?: InputMessageContent;
}
/** Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. */
export interface InlineQueryResultMpeg4Gif {
/** Type of the result, must be mpeg4_gif */
type: "mpeg4_gif";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the MPEG4 file. File size must not exceed 1MB */
mpeg4_url: string;
/** Video width */
mpeg4_width?: number;
/** Video height */
mpeg4_height?: number;
/** Video duration in seconds */
mpeg4_duration?: number;
/** URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result */
thumbnail_url: string;
/** MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” */
thumbnail_mime_type?: "image/jpeg" | "image/gif" | "video/mp4";
/** Title for the result */
title?: string;
/** Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the video animation */
input_message_content?: InputMessageContent;
}
/** Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.
> If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content. */
export interface InlineQueryResultVideo {
/** Type of the result, must be video */
type: "video";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the embedded video player or video file */
video_url: string;
/** MIME type of the content of the video URL, “text/html” or “video/mp4” */
mime_type: "text/html" | "video/mp4";
/** URL of the thumbnail (JPEG only) for the video */
thumbnail_url: string;
/** Title for the result */
title: string;
/** Caption of the video to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the video caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Video width */
video_width?: number;
/** Video height */
video_height?: number;
/** Video duration in seconds */
video_duration?: number;
/** Short description of the result */
description?: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video). */
input_message_content?: InputMessageContent;
}
/** Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultAudio {
/** Type of the result, must be audio */
type: "audio";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the audio file */
audio_url: string;
/** Title */
title: string;
/** Caption, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the audio caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Performer */
performer?: string;
/** Audio duration in seconds */
audio_duration?: number;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the audio */
input_message_content?: InputMessageContent;
}
/** Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultVoice {
/** Type of the result, must be voice */
type: "voice";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid URL for the voice recording */
voice_url: string;
/** Recording title */
title: string;
/** Caption, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the voice message caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Recording duration in seconds */
voice_duration?: number;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the voice recording */
input_message_content?: InputMessageContent;
}
/** Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultDocument {
/** Type of the result, must be document */
type: "document";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** Title for the result */
title: string;
/** Caption of the document to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the document caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** A valid URL for the file */
document_url: string;
/** MIME type of the content of the file, either “application/pdf” or “application/zip” */
mime_type: "application/pdf" | "application/zip";
/** Short description of the result */
description?: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the file */
input_message_content?: InputMessageContent;
/** URL of the thumbnail (JPEG only) for the file */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultLocation {
/** Type of the result, must be location */
type: "location";
/** Unique identifier for this result, 1-64 Bytes */
id: string;
/** Location latitude in degrees */
latitude: number;
/** Location longitude in degrees */
longitude: number;
/** Location title */
title: string;
/** The radius of uncertainty for the location, measured in meters; 0-1500 */
horizontal_accuracy?: number;
/** Period in seconds for which the location can be updated, should be between 60 and 86400. */
live_period?: number;
/** For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. */
heading?: number;
/** For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */
proximity_alert_radius?: number;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the location */
input_message_content?: InputMessageContent;
/** Url of the thumbnail for the result */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultVenue {
/** Type of the result, must be venue */
type: "venue";
/** Unique identifier for this result, 1-64 Bytes */
id: string;
/** Latitude of the venue location in degrees */
latitude: number;
/** Longitude of the venue location in degrees */
longitude: number;
/** Title of the venue */
title: string;
/** Address of the venue */
address: string;
/** Foursquare identifier of the venue if known */
foursquare_id?: string;
/** Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) */
foursquare_type?: string;
/** Google Places identifier of the venue */
google_place_id?: string;
/** Google Places type of the venue. (See supported types.) */
google_place_type?: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the venue */
input_message_content?: InputMessageContent;
/** Url of the thumbnail for the result */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultContact {
/** Type of the result, must be contact */
type: "contact";
/** Unique identifier for this result, 1-64 Bytes */
id: string;
/** Contact's phone number */
phone_number: string;
/** Contact's first name */
first_name: string;
/** Contact's last name */
last_name?: string;
/** Additional data about the contact in the form of a vCard, 0-2048 bytes */
vcard?: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the contact */
input_message_content?: InputMessageContent;
/** Url of the thumbnail for the result */
thumbnail_url?: string;
/** Thumbnail width */
thumbnail_width?: number;
/** Thumbnail height */
thumbnail_height?: number;
}
/** Represents a Game.
Note: This will only work in Telegram versions released after October 1, 2016. Older clients will not display any inline results if a game result is among them. */
export interface InlineQueryResultGame {
/** Type of the result, must be game */
type: "game";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** Short name of the game */
game_short_name: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
}
/** Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. */
export interface InlineQueryResultCachedPhoto {
/** Type of the result, must be photo */
type: "photo";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier of the photo */
photo_file_id: string;
/** Title for the result */
title?: string;
/** Short description of the result */
description?: string;
/** Caption of the photo to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the photo caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the photo */
input_message_content?: InputMessageContent;
}
/** Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation. */
export interface InlineQueryResultCachedGif {
/** Type of the result, must be gif */
type: "gif";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the GIF file */
gif_file_id: string;
/** Title for the result */
title?: string;
/** Caption of the GIF file to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the GIF animation */
input_message_content?: InputMessageContent;
}
/** Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. */
export interface InlineQueryResultCachedMpeg4Gif {
/** Type of the result, must be mpeg4_gif */
type: "mpeg4_gif";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the MPEG4 file */
mpeg4_file_id: string;
/** Title for the result */
title?: string;
/** Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the video animation */
input_message_content?: InputMessageContent;
}
/** Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker.
Note: This will only work in Telegram versions released after 9 April, 2016 for static stickers and after 06 July, 2019 for animated stickers. Older clients will ignore them. */
export interface InlineQueryResultCachedSticker {
/** Type of the result, must be sticker */
type: "sticker";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier of the sticker */
sticker_file_id: string;
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the sticker */
input_message_content?: InputMessageContent;
}
/** Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultCachedDocument {
/** Type of the result, must be document */
type: "document";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** Title for the result */
title: string;
/** A valid file identifier for the file */
document_file_id: string;
/** Short description of the result */
description?: string;
/** Caption of the document to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the document caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the file */
input_message_content?: InputMessageContent;
}
/** Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. */
export interface InlineQueryResultCachedVideo {
/** Type of the result, must be video */
type: "video";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the video file */
video_file_id: string;
/** Title for the result */
title: string;
/** Short description of the result */
description?: string;
/** Caption of the video to be sent, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the video caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the video */
input_message_content?: InputMessageContent;
}
/** Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultCachedVoice {
/** Type of the result, must be voice */
type: "voice";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the voice message */
voice_file_id: string;
/** Voice message title */
title: string;
/** Caption, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the voice message caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the voice message */
input_message_content?: InputMessageContent;
}
/** Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. */
export interface InlineQueryResultCachedAudio {
/** Type of the result, must be audio */
type: "audio";
/** Unique identifier for this result, 1-64 bytes */
id: string;
/** A valid file identifier for the audio file */
audio_file_id: string;
/** Caption, 0-1024 characters after entities parsing */
caption?: string;
/** Mode for parsing entities in the audio caption. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[];
/** Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup;
/** Content of the message to be sent instead of the audio */
input_message_content?: InputMessageContent;
}
/** This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following 5 types:
- InputTextMessageContent
- InputLocationMessageContent
- InputVenueMessageContent
- InputContactMessageContent
- InputInvoiceMessageContent */
export type InputMessageContent = InputTextMessageContent | InputLocationMessageContent | InputVenueMessageContent | InputContactMessageContent | InputInvoiceMessageContent;
/** Represents the content of a text message to be sent as the result of an inline query. */
export interface InputTextMessageContent {
/** Text of the message to be sent, 1-4096 characters */
message_text: string;
/** Mode for parsing entities in the message text. See formatting options for more details. */
parse_mode?: ParseMode;
/** List of special entities that appear in message text, which can be specified instead of parse_mode */
entities?: MessageEntity[];
/** Disables link previews for links in the sent message */
disable_web_page_preview?: boolean;
}
/** Represents the content of a location message to be sent as the result of an inline query. */
export interface InputLocationMessageContent {
/** Latitude of the location in degrees */
latitude: number;
/** Longitude of the location in degrees */
longitude: number;
/** The radius of uncertainty for the location, measured in meters; 0-1500 */
horizontal_accuracy?: number;
/** Period in seconds for which the location can be updated, should be between 60 and 86400. */
live_period?: number;
/** For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. */
heading?: number;
/** For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */
proximity_alert_radius?: number;
}
/** Represents the content of a venue message to be sent as the result of an inline query. */
export interface InputVenueMessageContent {
/** Latitude of the venue in degrees */
latitude: number;
/** Longitude of the venue in degrees */
longitude: number;
/** Name of the venue */
title: string;
/** Address of the venue */
address: string;
/** Foursquare identifier of the venue, if known */
foursquare_id?: string;
/** Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) */
foursquare_type?: string;
/** Google Places identifier of the venue */
google_place_id?: string;
/** Google Places type of the venue. (See supported types.) */
google_place_type?: string;
}
/** Represents the content of a contact message to be sent as the result of an inline query. */
export interface InputContactMessageContent {
/** Contact's phone number */
phone_number: string;
/** Contact's first name */
first_name: string;
/** Contact's last name */
last_name?: string;
/** Additional data about the contact in the form of a vCard, 0-2048 bytes */
vcard?: string;
}
/** Represents the content of an invoice message to be sent as the result of an inline query. */
export interface InputInvoiceMessageContent {
/** Product name, 1-32 characters */
title: string;
/** Product description, 1-255 characters */
description: string;
/** Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. */
payload: string;
/** Payment provider token, obtained via BotFather */
provider_token: string;
/** Three-letter ISO 4217 currency code, see more on currencies */
currency: string;
/** Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) */
prices: LabeledPrice[];
/** The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0 */
max_tip_amount?: number;
/** An array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. */
suggested_tip_amounts?: number[];
/** Data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider. */
provider_data?: string;
/** URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. */
photo_url?: string;
/** Photo size in bytes */
photo_size?: number;
/** Photo width */
photo_width?: number;
/** Photo height */
photo_height?: number;
/** Pass True if you require the user's full name to complete the order */
need_name?: boolean;
/** Pass True if you require the user's phone number to complete the order */
need_phone_number?: boolean;
/** Pass True if you require the user's email address to complete the order */
need_email?: boolean;
/** Pass True if you require the user's shipping address to complete the order */
need_shipping_address?: boolean;
/** Pass True if the user's phone number should be sent to provider */
send_phone_number_to_provider?: boolean;
/** Pass True if the user's email address should be sent to provider */
send_email_to_provider?: boolean;
/** Pass True if the final price depends on the shipping method */
is_flexible?: boolean;
}
/** Represents a result of an inline query that was chosen by the user and sent to their chat partner.
Note: It is necessary to enable inline feedback via @BotFather in order to receive these objects in updates. */
export interface ChosenInlineResult {
/** The unique identifier for the result that was chosen */
result_id: string;
/** The user that chose the result */
from: User;
/** Sender location, only for bots that require user location */
location?: Location;
/** Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message. */
inline_message_id?: string;
/** The query that was used to obtain the result */
query: string;
}
export interface AbstractInlineQueryResultsButton {
/** Label text on the button */
text: string;
}
export interface InlineQueryResultsWebAppButton extends AbstractInlineQueryResultsButton {
/** Description of the Web App that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method web_app_switch_inline_query inside the Web App. */
web_app: WebAppInfo;
}
export interface InlineQueryResultsStartButton extends AbstractInlineQueryResultsButton {
/** Deep-linking parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed. */
start_parameter: string;
}
/** This object represents a button to be shown above inline query results.
Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. */
export type InlineQueryResultsButton = InlineQueryResultsWebAppButton | InlineQueryResultsStartButton;

459
node_modules/@telegraf/types/manage.d.ts generated vendored Normal file
View File

@@ -0,0 +1,459 @@
import type { Location, Message, PhotoSize } from "./message.js";
/** Describes the current status of a webhook. */
export interface WebhookInfo {
/** Webhook URL, may be empty if webhook is not set up */
url?: string;
/** True, if a custom certificate was provided for webhook certificate checks */
has_custom_certificate: boolean;
/** Number of updates awaiting delivery */
pending_update_count: number;
/** Currently used webhook IP address */
ip_address?: string;
/** Unix time for the most recent error that happened when trying to deliver an update via webhook */
last_error_date?: number;
/** Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook */
last_error_message?: string;
/** Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters */
last_synchronization_error_date?: number;
/** The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery */
max_connections?: number;
/** A list of update types the bot is subscribed to. Defaults to all update types except chat_member */
allowed_updates?: string[];
}
/** This object represents a Telegram user or bot. */
export interface User {
/** Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. */
id: number;
/** True, if this user is a bot */
is_bot: boolean;
/** User's or bot's first name */
first_name: string;
/** User's or bot's last name */
last_name?: string;
/** User's or bot's username */
username?: string;
/** IETF language tag of the user's language */
language_code?: string;
/** True, if this user is a Telegram Premium user */
is_premium?: true;
/** True, if this user added the bot to the attachment menu */
added_to_attachment_menu?: true;
}
/** This object represents a Telegram user or bot that was returned by `getMe`. */
export interface UserFromGetMe extends User {
is_bot: true;
username: string;
/** True, if the bot can be invited to groups. Returned only in getMe. */
can_join_groups: boolean;
/** True, if privacy mode is disabled for the bot. Returned only in getMe. */
can_read_all_group_messages: boolean;
/** True, if the bot supports inline queries. Returned only in getMe. */
supports_inline_queries: boolean;
}
export declare namespace Chat {
/** Internal type holding properties that all kinds of chats share. */
interface AbstractChat {
/** Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. */
id: number;
/** Type of chat, can be either “private”, “group”, “supergroup” or “channel” */
type: string;
}
/** Internal type holding properties that those chats with user names share. */
interface UserNameChat {
/** Username, for private chats, supergroups and channels if available */
username?: string;
}
/** Internal type holding properties that those chats with titles share. */
interface TitleChat {
/** Title, for supergroups, channels and group chats */
title: string;
}
/** Internal type representing private chats. */
interface PrivateChat extends AbstractChat, UserNameChat {
type: "private";
/** First name of the other party in a private chat */
first_name: string;
/** Last name of the other party in a private chat */
last_name?: string;
}
/** Internal type representing group chats. */
interface GroupChat extends AbstractChat, TitleChat {
type: "group";
}
/** Internal type representing super group chats. */
interface SupergroupChat extends AbstractChat, UserNameChat, TitleChat {
type: "supergroup";
/** True, if the supergroup chat is a forum (has topics enabled) */
is_forum?: true;
}
/** Internal type representing channel chats. */
interface ChannelChat extends AbstractChat, UserNameChat, TitleChat {
type: "channel";
}
/** Internal type holding properties that those chats returned from `getChat` share. */
interface GetChat {
/** Chat photo. Returned only in getChat. */
photo?: ChatPhoto;
/** The most recent pinned message (by sending date). Returned only in getChat. */
pinned_message?: Message;
/** The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in getChat. */
message_auto_delete_time?: number;
/** True, if messages from the chat can't be forwarded to other chats. Returned only in getChat. */
has_protected_content?: true;
}
/** Internal type holding properties that those private, supergroup, and channel chats returned from `getChat` share. */
interface NonGroupGetChat extends GetChat {
/** If non-empty, the list of all active chat usernames; for private chats, supergroups and channels. Returned only in getChat. */
active_usernames?: string[];
}
/** Internal type holding properties that those group, supergroup, and channel chats returned from `getChat` share. */
interface NonPrivateGetChat extends GetChat {
/** Description, for groups, supergroups and channel chats. Returned only in getChat. */
description?: string;
/** Primary invite link, for groups, supergroups and channel chats. Returned only in getChat. */
invite_link?: string;
}
/** Internal type holding properties that those group and supergroup chats returned from `getChat` share. */
interface MultiUserGetChat extends NonPrivateGetChat {
/** Default chat member permissions, for groups and supergroups. Returned only in getChat. */
permissions?: ChatPermissions;
/** True, if the bot can change the group sticker set. Returned only in getChat. */
can_set_sticker_set?: true;
}
/** Internal type holding properties that those supergroup and channel chats returned from `getChat` share. */
interface LargeGetChat extends NonPrivateGetChat {
/** Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. Returned only in getChat. */
linked_chat_id?: number;
}
/** Internal type representing private chats returned from `getChat`. */
interface PrivateGetChat extends PrivateChat, NonGroupGetChat, GetChat {
/** Custom emoji identifier of emoji status of the other party in a private chat. Returned only in getChat. */
emoji_status_custom_emoji_id?: string;
/** Expiration date of the emoji status of the other party in a private chat in Unix time, if any. Returned only in getChat. */
emoji_status_expiration_date?: number;
/** Bio of the other party in a private chat. Returned only in getChat. */
bio?: string;
/** True, if privacy settings of the other party in the private chat allows to use tg://user?id=<user_id> links only in chats with the user. Returned only in getChat. */
has_private_forwards?: true;
/** True, if the privacy settings of the other party restrict sending voice and video note messages in the private chat. Returned only in getChat. */
has_restricted_voice_and_video_messages?: true;
}
/** Internal type representing group chats returned from `getChat`. */
interface GroupGetChat extends GroupChat, MultiUserGetChat {
}
/** Internal type representing supergroup chats returned from `getChat`. */
interface SupergroupGetChat extends SupergroupChat, NonGroupGetChat, MultiUserGetChat, LargeGetChat {
/** True, if users need to join the supergroup before they can send messages. Returned only in getChat. */
join_to_send_messages?: true;
/** True, if all users directly joining the supergroup need to be approved by supergroup administrators. Returned only in getChat. */
join_by_request?: true;
/** For supergroups, the minimum allowed delay between consecutive messages sent by each unpriviledged user; in seconds. Returned only in getChat. */
slow_mode_delay?: number;
/** True, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators. Returned only in getChat. */
has_aggressive_anti_spam_enabled?: true;
/** For supergroups, name of group sticker set. Returned only in getChat. */
sticker_set_name?: string;
/** For supergroups, the location to which the supergroup is connected. Returned only in getChat. */
location?: ChatLocation;
}
/** Internal type representing channel chats returned from `getChat`. */
interface ChannelGetChat extends ChannelChat, NonGroupGetChat, LargeGetChat {
}
}
/** This object represents a chat. */
export type Chat = Chat.PrivateChat | Chat.GroupChat | Chat.SupergroupChat | Chat.ChannelChat;
/** This object represents a Telegram user or bot that was returned by `getChat`. */
export type ChatFromGetChat = Chat.PrivateGetChat | Chat.GroupGetChat | Chat.SupergroupGetChat | Chat.ChannelGetChat;
/** This object represent a user's profile pictures. */
export interface UserProfilePhotos {
/** Total number of profile pictures the target user has */
total_count: number;
/** Requested profile pictures (in up to 4 sizes each) */
photos: PhotoSize[][];
}
/** This object represents a chat photo. */
export interface ChatPhoto {
/** File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed. */
small_file_id: string;
/** Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
small_file_unique_id: string;
/** File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed. */
big_file_id: string;
/** Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
big_file_unique_id: string;
}
/** Represents an invite link for a chat. */
export interface ChatInviteLink {
/** The invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with “…”. */
invite_link: string;
/** Creator of the link */
creator: User;
/** True, if users joining the chat via the link need to be approved by chat administrators */
creates_join_request: boolean;
/** True, if the link is primary */
is_primary: boolean;
/** True, if the link is revoked */
is_revoked: boolean;
/** Invite link name */
name?: string;
/** Point in time (Unix timestamp) when the link will expire or has been expired */
expire_date?: number;
/** The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 */
member_limit?: number;
/** Number of pending join requests created using this link */
pending_join_request_count?: number;
}
/** Represents the rights of an administrator in a chat. */
export interface ChatAdministratorRights {
/** True, if the user's presence in the chat is hidden */
is_anonymous: boolean;
/** True, if the administrator can access the chat event log, chat statistics, message statistics in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other administrator privilege */
can_manage_chat: boolean;
/** True, if the administrator can delete messages of other users */
can_delete_messages: boolean;
/** True, if the administrator can manage video chats */
can_manage_video_chats: boolean;
/** True, if the administrator can restrict, ban or unban chat members */
can_restrict_members: boolean;
/** True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user) */
can_promote_members: boolean;
/** True, if the user is allowed to change the chat title, photo and other settings */
can_change_info: boolean;
/** True, if the user is allowed to invite new users to the chat */
can_invite_users: boolean;
/** True, if the administrator can post in the channel; channels only */
can_post_messages?: boolean;
/** True, if the administrator can edit messages of other users and can pin messages; channels only */
can_edit_messages?: boolean;
/** True, if the user is allowed to pin messages; groups and supergroups only */
can_pin_messages?: boolean;
/** True, if the administrator can post stories in the channel; channels only */
can_post_stories?: boolean;
/** True, if the administrator can edit stories posted by other users; channels only */
can_edit_stories?: boolean;
/** True, if the administrator can delete stories posted by other users */
can_delete_stories?: boolean;
/** True, if the user is allowed to create, rename, close, and reopen forum topics; supergroups only */
can_manage_topics?: boolean;
}
/** This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported:
- ChatMemberOwner
- ChatMemberAdministrator
- ChatMemberMember
- ChatMemberRestricted
- ChatMemberLeft
- ChatMemberBanned */
export type ChatMember = ChatMemberOwner | ChatMemberAdministrator | ChatMemberMember | ChatMemberRestricted | ChatMemberLeft | ChatMemberBanned;
/** Represents a chat member that owns the chat and has all administrator privileges. */
export interface ChatMemberOwner {
/** The member's status in the chat, always “creator” */
status: "creator";
/** Information about the user */
user: User;
/** True, if the user's presence in the chat is hidden */
is_anonymous: boolean;
/** Custom title for this user */
custom_title?: string;
}
/** Represents a chat member that has some additional privileges. */
export interface ChatMemberAdministrator {
/** The member's status in the chat, always “administrator” */
status: "administrator";
/** Information about the user */
user: User;
/** True, if the bot is allowed to edit administrator privileges of that user */
can_be_edited: boolean;
/** True, if the user's presence in the chat is hidden */
is_anonymous: boolean;
/** True, if the administrator can access the chat event log, chat statistics, message statistics in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other administrator privilege */
can_manage_chat: boolean;
/** True, if the administrator can delete messages of other users */
can_delete_messages: boolean;
/** True, if the administrator can manage video chats */
can_manage_video_chats: boolean;
/** True, if the administrator can restrict, ban or unban chat members */
can_restrict_members: boolean;
/** True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user) */
can_promote_members: boolean;
/** True, if the user is allowed to change the chat title, photo and other settings */
can_change_info: boolean;
/** True, if the user is allowed to invite new users to the chat */
can_invite_users: boolean;
/** True, if the administrator can post in the channel; channels only */
can_post_messages?: boolean;
/** True, if the administrator can edit messages of other users and can pin messages; channels only */
can_edit_messages?: boolean;
/** True, if the user is allowed to pin messages; groups and supergroups only */
can_pin_messages?: boolean;
/** True, if the administrator can post stories in the channel; channels only */
can_post_stories?: boolean;
/** True, if the administrator can edit stories posted by other users; channels only */
can_edit_stories?: boolean;
/** True, if the administrator can delete stories posted by other users */
can_delete_stories?: boolean;
/** True, if the user is allowed to create, rename, close, and reopen forum topics; supergroups only */
can_manage_topics?: boolean;
/** Custom title for this user */
custom_title?: string;
}
/** Represents a chat member that has no additional privileges or restrictions. */
export interface ChatMemberMember {
/** The member's status in the chat, always “member” */
status: "member";
/** Information about the user */
user: User;
}
/** Represents a chat member that is under certain restrictions in the chat. Supergroups only. */
export interface ChatMemberRestricted {
/** The member's status in the chat, always “restricted” */
status: "restricted";
/** Information about the user */
user: User;
/** True, if the user is a member of the chat at the moment of the request */
is_member: boolean;
/** True, if the user is allowed to send text messages, contacts, invoices, locations and venues */
can_send_messages: boolean;
/** True, if the user is allowed to send audios */
can_send_audios: boolean;
/** True, if the user is allowed to send documents */
can_send_documents: boolean;
/** True, if the user is allowed to send photos */
can_send_photos: boolean;
/** True, if the user is allowed to send videos */
can_send_videos: boolean;
/** True, if the user is allowed to send video notes */
can_send_video_notes: boolean;
/** True, if the user is allowed to send voice notes */
can_send_voice_notes: boolean;
/** True, if the user is allowed to send polls */
can_send_polls: boolean;
/** True, if the user is allowed to send animations, games, stickers and use inline bots */
can_send_other_messages: boolean;
/** True, if the user is allowed to add web page previews to their messages */
can_add_web_page_previews: boolean;
/** True, if the user is allowed to change the chat title, photo and other settings */
can_change_info: boolean;
/** True, if the user is allowed to invite new users to the chat */
can_invite_users: boolean;
/** True, if the user is allowed to pin messages */
can_pin_messages: boolean;
/** True, if the user is allowed to create forum topics */
can_manage_topics: boolean;
/** Date when restrictions will be lifted for this user; Unix time. If 0, then the user is restricted forever */
until_date: number;
}
/** Represents a chat member that isn't currently a member of the chat, but may join it themselves. */
export interface ChatMemberLeft {
/** The member's status in the chat, always “left” */
status: "left";
/** Information about the user */
user: User;
}
/** Represents a chat member that was banned in the chat and can't return to the chat or view chat messages. */
export interface ChatMemberBanned {
/** The member's status in the chat, always “kicked” */
status: "kicked";
/** Information about the user */
user: User;
/** Date when restrictions will be lifted for this user; Unix time. If 0, then the user is banned forever */
until_date: number;
}
/** This object represents changes in the status of a chat member. */
export interface ChatMemberUpdated {
/** Chat the user belongs to */
chat: Chat;
/** Performer of the action, which resulted in the change */
from: User;
/** Date the change was done in Unix time */
date: number;
/** Previous information about the chat member */
old_chat_member: ChatMember;
/** New information about the chat member */
new_chat_member: ChatMember;
/** Chat invite link, which was used by the user to join the chat; for joining by invite link events only. */
invite_link?: ChatInviteLink;
/** True, if the user joined the chat via a chat folder invite link */
via_chat_folder_invite_link?: boolean;
}
/** Represents a join request sent to a chat. */
export interface ChatJoinRequest {
/** Chat to which the request was sent */
chat: Chat.SupergroupChat | Chat.ChannelChat;
/** User that sent the join request */
from: User;
/** Identifier of a private chat with the user who sent the join request. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot can use this identifier for 24 hours to send messages until the join request is processed, assuming no other administrator contacted the user. */
user_chat_id: number;
/** Date the request was sent in Unix time */
date: number;
/** Bio of the user. */
bio?: string;
/** Chat invite link that was used by the user to send the join request */
invite_link?: ChatInviteLink;
}
/** Describes actions that a non-administrator user is allowed to take in a chat. */
export interface ChatPermissions {
/** True, if the user is allowed to send text messages, contacts, invoices, locations and venues */
can_send_messages?: boolean;
/** True, if the user is allowed to send audios */
can_send_audios?: boolean;
/** True, if the user is allowed to send documents */
can_send_documents?: boolean;
/** True, if the user is allowed to send photos */
can_send_photos?: boolean;
/** True, if the user is allowed to send videos */
can_send_videos?: boolean;
/** True, if the user is allowed to send video notes */
can_send_video_notes?: boolean;
/** True, if the user is allowed to send voice notes */
can_send_voice_notes?: boolean;
/** True, if the user is allowed to send polls */
can_send_polls?: boolean;
/** True, if the user is allowed to send animations, games, stickers and use inline bots */
can_send_other_messages?: boolean;
/** True, if the user is allowed to add web page previews to their messages */
can_add_web_page_previews?: boolean;
/** True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups */
can_change_info?: boolean;
/** True, if the user is allowed to invite new users to the chat */
can_invite_users?: boolean;
/** True, if the user is allowed to pin messages. Ignored in public supergroups */
can_pin_messages?: boolean;
/** True, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages */
can_manage_topics?: boolean;
}
/** Represents a location to which a chat is connected. */
export interface ChatLocation {
/** The location to which the supergroup is connected. Can't be a live location. */
location: Location;
/** Location address; 1-64 characters, as defined by the chat owner */
address: string;
}
/** This object represents a forum topic. */
export interface ForumTopic {
/** Unique identifier of the forum topic */
message_thread_id: number;
/** Name of the topic */
name: string;
/** Color of the topic icon in RGB format */
icon_color: number;
/** Unique identifier of the custom emoji shown as the topic icon */
icon_custom_emoji_id?: string;
}
/** This object represents a bot command. */
export interface BotCommand {
/** Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores. */
command: string;
/** Description of the command; 1-256 characters. */
description: string;
}
/** This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile. */
export interface File {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** File size in bytes */
file_size?: number;
/** File path. Use https://api.telegram.org/file/bot<token>/<file_path> to get the file. */
file_path?: string;
}

226
node_modules/@telegraf/types/markup.d.ts generated vendored Normal file
View File

@@ -0,0 +1,226 @@
import type { ChatAdministratorRights, User } from "./manage.js";
import type { Message } from "./message.js";
/** This object represents an inline keyboard that appears right next to the message it belongs to. */
export interface InlineKeyboardMarkup {
/** Array of button rows, each represented by an Array of InlineKeyboardButton objects */
inline_keyboard: InlineKeyboardButton[][];
}
export declare namespace InlineKeyboardButton {
interface AbstractInlineKeyboardButton {
/** Label text on the button */
text: string;
}
interface UrlButton extends AbstractInlineKeyboardButton {
/** HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id=<user_id> can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings. */
url: string;
}
interface CallbackButton extends AbstractInlineKeyboardButton {
/** Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes */
callback_data: string;
}
interface WebAppButton extends AbstractInlineKeyboardButton {
/** Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. */
web_app: WebAppInfo;
}
interface LoginButton extends AbstractInlineKeyboardButton {
/** An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget. */
login_url: LoginUrl;
}
interface SwitchInlineButton extends AbstractInlineKeyboardButton {
/** If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. Can be empty, in which case just the bot's username will be inserted. */
switch_inline_query: string;
}
interface SwitchInlineCurrentChatButton extends AbstractInlineKeyboardButton {
/** If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot's username will be inserted.
This offers a quick way for the user to open your bot in inline mode in the same chat good for selecting something from multiple options. */
switch_inline_query_current_chat: string;
}
interface SwitchInlineChosenChatButton extends AbstractInlineKeyboardButton {
/** If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field */
switch_inline_query_chosen_chat: SwitchInlineQueryChosenChat;
}
interface GameButton extends AbstractInlineKeyboardButton {
/** Description of the game that will be launched when the user presses the button.
NOTE: This type of button must always be the first button in the first row. */
callback_game: CallbackGame;
}
interface PayButton extends AbstractInlineKeyboardButton {
/** Specify True, to send a Pay button.
NOTE: This type of button must always be the first button in the first row and can only be used in invoice messages. */
pay: boolean;
}
}
/** This object represents one button of an inline keyboard. You must use exactly one of the optional fields. */
export type InlineKeyboardButton = InlineKeyboardButton.CallbackButton | InlineKeyboardButton.GameButton | InlineKeyboardButton.LoginButton | InlineKeyboardButton.PayButton | InlineKeyboardButton.SwitchInlineButton | InlineKeyboardButton.SwitchInlineCurrentChatButton | InlineKeyboardButton.SwitchInlineChosenChatButton | InlineKeyboardButton.UrlButton | InlineKeyboardButton.WebAppButton;
/** This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in.
Telegram apps support these buttons as of version 5.7. */
export interface LoginUrl {
/** An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data.
NOTE: You must always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization. */
url: string;
/** New text of the button in forwarded messages. */
forward_text?: string;
/** Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details. */
bot_username?: string;
/** Pass True to request the permission for your bot to send messages to the user. */
request_write_access?: boolean;
}
/** This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query. */
export interface SwitchInlineQueryChosenChat {
/** The default inline query to be inserted in the input field. If left empty, only the bot's username will be inserted */
query?: string;
/** True, if private chats with users can be chosen */
allow_user_chats?: boolean;
/** True, if private chats with bots can be chosen */
allow_bot_chats?: boolean;
/** True, if group and supergroup chats can be chosen */
allow_group_chats?: boolean;
/** True, if channel chats can be chosen */
allow_channel_chats?: boolean;
}
/** A placeholder, currently holds no information. Use BotFather to set up your game. */
export interface CallbackGame {
}
export declare namespace CallbackQuery {
interface AbstractQuery {
/** Unique identifier for this query */
id: string;
/** Sender */
from: User;
/** Message with the callback button that originated the query. Note that message content and message date will not be available if the message is too old */
message?: Message;
/** Identifier of the message sent via the bot in inline mode, that originated the query. */
inline_message_id?: string;
/** Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games. */
chat_instance: string;
}
interface DataQuery extends AbstractQuery {
/** Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data. */
data: string;
}
interface GameQuery extends AbstractQuery {
/** Short name of a Game to be returned, serves as the unique identifier for the game */
game_short_name: string;
}
}
/** This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.
NOTE: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters). */
export type CallbackQuery = CallbackQuery.DataQuery | CallbackQuery.GameQuery;
/** This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). */
export interface ReplyKeyboardMarkup {
/** Array of button rows, each represented by an Array of KeyboardButton objects */
keyboard: KeyboardButton[][];
/** Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to false, in which case the custom keyboard can be hidden and opened with a keyboard icon. */
is_persistent?: boolean;
/** Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. */
resize_keyboard?: boolean;
/** Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat the user can press a special button in the input field to see the custom keyboard again. Defaults to false. */
one_time_keyboard?: boolean;
/** The placeholder to be shown in the input field when the keyboard is active; 1-64 characters */
input_field_placeholder?: string;
/** Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard. */
selective?: boolean;
}
export declare namespace KeyboardButton {
interface CommonButton {
/** Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed */
text: string;
}
interface RequestUserButton extends CommonButton {
/** If specified, pressing the button will open a list of suitable users. Tapping on any user will send their identifier to the bot in a “user_shared” service message. Available in private chats only. */
request_user: KeyboardButtonRequestUser;
}
interface RequestChatButton extends CommonButton {
/** If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only. */
request_chat: KeyboardButtonRequestChat;
}
interface RequestContactButton extends CommonButton {
/** If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only. */
request_contact: boolean;
}
interface RequestLocationButton extends CommonButton {
/** If True, the user's current location will be sent when the button is pressed. Available in private chats only. */
request_location: boolean;
}
interface RequestPollButton extends CommonButton {
/** If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only. */
request_poll: KeyboardButtonPollType;
}
interface WebAppButton extends CommonButton {
/** If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only. */
web_app: WebAppInfo;
}
}
/** This object represents one button of the reply keyboard. For simple text buttons, String can be used instead of this object to specify the button text. The optional fields web_app, request_user, request_chat, request_contact, request_location, and request_poll are mutually exclusive. */
export type KeyboardButton = KeyboardButton.CommonButton | KeyboardButton.RequestUserButton | KeyboardButton.RequestChatButton | KeyboardButton.RequestContactButton | KeyboardButton.RequestLocationButton | KeyboardButton.RequestPollButton | KeyboardButton.WebAppButton | string;
/** This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed. */
export interface KeyboardButtonPollType {
/** If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type. */
type?: "quiz" | "regular";
}
/** Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). */
export interface ReplyKeyboardRemove {
/** Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup) */
remove_keyboard: true;
/** Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet. */
selective?: boolean;
}
/** Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode.
Example: A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll:
Explain the user how to send a command with parameters (e.g. /newpoll question answer1 answer2). May be appealing for hardcore users but lacks modern day polish.
Guide the user through a step-by-step process. 'Please send me your question', 'Cool, now let's add the first answer option', 'Great. Keep adding answer options, then send /done when you're ready'.
The last option is definitely more attractive. And if you use ForceReply in your bot's questions, it will receive the user's answers even if it only receives replies, commands and mentions - without any extra work for the user. */
export interface ForceReply {
/** Shows reply interface to the user, as if they manually selected the bot's message and tapped 'Reply' */
force_reply: true;
/** The placeholder to be shown in the input field when the reply is active; 1-64 characters */
input_field_placeholder?: string;
/** Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. */
selective?: boolean;
}
/** Describes a Web App. */
export interface WebAppInfo {
/** An HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps */
url: string;
}
/** This object defines the criteria used to request a suitable user. The identifier of the selected user will be shared with the bot when the corresponding button is pressed. */
export interface KeyboardButtonRequestUser {
/** Signed 32-bit identifier of the request, which will be received back in the UserShared object. Must be unique within the message */
request_id: number;
/** Pass True to request a bot, pass False to request a regular user. If not specified, no additional restrictions are applied. */
user_is_bot?: boolean;
/** Pass True to request a premium user, pass False to request a non-premium user. If not specified, no additional restrictions are applied. */
user_is_premium?: boolean;
}
/** This object defines the criteria used to request a suitable chat. The identifier of the selected chat will be shared with the bot when the corresponding button is pressed. */
export interface KeyboardButtonRequestChat {
/** Signed 32-bit identifier of the request, which will be received back in the ChatShared object. Must be unique within the message */
request_id: number;
/** Pass True to request a channel chat, pass False to request a group or a supergroup chat. */
chat_is_channel: boolean;
/** Pass True to request a forum supergroup, pass False to request a non-forum chat. If not specified, no additional restrictions are applied. */
chat_is_forum?: boolean;
/** Pass True to request a supergroup or a channel with a username, pass False to request a chat without a username. If not specified, no additional restrictions are applied. */
chat_has_username?: boolean;
/** Pass True to request a chat owned by the user. Otherwise, no additional restrictions are applied. */
chat_is_created?: boolean;
/** An object listing the required administrator rights of the user in the chat. The rights must be a superset of bot_administrator_rights. If not specified, no additional restrictions are applied. */
user_administrator_rights?: ChatAdministratorRights;
/** An object listing the required administrator rights of the bot in the chat. The rights must be a subset of user_administrator_rights. If not specified, no additional restrictions are applied. */
bot_administrator_rights?: ChatAdministratorRights;
/** Pass True to request a chat with the bot as a member. Otherwise, no additional restrictions are applied. */
bot_is_member?: boolean;
}

806
node_modules/@telegraf/types/message.d.ts generated vendored Normal file
View File

@@ -0,0 +1,806 @@
import type { Chat, File, User } from "./manage.js";
import type { InlineKeyboardMarkup } from "./markup.js";
import type { PassportData } from "./passport.js";
import type { Invoice, SuccessfulPayment } from "./payment.js";
export declare namespace Message {
interface ServiceMessage {
/** Unique message identifier inside this chat */
message_id: number;
/** Unique identifier of a message thread or a forum topic to which the message belongs; for supergroups only */
message_thread_id?: number;
/** Sender of the message; empty for messages sent to channels. For backward compatibility, the field contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat. */
from?: User;
/** Sender of the message, sent on behalf of a chat. For example, the channel itself for channel posts, the supergroup itself for messages from anonymous group administrators, the linked channel for messages automatically forwarded to the discussion group. For backward compatibility, the field from contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat. */
sender_chat?: Chat;
/** Date the message was sent in Unix time */
date: number;
/** Conversation the message belongs to */
chat: Chat;
/** True, if the message is sent to a forum topic */
is_topic_message?: boolean;
}
interface CommonMessage extends ServiceMessage {
/** For forwarded messages, sender of the original message */
forward_from?: User;
/** For messages forwarded from channels or from anonymous administrators, information about the original sender chat */
forward_from_chat?: Chat;
/** For messages forwarded from channels, identifier of the original message in the channel */
forward_from_message_id?: number;
/** For forwarded messages that were originally sent in channels or by an anonymous chat administrator, signature of the message sender if present */
forward_signature?: string;
/** Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages */
forward_sender_name?: string;
/** For forwarded messages, date the original message was sent in Unix time */
forward_date?: number;
/** True, if the message is a channel post that was automatically forwarded to the connected discussion group */
is_automatic_forward?: true;
/** For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. */
reply_to_message?: ReplyMessage;
/** Bot through which the message was sent */
via_bot?: User;
/** Date the message was last edited in Unix time */
edit_date?: number;
/** True, if the message can't be forwarded */
has_protected_content?: true;
/** Signature of the post author for messages in channels, or the custom title of an anonymous group administrator */
author_signature?: string;
/** Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons. */
reply_markup?: InlineKeyboardMarkup;
}
interface TextMessage extends CommonMessage {
/** For text messages, the actual UTF-8 text of the message */
text: string;
/** For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text */
entities?: MessageEntity[];
}
interface CaptionableMessage extends CommonMessage {
/** Caption for the animation, audio, document, photo, video or voice */
caption?: string;
/** For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption */
caption_entities?: MessageEntity[];
}
interface MediaMessage extends CaptionableMessage {
/** The unique identifier of a media message group this message belongs to */
media_group_id?: string;
/** True, if the message media is covered by a spoiler animation */
has_media_spoiler?: true;
}
interface AudioMessage extends MediaMessage {
/** Message is an audio file, information about the file */
audio: Audio;
}
interface DocumentMessage extends MediaMessage {
/** Message is a general file, information about the file */
document: Document;
}
interface AnimationMessage extends DocumentMessage {
/** Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set */
animation: Animation;
}
interface PhotoMessage extends MediaMessage {
/** Message is a photo, available sizes of the photo */
photo: PhotoSize[];
}
interface StickerMessage extends CommonMessage {
/** Message is a sticker, information about the sticker */
sticker: Sticker;
}
interface StoryMessage extends CommonMessage {
/** Message is a forwarded story. Currently holds no information */
story: Story;
}
interface VideoMessage extends MediaMessage {
/** Message is a video, information about the video */
video: Video;
}
interface VideoNoteMessage extends CommonMessage {
/** Message is a video note, information about the video message */
video_note: VideoNote;
}
interface VoiceMessage extends CaptionableMessage {
/** Message is a voice message, information about the file */
voice: Voice;
}
interface ContactMessage extends CommonMessage {
/** Message is a shared contact, information about the contact */
contact: Contact;
}
interface DiceMessage extends CommonMessage {
/** Message is a dice with random value */
dice: Dice;
}
interface GameMessage extends CommonMessage {
/** Message is a game, information about the game. More about games » */
game: Game;
}
interface PollMessage extends CommonMessage {
/** Message is a native poll, information about the poll */
poll: Poll;
}
interface LocationMessage extends CommonMessage {
/** Message is a shared location, information about the location */
location: Location;
}
interface VenueMessage extends LocationMessage {
/** Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set */
venue: Venue;
}
interface NewChatMembersMessage extends ServiceMessage {
/** New members that were added to the group or supergroup and information about them (the bot itself may be one of these members) */
new_chat_members: User[];
}
interface LeftChatMemberMessage extends ServiceMessage {
/** A member was removed from the group, information about them (this member may be the bot itself) */
left_chat_member: User;
}
interface NewChatTitleMessage extends ServiceMessage {
/** A chat title was changed to this value */
new_chat_title: string;
}
interface NewChatPhotoMessage extends ServiceMessage {
/** A chat photo was change to this value */
new_chat_photo: PhotoSize[];
}
interface DeleteChatPhotoMessage extends ServiceMessage {
/** Service message: the chat photo was deleted */
delete_chat_photo: true;
}
interface GroupChatCreatedMessage extends ServiceMessage {
/** Service message: the group has been created */
group_chat_created: true;
}
interface SupergroupChatCreated extends ServiceMessage {
/** Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup. */
supergroup_chat_created: true;
}
interface ChannelChatCreatedMessage extends ServiceMessage {
/** Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel. */
channel_chat_created: true;
}
interface MessageAutoDeleteTimerChangedMessage extends ServiceMessage {
/** Service message: auto-delete timer settings changed in the chat */
message_auto_delete_timer_changed: MessageAutoDeleteTimerChanged;
}
interface MigrateToChatIdMessage extends ServiceMessage {
/** The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. */
migrate_to_chat_id: number;
}
interface MigrateFromChatIdMessage extends ServiceMessage {
/** The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. */
migrate_from_chat_id: number;
}
interface PinnedMessageMessage extends ServiceMessage {
/** Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply. */
pinned_message: ReplyMessage;
}
interface InvoiceMessage extends ServiceMessage {
/** Message is an invoice for a payment, information about the invoice. More about payments » */
invoice: Invoice;
}
interface SuccessfulPaymentMessage extends ServiceMessage {
/** Message is a service message about a successful payment, information about the payment. More about payments » */
successful_payment: SuccessfulPayment;
}
interface UserSharedMessage extends ServiceMessage {
/** Service message: a user was shared with the bot */
user_shared: UserShared;
}
interface ChatSharedMessage extends ServiceMessage {
/** Service message: a chat was shared with the bot */
chat_shared: ChatShared;
}
interface ConnectedWebsiteMessage extends ServiceMessage {
/** The domain name of the website on which the user has logged in. More about Telegram Login » */
connected_website: string;
}
interface WriteAccessAllowedMessage extends ServiceMessage {
/** Service message: the user allowed the bot added to the attachment menu to write messages */
write_access_allowed: WriteAccessAllowed;
}
interface PassportDataMessage extends ServiceMessage {
/** Telegram Passport data */
passport_data: PassportData;
}
interface ProximityAlertTriggeredMessage extends ServiceMessage {
/** Service message. A user in the chat triggered another user's proximity alert while sharing Live Location. */
proximity_alert_triggered: ProximityAlertTriggered;
}
interface ForumTopicCreatedMessage extends ServiceMessage {
/** Service message: forum topic created */
forum_topic_created: ForumTopicCreated;
}
interface ForumTopicEditedMessage extends ServiceMessage {
/** Service message: forum topic edited */
forum_topic_edited: ForumTopicEdited;
}
interface ForumTopicClosedMessage extends ServiceMessage {
/** Service message: forum topic closed */
forum_topic_closed: ForumTopicClosed;
}
interface ForumTopicReopenedMessage extends ServiceMessage {
/** Service message: forum topic reopened */
forum_topic_reopened: ForumTopicReopened;
}
interface GeneralForumTopicHiddenMessage extends ServiceMessage {
/** Service message: the 'General' forum topic hidden */
general_forum_topic_hidden: GeneralForumTopicHidden;
}
interface GeneralForumTopicUnhiddenMessage extends ServiceMessage {
/** Service message: the 'General' forum topic unhidden */
general_forum_topic_unhidden: GeneralForumTopicUnhidden;
}
interface VideoChatScheduledMessage extends ServiceMessage {
/** Service message: video chat scheduled */
video_chat_scheduled: VideoChatScheduled;
}
interface VideoChatStartedMessage extends ServiceMessage {
/** Service message: video chat started */
video_chat_started: VideoChatStarted;
}
interface VideoChatEndedMessage extends ServiceMessage {
/** Service message: video chat ended */
video_chat_ended: VideoChatEnded;
}
interface VideoChatParticipantsInvitedMessage extends ServiceMessage {
/** Service message: new participants invited to a video chat */
video_chat_participants_invited: VideoChatParticipantsInvited;
}
interface WebAppDataMessage extends ServiceMessage {
/** Service message: data sent by a Web App */
web_app_data: WebAppData;
}
}
/** Helper type that bundles all possible `Message.ServiceMessage`s. More specifically, bundles all messages that do not have a `reply_to_message` field, i.e. are not a `Message.CommonMessage`. */
export type ServiceMessageBundle = Message.NewChatMembersMessage | Message.LeftChatMemberMessage | Message.NewChatTitleMessage | Message.NewChatPhotoMessage | Message.DeleteChatPhotoMessage | Message.GroupChatCreatedMessage | Message.SupergroupChatCreated | Message.ChannelChatCreatedMessage | Message.MessageAutoDeleteTimerChangedMessage | Message.MigrateToChatIdMessage | Message.MigrateFromChatIdMessage | Message.PinnedMessageMessage | Message.InvoiceMessage | Message.SuccessfulPaymentMessage | Message.UserSharedMessage | Message.ChatSharedMessage | Message.ConnectedWebsiteMessage | Message.WriteAccessAllowedMessage | Message.PassportDataMessage | Message.ProximityAlertTriggeredMessage | Message.ForumTopicCreatedMessage | Message.ForumTopicEditedMessage | Message.ForumTopicClosedMessage | Message.ForumTopicReopenedMessage | Message.GeneralForumTopicHiddenMessage | Message.GeneralForumTopicUnhiddenMessage | Message.VideoChatScheduledMessage | Message.VideoChatStartedMessage | Message.VideoChatEndedMessage | Message.VideoChatParticipantsInvitedMessage | Message.WebAppDataMessage;
/** Helper type that bundles all possible `Message.CommonMessage`s. More specifically, bundles all messages that do have a `reply_to_message` field, i.e. are a `Message.CommonMessage`. */
export type CommonMessageBundle = Message.AnimationMessage | Message.AudioMessage | Message.ContactMessage | Message.DiceMessage | Message.DocumentMessage | Message.GameMessage | Message.LocationMessage | Message.PhotoMessage | Message.PollMessage | Message.StickerMessage | Message.StoryMessage | Message.TextMessage | Message.VenueMessage | Message.VideoMessage | Message.VideoNoteMessage | Message.VoiceMessage;
/** Helper type that represents a message which occurs in a `reply_to_message` field. */
type ReplyMessage = ServiceMessageBundle | (CommonMessageBundle & {
reply_to_message: undefined;
});
/** This object represents a message. */
export type Message = ServiceMessageBundle | CommonMessageBundle;
/** This object represents a unique message identifier. */
export interface MessageId {
/** Unique message identifier */
message_id: number;
}
/** Describes an inline message sent by a Web App on behalf of a user. */
export interface SentWebAppMessage {
/** Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. */
inline_message_id: string;
}
/** The Bot API supports basic formatting for messages. You can use bold, italic, underlined, strikethrough, and spoiler text, as well as inline links and pre-formatted code in your bots' messages. Telegram clients will render them accordingly. You can use either markdown-style or HTML-style formatting.
Note that Telegram clients will display an **alert** to the user before opening an inline link ('Open this link?' together with the full URL).
Message entities can be nested, providing following restrictions are met:
- If two entities have common characters, then one of them is fully contained inside another.
- bold, italic, underline, strikethrough, and spoiler entities can contain and can be part of any other entities, except pre and code.
- All other entities can't contain each other.
Links `tg://user?id=<user_id>` can be used to mention a user by their ID without using a username. Please note:
- These links will work only if they are used inside an inline link or in an inline keyboard button. For example, they will not work, when used in a message text.
- Unless the user is a member of the chat where they were mentioned, these mentions are only guaranteed to work if the user has contacted the bot in private in the past or has sent a callback query to the bot via an inline button and doesn't have Forwarded Messages privacy enabled for the bot.
#### MarkdownV2 style
To use this mode, pass *MarkdownV2* in the *parse_mode* field. Use the following syntax in your message:
```
*bold \*text*
_italic \*text_
__underline__
~strikethrough~
||spoiler||
*bold _italic bold ~italic bold strikethrough ||italic bold strikethrough spoiler||~ __underline italic bold___ bold*
[inline URL](http://www.example.com/)
[inline mention of a user](tg://user?id=123456789)
![👍](tg://emoji?id=5368324170671202286)
`inline fixed-width code`
```
pre-formatted fixed-width code block
```
```python
pre-formatted fixed-width code block written in the Python programming language
```
```
Please note:
- Any character with code between 1 and 126 inclusively can be escaped anywhere with a preceding '\' character, in which case it is treated as an ordinary character and not a part of the markup. This implies that '\' character usually must be escaped with a preceding '\' character.
- Inside `pre` and `code` entities, all '`' and '\' characters must be escaped with a preceding '\' character.
- Inside the `(...)` part of the inline link and custom emoji definition, all ')' and '\' must be escaped with a preceding '\' character.
- In all other places characters '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' must be escaped with the preceding character '\'.
- In case of ambiguity between `italic` and `underline` entities `__` is always greadily treated from left to right as beginning or end of `underline` entity, so instead of `___italic underline___` use `___italic underline_\r__`, where `\r` is a character with code 13, which will be ignored.
- A valid emoji must be provided as an alternative value for the custom emoji. The emoji will be shown instead of the custom emoji in places where a custom emoji cannot be displayed (e.g., system notifications) or if the message is forwarded by a non-premium user. It is recommended to use the emoji from the emoji field of the custom emoji sticker.
- Custom emoji entities can only be used by bots that purchased additional usernames on Fragment.
#### HTML style
To use this mode, pass *HTML* in the *parse_mode* field. The following tags are currently supported:
```html
<b>bold</b>, <strong>bold</strong>
<i>italic</i>, <em>italic</em>
<u>underline</u>, <ins>underline</ins>
<s>strikethrough</s>, <strike>strikethrough</strike>, <del>strikethrough</del>
<span class="tg-spoiler">spoiler</span>, <tg-spoiler>spoiler</tg-spoiler>
<b>bold <i>italic bold <s>italic bold strikethrough <span class="tg-spoiler">italic bold strikethrough spoiler</span></s> <u>underline italic bold</u></i> bold</b>
<a href="http://www.example.com/">inline URL</a>
<a href="tg://user?id=123456789">inline mention of a user</a>
<tg-emoji emoji-id="5368324170671202286">👍</tg-emoji>
<code>inline fixed-width code</code>
<pre>pre-formatted fixed-width code block</pre>
<pre><code class="language-python">pre-formatted fixed-width code block written in the Python programming language</code></pre>
```
Please note:
- Only the tags mentioned above are currently supported.
- All `<`, `>` and `&` symbols that are not a part of a tag or an HTML entity must be replaced with the corresponding HTML entities (`<` with `&lt;`, `>` with `&gt;` and `&` with `&amp;`).
- All numerical HTML entities are supported.
- The API currently supports only the following named HTML entities: `&lt;`, `&gt;`, `&amp;` and `&quot;`.
- Use nested `pre` and `code` tags, to define programming language for pre entity.
- Programming language can't be specified for standalone `code` tags.
- A valid emoji must be used as the content of the tg-emoji tag. The emoji will be shown instead of the custom emoji in places where a custom emoji cannot be displayed (e.g., system notifications) or if the message is forwarded by a non-premium user. It is recommended to use the emoji from the emoji field of the custom emoji sticker.
- Custom emoji entities can only be used by bots that purchased additional usernames on Fragment.
#### Markdown style
This is a legacy mode, retained for backward compatibility. To use this mode, pass *Markdown* in the *parse_mode* field. Use the following syntax in your message:
```
*bold text*
_italic text_
[inline URL](http://www.example.com/)
[inline mention of a user](tg://user?id=123456789)
`inline fixed-width code`
```
pre-formatted fixed-width code block
```
```python
pre-formatted fixed-width code block written in the Python programming language
```
```
Please note:
- Entities must not be nested, use parse mode MarkdownV2 instead.
- There is no way to specify underline and strikethrough entities, use parse mode MarkdownV2 instead.
- To escape characters '_', '*', '`', '[' outside of an entity, prepend the characters '\' before them.
- Escaping inside entities is not allowed, so entity must be closed first and reopened again: use `_snake_\__case_` for italic `snake_case` and `*2*\**2=4*` for bold `2*2=4`. */
export type ParseMode = "Markdown" | "MarkdownV2" | "HTML";
export declare namespace MessageEntity {
interface AbstractMessageEntity {
/** Type of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag), “cashtag” ($USD), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames), “custom_emoji” (for inline custom emoji stickers) */
type: string;
/** Offset in UTF-16 code units to the start of the entity */
offset: number;
/** Length of the entity in UTF-16 code units */
length: number;
}
interface CommonMessageEntity extends AbstractMessageEntity {
type: "mention" | "hashtag" | "cashtag" | "bot_command" | "url" | "email" | "phone_number" | "bold" | "italic" | "underline" | "strikethrough" | "spoiler" | "code";
}
interface PreMessageEntity extends AbstractMessageEntity {
type: "pre";
/** For “pre” only, the programming language of the entity text */
language?: string;
}
interface TextLinkMessageEntity extends AbstractMessageEntity {
type: "text_link";
/** For “text_link” only, URL that will be opened after user taps on the text */
url: string;
}
interface TextMentionMessageEntity extends AbstractMessageEntity {
type: "text_mention";
/** For “text_mention” only, the mentioned user */
user: User;
}
interface CustomEmojiMessageEntity extends AbstractMessageEntity {
type: "custom_emoji";
/** For “custom_emoji” only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker */
custom_emoji_id: string;
}
}
/** This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. */
export type MessageEntity = MessageEntity.CommonMessageEntity | MessageEntity.CustomEmojiMessageEntity | MessageEntity.PreMessageEntity | MessageEntity.TextLinkMessageEntity | MessageEntity.TextMentionMessageEntity;
/** This object represents one size of a photo or a file / sticker thumbnail. */
export interface PhotoSize {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** Photo width */
width: number;
/** Photo height */
height: number;
/** File size in bytes */
file_size?: number;
}
/** This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound). */
export interface Animation {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** Video width as defined by sender */
width: number;
/** Video height as defined by sender */
height: number;
/** Duration of the video in seconds as defined by sender */
duration: number;
/** Animation thumbnail as defined by sender */
thumbnail?: PhotoSize;
/** Original animation filename as defined by sender */
file_name?: string;
/** MIME type of the file as defined by sender */
mime_type?: string;
/** File size in bytes */
file_size?: number;
}
/** This object represents an audio file to be treated as music by the Telegram clients. */
export interface Audio {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** Duration of the audio in seconds as defined by sender */
duration: number;
/** Performer of the audio as defined by sender or by audio tags */
performer?: string;
/** Title of the audio as defined by sender or by audio tags */
title?: string;
/** Original filename as defined by sender */
file_name?: string;
/** MIME type of the file as defined by sender */
mime_type?: string;
/** File size in bytes */
file_size?: number;
/** Thumbnail of the album cover to which the music file belongs */
thumbnail?: PhotoSize;
}
/** This object represents a general file (as opposed to photos, voice messages and audio files). */
export interface Document {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** Document thumbnail as defined by sender */
thumbnail?: PhotoSize;
/** Original filename as defined by sender */
file_name?: string;
/** MIME type of the file as defined by sender */
mime_type?: string;
/** File size in bytes */
file_size?: number;
}
/** This object represents a video file. */
export interface Video {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** Video width as defined by sender */
width: number;
/** Video height as defined by sender */
height: number;
/** Duration of the video in seconds as defined by sender */
duration: number;
/** Video thumbnail */
thumbnail?: PhotoSize;
/** Original filename as defined by sender */
file_name?: string;
/** MIME type of the file as defined by sender */
mime_type?: string;
/** File size in bytes */
file_size?: number;
}
/** This object represents a video message (available in Telegram apps as of v.4.0). */
export interface VideoNote {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** Video width and height (diameter of the video message) as defined by sender */
length: number;
/** Duration of the video in seconds as defined by sender */
duration: number;
/** Video thumbnail */
thumbnail?: PhotoSize;
/** File size in bytes */
file_size?: number;
}
/** This object represents a voice note. */
export interface Voice {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** Duration of the audio in seconds as defined by sender */
duration: number;
/** MIME type of the file as defined by sender */
mime_type?: string;
/** File size in bytes */
file_size?: number;
}
/** This object represents a phone contact. */
export interface Contact {
/** Contact's phone number */
phone_number: string;
/** Contact's first name */
first_name: string;
/** Contact's last name */
last_name?: string;
/** Contact's user identifier in Telegram. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. */
user_id?: number;
/** Additional data about the contact in the form of a vCard */
vcard?: string;
}
/** This object represents an animated emoji that displays a random value. */
export interface Dice {
/** Emoji on which the dice throw animation is based */
emoji: string;
/** Value of the dice, 1-6 for “🎲”, “🎯” and “🎳” base emoji, 1-5 for “🏀” and “⚽” base emoji, 1-64 for “🎰” base emoji */
value: number;
}
/** This object contains information about one answer option in a poll. */
export interface PollOption {
/** Option text, 1-100 characters */
text: string;
/** Number of users that voted for this option */
voter_count: number;
}
/** This object represents an answer of a user in a non-anonymous poll. */
export interface PollAnswer {
/** Unique poll identifier */
poll_id: string;
/** The chat that changed the answer to the poll, if the voter is anonymous */
voter_chat?: Chat;
/** The user, who changed the answer to the poll, if the voter isn't anonymous
*
* For backward compatibility, the field user will contain the user 136817688 (@Channel_Bot) if the voter was a chat
*/
user?: User;
/** 0-based identifiers of answer options, chosen by the user. May be empty if the user retracted their vote. */
option_ids: number[];
}
/** This object contains information about a poll. */
export interface Poll {
/** Unique poll identifier */
id: string;
/** Poll question, 1-300 characters */
question: string;
/** List of poll options */
options: PollOption[];
/** Total number of users that voted in the poll */
total_voter_count: number;
/** True, if the poll is closed */
is_closed: boolean;
/** True, if the poll is anonymous */
is_anonymous: boolean;
/** Poll type, currently can be “regular” or “quiz” */
type: "regular" | "quiz";
/** True, if the poll allows multiple answers */
allows_multiple_answers: boolean;
/** 0-based identifier of the correct answer option. Available only for polls in the quiz mode, which are closed, or was sent (not forwarded) by the bot or to the private chat with the bot. */
correct_option_id?: number;
/** Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters */
explanation?: string;
/** Special entities like usernames, URLs, bot commands, etc. that appear in the explanation */
explanation_entities?: MessageEntity[];
/** Amount of time in seconds the poll will be active after creation */
open_period?: number;
/** Point in time (Unix timestamp) when the poll will be automatically closed */
close_date?: number;
}
export declare namespace Location {
interface CommonLocation {
/** Longitude as defined by sender */
longitude: number;
/** Latitude as defined by sender */
latitude: number;
/** The radius of uncertainty for the location, measured in meters; 0-1500 */
horizontal_accuracy?: number;
}
interface LiveLocation extends CommonLocation {
/** Time relative to the message sending date, during which the location can be updated, in seconds. For active live locations only. */
live_period: number;
/** The direction in which user is moving, in degrees; 1-360. For active live locations only. */
heading: number;
/** The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only. */
proximity_alert_radius?: number;
}
}
/** This object represents a point on the map. */
export type Location = Location.CommonLocation | Location.LiveLocation;
/** This object represents a venue. */
export interface Venue {
/** Venue location. Can't be a live location */
location: Location;
/** Name of the venue */
title: string;
/** Address of the venue */
address: string;
/** Foursquare identifier of the venue */
foursquare_id?: string;
/** Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) */
foursquare_type?: string;
/** Google Places identifier of the venue */
google_place_id?: string;
/** Google Places type of the venue. (See supported types.) */
google_place_type?: string;
}
/** This object represents a message about a forwarded story in the chat. Currently holds no information. */
export interface Story {
}
/** This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user. */
export interface ProximityAlertTriggered {
/** User that triggered the alert */
traveler: User;
/** User that set the alert */
watcher: User;
/** The distance between the users */
distance: number;
}
/** This object represents a service message about a change in auto-delete timer settings. */
export interface MessageAutoDeleteTimerChanged {
/** New auto-delete time for messages in the chat; in seconds */
message_auto_delete_time: number;
}
/** This object represents a service message about a new forum topic created in the chat. */
export interface ForumTopicCreated {
/** Name of the topic */
name: string;
/** Color of the topic icon in RGB format */
icon_color: number;
/** Unique identifier of the custom emoji shown as the topic icon */
icon_custom_emoji_id?: string;
}
/** This object represents a service message about an edited forum topic. */
export interface ForumTopicEdited {
/** New name of the topic, if it was edited */
name?: string;
/** New identifier of the custom emoji shown as the topic icon, if it was edited; an empty string if the icon was removed */
icon_custom_emoji_id?: string;
}
/** This object represents a service message about a forum topic closed in the chat. Currently holds no information. */
export interface ForumTopicClosed {
}
/** This object represents a service message about a forum topic reopened in the chat. Currently holds no information. */
export interface ForumTopicReopened {
}
/** This object represents a service message about General forum topic hidden in the chat. Currently holds no information. */
export interface GeneralForumTopicHidden {
}
/** This object represents a service message about General forum topic unhidden in the chat. Currently holds no information. */
export interface GeneralForumTopicUnhidden {
}
/** This object contains information about the user whose identifier was shared with the bot using a KeyboardButtonRequestUser button. */
export interface UserShared {
/** Identifier of the request */
request_id: number;
/** Identifier of the shared user. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot may not have access to the user and could be unable to use this identifier, unless the user is already known to the bot by some other means. */
user_id: number;
}
/** This object contains information about the chat whose identifier was shared with the bot using a KeyboardButtonRequestChat button. */
export interface ChatShared {
/** Identifier of the request */
request_id: number;
/** Identifier of the shared chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot may not have access to the chat and could be unable to use this identifier, unless the chat is already known to the bot by some other means. */
chat_id: number;
}
/** This object represents a service message about a user allowing a bot to write messages after adding the bot to the attachment menu or launching a Web App from a link. */
export interface WriteAccessAllowed {
/** True, if the access was granted after the user accepted an explicit request from a Web App sent by the method requestWriteAccess */
from_request?: boolean;
/** Name of the Web App, if the access was granted when the Web App was launched from a link */
web_app_name?: string;
/** True, if the access was granted when the bot was added to the attachment or side menu */
from_attachment_menu?: boolean;
}
/** This object represents a service message about a video chat scheduled in the chat. */
export interface VideoChatScheduled {
/** Point in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator */
start_date: number;
}
/** This object represents a service message about a video chat started in the chat. Currently holds no information. */
export interface VideoChatStarted {
}
/** This object represents a service message about a video chat ended in the chat. */
export interface VideoChatEnded {
/** Video chat duration in seconds */
duration: number;
}
/** This object represents a service message about new members invited to a video chat. */
export interface VideoChatParticipantsInvited {
/** New members that were invited to the video chat */
users: User[];
}
/** Describes data sent from a Web App to the bot. */
export interface WebAppData {
/** The data. Be aware that a bad client can send arbitrary data in this field. */
data: string;
/** Text of the web_app keyboard button from which the Web App was opened. Be aware that a bad client can send arbitrary data in this field. */
button_text: string;
}
/** This object represents a sticker. */
export interface Sticker {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** Type of the sticker, currently one of “regular”, “mask”, “custom_emoji”. The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video. */
type: "regular" | "mask" | "custom_emoji";
/** Sticker width */
width: number;
/** Sticker height */
height: number;
/** True, if the sticker is animated */
is_animated: boolean;
/** True, if the sticker is a video sticker */
is_video: boolean;
/** Sticker thumbnail in the .WEBP or .JPG format */
thumbnail?: PhotoSize;
/** Emoji associated with the sticker */
emoji?: string;
/** Name of the sticker set to which the sticker belongs */
set_name?: string;
/** For premium regular stickers, premium animation for the sticker */
premium_animation?: File;
/** For mask stickers, the position where the mask should be placed */
mask_position?: MaskPosition;
/** For custom emoji stickers, unique identifier of the custom emoji */
custom_emoji_id?: string;
/** File size in bytes */
file_size?: number;
}
/** This object represents a sticker set. */
export interface StickerSet {
/** Sticker set name */
name: string;
/** Sticker set title */
title: string;
/** Type of stickers in the set, currently one of “regular”, “mask”, “custom_emoji” */
sticker_type: "regular" | "mask" | "custom_emoji";
/** True, if the sticker set contains animated stickers */
is_animated: boolean;
/** True, if the sticker set contains video stickers */
is_video: boolean;
/** List of all set stickers */
stickers: Sticker[];
/** Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format */
thumbnail?: PhotoSize;
}
/** This object describes the position on faces where a mask should be placed by default. */
export interface MaskPosition {
/** The part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or “chin”. */
point: "forehead" | "eyes" | "mouth" | "chin";
/** Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position. */
x_shift: number;
/** Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position. */
y_shift: number;
/** Mask scaling coefficient. For example, 2.0 means double size. */
scale: number;
}
/** This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers. */
export interface Game {
/** Title of the game */
title: string;
/** Description of the game */
description: string;
/** Photo that will be displayed in the game message in chats. */
photo: PhotoSize[];
/** Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters. */
text: string;
/** Special entities that appear in text, such as usernames, URLs, bot commands, etc. */
text_entities: MessageEntity[];
/** Animation that will be displayed in the game message in chats. Upload via BotFather */
animation: Animation;
}
/** This object represents one row of the high scores table for a game. */
export interface GameHighScore {
/** Position in high score table for the game */
position: number;
/** User */
user: User;
/** Score */
score: number;
}
export {};

1558
node_modules/@telegraf/types/methods.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

37
node_modules/@telegraf/types/package.json generated vendored Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "@telegraf/types",
"private": false,
"version": "6.9.1",
"description": "Type declarations for the Telegram API",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/telegraf/types.git"
},
"keywords": [
"telegram",
"grammy",
"telegraf",
"bot",
"api",
"types",
"typings"
],
"scripts": {
"prepare": "deno task backport"
},
"author": "Telegraf contributors",
"types": "index.d.ts",
"license": "MIT",
"bugs": {
"url": "https://github.com/telegraf/types/issues"
},
"homepage": "https://github.com/telegraf/types#readme",
"files": [
"*.d.ts",
"index.js"
],
"devDependencies": {
"deno-bin": "^1.31.1"
}
}

163
node_modules/@telegraf/types/passport.d.ts generated vendored Normal file
View File

@@ -0,0 +1,163 @@
/** Describes Telegram Passport data shared with the bot by the user. */
export interface PassportData {
/** Array with information about documents and other Telegram Passport elements that was shared with the bot */
data: EncryptedPassportElement[];
/** Encrypted credentials required to decrypt the data */
credentials: EncryptedCredentials;
}
/** This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB. */
export interface PassportFile {
/** Identifier for this file, which can be used to download or reuse the file */
file_id: string;
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id: string;
/** File size in bytes */
file_size: number;
/** Unix time when the file was uploaded */
file_date: number;
}
/** Describes documents or other Telegram Passport elements shared with the bot by the user. */
export interface EncryptedPassportElement {
/** Element type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email”. */
type: "personal_details" | "passport" | "driver_license" | "identity_card" | "internal_passport" | "address" | "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration" | "phone_number" | "email";
/** Base64-encoded encrypted Telegram Passport element data provided by the user, available for “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport” and “address” types. Can be decrypted and verified using the accompanying EncryptedCredentials. */
data?: string;
/** User's verified phone number, available only for “phone_number” type */
phone_number?: string;
/** User's verified email address, available only for “email” type */
email?: string;
/** Array of encrypted files with documents provided by the user, available for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials. */
files?: PassportFile[];
/** Encrypted file with the front side of the document, provided by the user. Available for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials. */
front_side?: PassportFile;
/** Encrypted file with the reverse side of the document, provided by the user. Available for “driver_license” and “identity_card”. The file can be decrypted and verified using the accompanying EncryptedCredentials. */
reverse_side?: PassportFile;
/** Encrypted file with the selfie of the user holding a document, provided by the user; available for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials. */
selfie?: PassportFile;
/** Array of encrypted files with translated versions of documents provided by the user. Available if requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials. */
translation?: PassportFile[];
/** Base64-encoded element hash for using in PassportElementErrorUnspecified */
hash: string;
}
/** Describes data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes. */
export interface EncryptedCredentials {
/** Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication */
data: string;
/** Base64-encoded data hash for data authentication */
hash: string;
/** Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption */
secret: string;
}
/** This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of:
- PassportElementErrorDataField
- PassportElementErrorFrontSide
- PassportElementErrorReverseSide
- PassportElementErrorSelfie
- PassportElementErrorFile
- PassportElementErrorFiles
- PassportElementErrorTranslationFile
- PassportElementErrorTranslationFiles
- PassportElementErrorUnspecified
*/
export type PassportElementError = PassportElementErrorDataField | PassportElementErrorFrontSide | PassportElementErrorReverseSide | PassportElementErrorSelfie | PassportElementErrorFile | PassportElementErrorFiles | PassportElementErrorTranslationFile | PassportElementErrorTranslationFiles | PassportElementErrorUnspecified;
/** Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes. */
export interface PassportElementErrorDataField {
/** Error source, must be data */
source: "data";
/** The section of the user's Telegram Passport which has the error, one of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address” */
type: "personal_details" | "passport" | "driver_license" | "identity_card" | "internal_passport" | "address";
/** Name of the data field which has the error */
field_name: string;
/** Base64-encoded data hash */
data_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes. */
export interface PassportElementErrorFrontSide {
/** Error source, must be front_side */
source: "front_side";
/** The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport” */
type: "passport" | "driver_license" | "identity_card" | "internal_passport";
/** Base64-encoded hash of the file with the front side of the document */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes. */
export interface PassportElementErrorReverseSide {
/** Error source, must be reverse_side */
source: "reverse_side";
/** The section of the user's Telegram Passport which has the issue, one of “driver_license”, “identity_card” */
type: "driver_license" | "identity_card";
/** Base64-encoded hash of the file with the reverse side of the document */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes. */
export interface PassportElementErrorSelfie {
/** Error source, must be selfie */
source: "selfie";
/** The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport” */
type: "passport" | "driver_license" | "identity_card" | "internal_passport";
/** Base64-encoded hash of the file with the selfie */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes. */
export interface PassportElementErrorFile {
/** Error source, must be file */
source: "file";
/** The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */
type: "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration";
/** Base64-encoded file hash */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes. */
export interface PassportElementErrorFiles {
/** Error source, must be files */
source: "files";
/** The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */
type: "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration";
/** List of base64-encoded file hashes */
file_hashes: string[];
/** Error message */
message: string;
}
/** Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes. */
export interface PassportElementErrorTranslationFile {
/** Error source, must be translation_file */
source: "translation_file";
/** Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */
type: "passport" | "driver_license" | "identity_card" | "internal_passport" | "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration";
/** Base64-encoded file hash */
file_hash: string;
/** Error message */
message: string;
}
/** Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change. */
export interface PassportElementErrorTranslationFiles {
/** Error source, must be translation_files */
source: "translation_files";
/** Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */
type: "passport" | "driver_license" | "identity_card" | "internal_passport" | "utility_bill" | "bank_statement" | "rental_agreement" | "passport_registration" | "temporary_registration";
/** List of base64-encoded file hashes */
file_hashes: string[];
/** Error message */
message: string;
}
/** Represents an issue in an unspecified place. The error is considered resolved when new data is added. */
export interface PassportElementErrorUnspecified {
/** Error source, must be unspecified */
source: "unspecified";
/** Type of element of the user's Telegram Passport which has the issue */
type: string;
/** Base64-encoded element hash */
element_hash: string;
/** Error message */
message: string;
}

101
node_modules/@telegraf/types/payment.d.ts generated vendored Normal file
View File

@@ -0,0 +1,101 @@
import type { User } from "./manage.js";
/** This object represents a portion of the price for goods or services. */
export interface LabeledPrice {
/** Portion label */
label: string;
/** Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
amount: number;
}
/** This object contains basic information about an invoice. */
export interface Invoice {
/** Product name */
title: string;
/** Product description */
description: string;
/** Unique bot deep-linking parameter that can be used to generate this invoice */
start_parameter: string;
/** Three-letter ISO 4217 currency code */
currency: string;
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount: number;
}
/** This object represents a shipping address. */
export interface ShippingAddress {
/** Two-letter ISO 3166-1 alpha-2 country code */
country_code: string;
/** State, if applicable */
state: string;
/** City */
city: string;
/** First line for the address */
street_line1: string;
/** Second line for the address */
street_line2: string;
/** Address post code */
post_code: string;
}
/** This object represents information about an order. */
export interface OrderInfo {
/** User name */
name?: string;
/** User's phone number */
phone_number?: string;
/** User email */
email?: string;
/** User shipping address */
shipping_address?: ShippingAddress;
}
/** This object represents one shipping option. */
export interface ShippingOption {
/** Shipping option identifier */
id: string;
/** Option title */
title: string;
/** List of price portions */
prices: LabeledPrice[];
}
/** This object contains basic information about a successful payment. */
export interface SuccessfulPayment {
/** Three-letter ISO 4217 currency code */
currency: string;
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount: number;
/** Bot specified invoice payload */
invoice_payload: string;
/** Identifier of the shipping option chosen by the user */
shipping_option_id?: string;
/** Order information provided by the user */
order_info?: OrderInfo;
/** Telegram payment identifier */
telegram_payment_charge_id: string;
/** Provider payment identifier */
provider_payment_charge_id: string;
}
/** This object contains information about an incoming shipping query. */
export interface ShippingQuery {
/** Unique query identifier */
id: string;
/** User who sent the query */
from: User;
/** Bot specified invoice payload */
invoice_payload: string;
/** User specified shipping address */
shipping_address: ShippingAddress;
}
/** This object contains information about an incoming pre-checkout query. */
export interface PreCheckoutQuery {
/** Unique query identifier */
id: string;
/** User who sent the query */
from: User;
/** Three-letter ISO 4217 currency code */
currency: string;
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount: number;
/** Bot specified invoice payload */
invoice_payload: string;
/** Identifier of the shipping option chosen by the user */
shipping_option_id?: string;
/** Order information provided by the user */
order_info?: OrderInfo;
}

120
node_modules/@telegraf/types/settings.d.ts generated vendored Normal file
View File

@@ -0,0 +1,120 @@
import type { WebAppInfo } from "./markup.js";
/** This object represents the bot's name. */
export interface BotName {
/** The bot's name */
name: string;
}
/** This object represents the bot's description. */
export interface BotDescription {
/** The bot's description */
description: string;
}
/** This object represents the bot's short description. */
export interface BotShortDescription {
/** The bot's short description */
short_description: string;
}
/** This object describes the bot's menu button in a private chat. It should be one of
- MenuButtonCommands
- MenuButtonWebApp
- MenuButtonDefault
If a menu button other than MenuButtonDefault is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands. */
export type MenuButton = MenuButtonCommands | MenuButtonWebApp | MenuButtonDefault;
/** Represents a menu button, which opens the bot's list of commands. */
export interface MenuButtonCommands {
/** Type of the button, must be commands */
type: "commands";
}
/** Represents a menu button, which launches a Web App. */
export interface MenuButtonWebApp {
/** Button type, must be web_app */
type: "web_app";
/** Text on the button */
text: string;
/** Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. */
web_app: WebAppInfo;
}
/** Describes that no specific value for the menu button was set. */
export interface MenuButtonDefault {
/** Type of the button, must be default */
type: "default";
}
/** This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported:
- BotCommandScopeDefault
- BotCommandScopeAllPrivateChats
- BotCommandScopeAllGroupChats
- BotCommandScopeAllChatAdministrators
- BotCommandScopeChat
- BotCommandScopeChatAdministrators
- BotCommandScopeChatMember
## Determining list of commands
The following algorithm is used to determine the list of commands for a particular user viewing the bot menu. The first list of commands which is set is returned:
### Commands in the chat with the bot
- botCommandScopeChat + language_code
- botCommandScopeChat
- botCommandScopeAllPrivateChats + language_code
- botCommandScopeAllPrivateChats
- botCommandScopeDefault + language_code
- botCommandScopeDefault
### Commands in group and supergroup chats
- botCommandScopeChatMember + language_code
- botCommandScopeChatMember
- botCommandScopeChatAdministrators + language_code (administrators only)
- botCommandScopeChatAdministrators (administrators only)
- botCommandScopeChat + language_code
- botCommandScopeChat
- botCommandScopeAllChatAdministrators + language_code (administrators only)
- botCommandScopeAllChatAdministrators (administrators only)
- botCommandScopeAllGroupChats + language_code
- botCommandScopeAllGroupChats
- botCommandScopeDefault + language_code
- botCommandScopeDefault */
export type BotCommandScope = BotCommandScopeDefault | BotCommandScopeAllPrivateChats | BotCommandScopeAllGroupChats | BotCommandScopeAllChatAdministrators | BotCommandScopeChat | BotCommandScopeChatAdministrators | BotCommandScopeChatMember;
/** Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user. */
export interface BotCommandScopeDefault {
/** Scope type, must be default */
type: "default";
}
/** Represents the scope of bot commands, covering all private chats. */
export interface BotCommandScopeAllPrivateChats {
/** Scope type, must be all_private_chats */
type: "all_private_chats";
}
/** Represents the scope of bot commands, covering all group and supergroup chats. */
export interface BotCommandScopeAllGroupChats {
/** Scope type, must be all_group_chats */
type: "all_group_chats";
}
/** Represents the scope of bot commands, covering all group and supergroup chat administrators. */
export interface BotCommandScopeAllChatAdministrators {
/** Scope type, must be all_chat_administrators */
type: "all_chat_administrators";
}
/** Represents the scope of bot commands, covering a specific chat. */
export interface BotCommandScopeChat {
/** Scope type, must be chat */
type: "chat";
/** Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) */
chat_id: number | string;
}
/** Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat. */
export interface BotCommandScopeChatAdministrators {
/** Scope type, must be chat_administrators */
type: "chat_administrators";
/** Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) */
chat_id: number | string;
}
/** Represents the scope of bot commands, covering a specific member of a group or supergroup chat. */
export interface BotCommandScopeChatMember {
/** Scope type, must be chat_member */
type: "chat_member";
/** Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) */
chat_id: number | string;
/** Unique identifier of the target user */
user_id: number;
}

97
node_modules/@telegraf/types/update.d.ts generated vendored Normal file
View File

@@ -0,0 +1,97 @@
import type { ChosenInlineResult, InlineQuery } from "./inline.js";
import type { Chat, ChatJoinRequest, ChatMemberUpdated, User } from "./manage.js";
import type { CallbackQuery } from "./markup.js";
import type { CommonMessageBundle, Message, Poll, PollAnswer } from "./message.js";
import type { PreCheckoutQuery, ShippingQuery } from "./payment.js";
export declare namespace Update {
/** Internal type holding properties that updates in channels share. */
interface Channel {
chat: Chat.ChannelChat;
author_signature?: string;
from?: never;
}
/** Internal type holding properties that updates outside of channels share. */
interface NonChannel {
chat: Exclude<Chat, Chat.ChannelChat>;
author_signature?: never;
from: User;
}
/** Internal type holding properties that updates about new messages share. */
interface New {
edit_date?: never;
}
/** Internal type holding properties that updates about edited messages share. */
interface Edited {
/** Date the message was last edited in Unix time */
edit_date: number;
forward_from?: never;
forward_from_chat?: never;
forward_from_message_id?: never;
forward_signature?: never;
forward_sender_name?: never;
forward_date?: never;
}
interface AbstractUpdate {
/** The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. */
update_id: number;
}
interface MessageUpdate<M extends Message = Message> extends AbstractUpdate {
/** New incoming message of any kind - text, photo, sticker, etc. */
message: New & NonChannel & M;
}
interface EditedMessageUpdate<M extends CommonMessageBundle = CommonMessageBundle> extends AbstractUpdate {
/** New version of a message that is known to the bot and was edited */
edited_message: Edited & NonChannel & M;
}
interface ChannelPostUpdate<M extends Message = Message> extends AbstractUpdate {
/** New incoming channel post of any kind - text, photo, sticker, etc. */
channel_post: New & Channel & M;
}
interface EditedChannelPostUpdate<M extends CommonMessageBundle = CommonMessageBundle> extends AbstractUpdate {
/** New version of a channel post that is known to the bot and was edited */
edited_channel_post: Edited & Channel & M;
}
interface InlineQueryUpdate extends AbstractUpdate {
/** New incoming inline query */
inline_query: InlineQuery;
}
interface ChosenInlineResultUpdate extends AbstractUpdate {
/** The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. */
chosen_inline_result: ChosenInlineResult;
}
interface CallbackQueryUpdate<C extends CallbackQuery = CallbackQuery> extends AbstractUpdate {
/** New incoming callback query */
callback_query: C;
}
interface ShippingQueryUpdate extends AbstractUpdate {
/** New incoming shipping query. Only for invoices with flexible price */
shipping_query: ShippingQuery;
}
interface PreCheckoutQueryUpdate extends AbstractUpdate {
/** New incoming pre-checkout query. Contains full information about checkout */
pre_checkout_query: PreCheckoutQuery;
}
interface PollUpdate extends AbstractUpdate {
/** New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot */
poll: Poll;
}
interface PollAnswerUpdate extends AbstractUpdate {
/** A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself. */
poll_answer: PollAnswer;
}
interface MyChatMemberUpdate extends AbstractUpdate {
/** The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user. */
my_chat_member: ChatMemberUpdated;
}
interface ChatMemberUpdate extends AbstractUpdate {
/** A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates. */
chat_member: ChatMemberUpdated;
}
interface ChatJoinRequestUpdate extends AbstractUpdate {
/** A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. */
chat_join_request: ChatJoinRequest;
}
}
/** This object represents an incoming update.
At most one of the optional parameters can be present in any given update. */
export type Update = Update.CallbackQueryUpdate | Update.ChannelPostUpdate | Update.ChatMemberUpdate | Update.ChosenInlineResultUpdate | Update.EditedChannelPostUpdate | Update.EditedMessageUpdate | Update.InlineQueryUpdate | Update.MessageUpdate | Update.MyChatMemberUpdate | Update.PreCheckoutQueryUpdate | Update.PollAnswerUpdate | Update.PollUpdate | Update.ShippingQueryUpdate | Update.ChatJoinRequestUpdate;

46
node_modules/abbrev/LICENSE generated vendored Normal file
View File

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

23
node_modules/abbrev/README.md generated vendored Normal file
View File

@@ -0,0 +1,23 @@
# abbrev-js
Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).
Usage:
var abbrev = require("abbrev");
abbrev("foo", "fool", "folding", "flop");
// returns:
{ fl: 'flop'
, flo: 'flop'
, flop: 'flop'
, fol: 'folding'
, fold: 'folding'
, foldi: 'folding'
, foldin: 'folding'
, folding: 'folding'
, foo: 'foo'
, fool: 'fool'
}
This is handy for command-line scripts, or other cases where you want to be able to accept shorthands.

61
node_modules/abbrev/abbrev.js generated vendored Normal file
View File

@@ -0,0 +1,61 @@
module.exports = exports = abbrev.abbrev = abbrev
abbrev.monkeyPatch = monkeyPatch
function monkeyPatch () {
Object.defineProperty(Array.prototype, 'abbrev', {
value: function () { return abbrev(this) },
enumerable: false, configurable: true, writable: true
})
Object.defineProperty(Object.prototype, 'abbrev', {
value: function () { return abbrev(Object.keys(this)) },
enumerable: false, configurable: true, writable: true
})
}
function abbrev (list) {
if (arguments.length !== 1 || !Array.isArray(list)) {
list = Array.prototype.slice.call(arguments, 0)
}
for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
}
// sort them lexicographically, so that they're next to their nearest kin
args = args.sort(lexSort)
// walk through each, seeing how much it has in common with the next and previous
var abbrevs = {}
, prev = ""
for (var i = 0, l = args.length ; i < l ; i ++) {
var current = args[i]
, next = args[i + 1] || ""
, nextMatches = true
, prevMatches = true
if (current === next) continue
for (var j = 0, cl = current.length ; j < cl ; j ++) {
var curChar = current.charAt(j)
nextMatches = nextMatches && curChar === next.charAt(j)
prevMatches = prevMatches && curChar === prev.charAt(j)
if (!nextMatches && !prevMatches) {
j ++
break
}
}
prev = current
if (j === cl) {
abbrevs[current] = current
continue
}
for (var a = current.substr(0, j) ; j <= cl ; j ++) {
abbrevs[a] = current
a += current.charAt(j)
}
}
return abbrevs
}
function lexSort (a, b) {
return a === b ? 0 : a > b ? 1 : -1
}

21
node_modules/abbrev/package.json generated vendored Normal file
View File

@@ -0,0 +1,21 @@
{
"name": "abbrev",
"version": "1.1.1",
"description": "Like ruby's abbrev module, but in js",
"author": "Isaac Z. Schlueter <i@izs.me>",
"main": "abbrev.js",
"scripts": {
"test": "tap test.js --100",
"preversion": "npm test",
"postversion": "npm publish",
"postpublish": "git push origin --all; git push origin --tags"
},
"repository": "http://github.com/isaacs/abbrev-js",
"license": "ISC",
"devDependencies": {
"tap": "^10.1"
},
"files": [
"abbrev.js"
]
}

21
node_modules/abort-controller/LICENSE generated vendored Normal file
View File

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

98
node_modules/abort-controller/README.md generated vendored Normal file
View File

@@ -0,0 +1,98 @@
# abort-controller
[![npm version](https://img.shields.io/npm/v/abort-controller.svg)](https://www.npmjs.com/package/abort-controller)
[![Downloads/month](https://img.shields.io/npm/dm/abort-controller.svg)](http://www.npmtrends.com/abort-controller)
[![Build Status](https://travis-ci.org/mysticatea/abort-controller.svg?branch=master)](https://travis-ci.org/mysticatea/abort-controller)
[![Coverage Status](https://codecov.io/gh/mysticatea/abort-controller/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/abort-controller)
[![Dependency Status](https://david-dm.org/mysticatea/abort-controller.svg)](https://david-dm.org/mysticatea/abort-controller)
An implementation of [WHATWG AbortController interface](https://dom.spec.whatwg.org/#interface-abortcontroller).
```js
import AbortController from "abort-controller"
const controller = new AbortController()
const signal = controller.signal
signal.addEventListener("abort", () => {
console.log("aborted!")
})
controller.abort()
```
> https://jsfiddle.net/1r2994qp/1/
## 💿 Installation
Use [npm](https://www.npmjs.com/) to install then use a bundler.
```
npm install abort-controller
```
Or download from [`dist` directory](./dist).
- [dist/abort-controller.mjs](dist/abort-controller.mjs) ... ES modules version.
- [dist/abort-controller.js](dist/abort-controller.js) ... Common JS version.
- [dist/abort-controller.umd.js](dist/abort-controller.umd.js) ... UMD (Universal Module Definition) version. This is transpiled by [Babel](https://babeljs.io/) for IE 11.
## 📖 Usage
### Basic
```js
import AbortController from "abort-controller"
// or
const AbortController = require("abort-controller")
// or UMD version defines a global variable:
const AbortController = window.AbortControllerShim
```
If your bundler recognizes `browser` field of `package.json`, the imported `AbortController` is the native one and it doesn't contain shim (even if the native implementation was nothing).
If you wanted to polyfill `AbortController` for IE, use `abort-controller/polyfill`.
### Polyfilling
Importing `abort-controller/polyfill` assigns the `AbortController` shim to the `AbortController` global variable if the native implementation was nothing.
```js
import "abort-controller/polyfill"
// or
require("abort-controller/polyfill")
```
### API
#### AbortController
> https://dom.spec.whatwg.org/#interface-abortcontroller
##### controller.signal
The [AbortSignal](https://dom.spec.whatwg.org/#interface-AbortSignal) object which is associated to this controller.
##### controller.abort()
Notify `abort` event to listeners that the `signal` has.
## 📰 Changelog
- See [GitHub releases](https://github.com/mysticatea/abort-controller/releases).
## 🍻 Contributing
Contributing is welcome ❤️
Please use GitHub issues/PRs.
### Development tools
- `npm install` installs dependencies for development.
- `npm test` runs tests and measures code coverage.
- `npm run clean` removes temporary files of tests.
- `npm run coverage` opens code coverage of the previous test with your default browser.
- `npm run lint` runs ESLint.
- `npm run build` generates `dist` codes.
- `npm run watch` runs tests on each file change.

13
node_modules/abort-controller/browser.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
/*globals self, window */
"use strict"
/*eslint-disable @mysticatea/prettier */
const { AbortController, AbortSignal } =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
module.exports = AbortController
module.exports.AbortSignal = AbortSignal
module.exports.default = AbortController

11
node_modules/abort-controller/browser.mjs generated vendored Normal file
View File

@@ -0,0 +1,11 @@
/*globals self, window */
/*eslint-disable @mysticatea/prettier */
const { AbortController, AbortSignal } =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
export default AbortController
export { AbortController, AbortSignal }

View File

@@ -0,0 +1,43 @@
import { EventTarget } from "event-target-shim"
type Events = {
abort: any
}
type EventAttributes = {
onabort: any
}
/**
* The signal class.
* @see https://dom.spec.whatwg.org/#abortsignal
*/
declare class AbortSignal extends EventTarget<Events, EventAttributes> {
/**
* AbortSignal cannot be constructed directly.
*/
constructor()
/**
* Returns `true` if this `AbortSignal`"s `AbortController` has signaled to abort, and `false` otherwise.
*/
readonly aborted: boolean
}
/**
* The AbortController.
* @see https://dom.spec.whatwg.org/#abortcontroller
*/
declare class AbortController {
/**
* Initialize this controller.
*/
constructor()
/**
* Returns the `AbortSignal` object associated with this object.
*/
readonly signal: AbortSignal
/**
* Abort and signal to any observers that the associated activity is to be aborted.
*/
abort(): void
}
export default AbortController
export { AbortController, AbortSignal }

127
node_modules/abort-controller/dist/abort-controller.js generated vendored Normal file
View File

@@ -0,0 +1,127 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var eventTargetShim = require('event-target-shim');
/**
* The signal class.
* @see https://dom.spec.whatwg.org/#abortsignal
*/
class AbortSignal extends eventTargetShim.EventTarget {
/**
* AbortSignal cannot be constructed directly.
*/
constructor() {
super();
throw new TypeError("AbortSignal cannot be constructed directly");
}
/**
* Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
*/
get aborted() {
const aborted = abortedFlags.get(this);
if (typeof aborted !== "boolean") {
throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
}
return aborted;
}
}
eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort");
/**
* Create an AbortSignal object.
*/
function createAbortSignal() {
const signal = Object.create(AbortSignal.prototype);
eventTargetShim.EventTarget.call(signal);
abortedFlags.set(signal, false);
return signal;
}
/**
* Abort a given signal.
*/
function abortSignal(signal) {
if (abortedFlags.get(signal) !== false) {
return;
}
abortedFlags.set(signal, true);
signal.dispatchEvent({ type: "abort" });
}
/**
* Aborted flag for each instances.
*/
const abortedFlags = new WeakMap();
// Properties should be enumerable.
Object.defineProperties(AbortSignal.prototype, {
aborted: { enumerable: true },
});
// `toString()` should return `"[object AbortSignal]"`
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortSignal",
});
}
/**
* The AbortController.
* @see https://dom.spec.whatwg.org/#abortcontroller
*/
class AbortController {
/**
* Initialize this controller.
*/
constructor() {
signals.set(this, createAbortSignal());
}
/**
* Returns the `AbortSignal` object associated with this object.
*/
get signal() {
return getSignal(this);
}
/**
* Abort and signal to any observers that the associated activity is to be aborted.
*/
abort() {
abortSignal(getSignal(this));
}
}
/**
* Associated signals.
*/
const signals = new WeakMap();
/**
* Get the associated signal of a given controller.
*/
function getSignal(controller) {
const signal = signals.get(controller);
if (signal == null) {
throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
}
return signal;
}
// Properties should be enumerable.
Object.defineProperties(AbortController.prototype, {
signal: { enumerable: true },
abort: { enumerable: true },
});
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortController",
});
}
exports.AbortController = AbortController;
exports.AbortSignal = AbortSignal;
exports.default = AbortController;
module.exports = AbortController
module.exports.AbortController = module.exports["default"] = AbortController
module.exports.AbortSignal = AbortSignal
//# sourceMappingURL=abort-controller.js.map

File diff suppressed because one or more lines are too long

118
node_modules/abort-controller/dist/abort-controller.mjs generated vendored Normal file
View File

@@ -0,0 +1,118 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
import { EventTarget, defineEventAttribute } from 'event-target-shim';
/**
* The signal class.
* @see https://dom.spec.whatwg.org/#abortsignal
*/
class AbortSignal extends EventTarget {
/**
* AbortSignal cannot be constructed directly.
*/
constructor() {
super();
throw new TypeError("AbortSignal cannot be constructed directly");
}
/**
* Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
*/
get aborted() {
const aborted = abortedFlags.get(this);
if (typeof aborted !== "boolean") {
throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
}
return aborted;
}
}
defineEventAttribute(AbortSignal.prototype, "abort");
/**
* Create an AbortSignal object.
*/
function createAbortSignal() {
const signal = Object.create(AbortSignal.prototype);
EventTarget.call(signal);
abortedFlags.set(signal, false);
return signal;
}
/**
* Abort a given signal.
*/
function abortSignal(signal) {
if (abortedFlags.get(signal) !== false) {
return;
}
abortedFlags.set(signal, true);
signal.dispatchEvent({ type: "abort" });
}
/**
* Aborted flag for each instances.
*/
const abortedFlags = new WeakMap();
// Properties should be enumerable.
Object.defineProperties(AbortSignal.prototype, {
aborted: { enumerable: true },
});
// `toString()` should return `"[object AbortSignal]"`
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortSignal",
});
}
/**
* The AbortController.
* @see https://dom.spec.whatwg.org/#abortcontroller
*/
class AbortController {
/**
* Initialize this controller.
*/
constructor() {
signals.set(this, createAbortSignal());
}
/**
* Returns the `AbortSignal` object associated with this object.
*/
get signal() {
return getSignal(this);
}
/**
* Abort and signal to any observers that the associated activity is to be aborted.
*/
abort() {
abortSignal(getSignal(this));
}
}
/**
* Associated signals.
*/
const signals = new WeakMap();
/**
* Get the associated signal of a given controller.
*/
function getSignal(controller) {
const signal = signals.get(controller);
if (signal == null) {
throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
}
return signal;
}
// Properties should be enumerable.
Object.defineProperties(AbortController.prototype, {
signal: { enumerable: true },
abort: { enumerable: true },
});
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortController",
});
}
export default AbortController;
export { AbortController, AbortSignal };
//# sourceMappingURL=abort-controller.mjs.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

97
node_modules/abort-controller/package.json generated vendored Normal file
View File

@@ -0,0 +1,97 @@
{
"name": "abort-controller",
"version": "3.0.0",
"description": "An implementation of WHATWG AbortController interface.",
"main": "dist/abort-controller",
"files": [
"dist",
"polyfill.*",
"browser.*"
],
"engines": {
"node": ">=6.5"
},
"dependencies": {
"event-target-shim": "^5.0.0"
},
"browser": "./browser.js",
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/plugin-transform-modules-commonjs": "^7.2.0",
"@babel/preset-env": "^7.3.0",
"@babel/register": "^7.0.0",
"@mysticatea/eslint-plugin": "^8.0.1",
"@mysticatea/spy": "^0.1.2",
"@types/mocha": "^5.2.5",
"@types/node": "^10.12.18",
"assert": "^1.4.1",
"codecov": "^3.1.0",
"dts-bundle-generator": "^2.0.0",
"eslint": "^5.12.1",
"karma": "^3.1.4",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage": "^1.1.2",
"karma-firefox-launcher": "^1.1.0",
"karma-growl-reporter": "^1.0.0",
"karma-ie-launcher": "^1.0.0",
"karma-mocha": "^1.3.0",
"karma-rollup-preprocessor": "^7.0.0-rc.2",
"mocha": "^5.2.0",
"npm-run-all": "^4.1.5",
"nyc": "^13.1.0",
"opener": "^1.5.1",
"rimraf": "^2.6.3",
"rollup": "^1.1.2",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-babel-minify": "^7.0.0",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-plugin-sourcemaps": "^0.4.2",
"rollup-plugin-typescript": "^1.0.0",
"rollup-watch": "^4.3.1",
"ts-node": "^8.0.1",
"type-tester": "^1.0.0",
"typescript": "^3.2.4"
},
"scripts": {
"preversion": "npm test",
"version": "npm run -s build && git add dist/*",
"postversion": "git push && git push --tags",
"clean": "rimraf .nyc_output coverage",
"coverage": "opener coverage/lcov-report/index.html",
"lint": "eslint . --ext .ts",
"build": "run-s -s build:*",
"build:rollup": "rollup -c",
"build:dts": "dts-bundle-generator -o dist/abort-controller.d.ts src/abort-controller.ts && ts-node scripts/fix-dts",
"test": "run-s -s lint test:*",
"test:mocha": "nyc mocha test/*.ts",
"test:karma": "karma start --single-run",
"watch": "run-p -s watch:*",
"watch:mocha": "mocha test/*.ts --require ts-node/register --watch-extensions ts --watch --growl",
"watch:karma": "karma start --watch",
"codecov": "codecov"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mysticatea/abort-controller.git"
},
"keywords": [
"w3c",
"whatwg",
"event",
"events",
"abort",
"cancel",
"abortcontroller",
"abortsignal",
"controller",
"signal",
"shim"
],
"author": "Toru Nagashima (https://github.com/mysticatea)",
"license": "MIT",
"bugs": {
"url": "https://github.com/mysticatea/abort-controller/issues"
},
"homepage": "https://github.com/mysticatea/abort-controller#readme"
}

21
node_modules/abort-controller/polyfill.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
/*globals require, self, window */
"use strict"
const ac = require("./dist/abort-controller")
/*eslint-disable @mysticatea/prettier */
const g =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
if (g) {
if (typeof g.AbortController === "undefined") {
g.AbortController = ac.AbortController
}
if (typeof g.AbortSignal === "undefined") {
g.AbortSignal = ac.AbortSignal
}
}

19
node_modules/abort-controller/polyfill.mjs generated vendored Normal file
View File

@@ -0,0 +1,19 @@
/*globals self, window */
import * as ac from "./dist/abort-controller"
/*eslint-disable @mysticatea/prettier */
const g =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
if (g) {
if (typeof g.AbortController === "undefined") {
g.AbortController = ac.AbortController
}
if (typeof g.AbortSignal === "undefined") {
g.AbortSignal = ac.AbortSignal
}
}

20
node_modules/ajv/.tonic_example.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});
var schema = {
"properties": {
"foo": { "type": "string" },
"bar": { "type": "number", "maximum": 3 }
}
};
var validate = ajv.compile(schema);
test({"foo": "abc", "bar": 2});
test({"foo": 2, "bar": 4});
function test(data) {
var valid = validate(data);
if (valid) console.log('Valid!');
else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}

22
node_modules/ajv/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015-2017 Evgeny Poberezkin
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.

1497
node_modules/ajv/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

7189
node_modules/ajv/dist/ajv.bundle.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

3
node_modules/ajv/dist/ajv.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/ajv/dist/ajv.min.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

397
node_modules/ajv/lib/ajv.d.ts generated vendored Normal file
View File

@@ -0,0 +1,397 @@
declare var ajv: {
(options?: ajv.Options): ajv.Ajv;
new(options?: ajv.Options): ajv.Ajv;
ValidationError: typeof AjvErrors.ValidationError;
MissingRefError: typeof AjvErrors.MissingRefError;
$dataMetaSchema: object;
}
declare namespace AjvErrors {
class ValidationError extends Error {
constructor(errors: Array<ajv.ErrorObject>);
message: string;
errors: Array<ajv.ErrorObject>;
ajv: true;
validation: true;
}
class MissingRefError extends Error {
constructor(baseId: string, ref: string, message?: string);
static message: (baseId: string, ref: string) => string;
message: string;
missingRef: string;
missingSchema: string;
}
}
declare namespace ajv {
type ValidationError = AjvErrors.ValidationError;
type MissingRefError = AjvErrors.MissingRefError;
interface Ajv {
/**
* Validate data using schema
* Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default).
* @param {string|object|Boolean} schemaKeyRef key, ref or schema object
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike<any>;
/**
* Create validating function for passed schema.
* @param {object|Boolean} schema schema object
* @return {Function} validating function
*/
compile(schema: object | boolean): ValidateFunction;
/**
* Creates validating function for passed schema with asynchronous loading of missing schemas.
* `loadSchema` option should be a function that accepts schema uri and node-style callback.
* @this Ajv
* @param {object|Boolean} schema schema object
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
* @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function.
* @return {PromiseLike<ValidateFunction>} validating function
*/
compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike<ValidateFunction>;
/**
* Adds schema to the instance.
* @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {string} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @return {Ajv} this for method chaining
*/
addSchema(schema: Array<object> | object, key?: string): Ajv;
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @param {object} schema schema object
* @param {string} key optional schema key
* @return {Ajv} this for method chaining
*/
addMetaSchema(schema: object, key?: string): Ajv;
/**
* Validate schema
* @param {object|Boolean} schema schema to validate
* @return {Boolean} true if schema is valid
*/
validateSchema(schema: object | boolean): boolean;
/**
* Get compiled schema from the instance by `key` or `ref`.
* @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
* @return {Function} schema validating function (with property `schema`). Returns undefined if keyRef can't be resolved to an existing schema.
*/
getSchema(keyRef: string): ValidateFunction | undefined;
/**
* Remove cached schema(s).
* If no parameter is passed all schemas but meta-schemas are removed.
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
* @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object
* @return {Ajv} this for method chaining
*/
removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv;
/**
* Add custom format
* @param {string} name format name
* @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
* @return {Ajv} this for method chaining
*/
addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv;
/**
* Define custom keyword
* @this Ajv
* @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords.
* @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
* @return {Ajv} this for method chaining
*/
addKeyword(keyword: string, definition: KeywordDefinition): Ajv;
/**
* Get keyword definition
* @this Ajv
* @param {string} keyword pre-defined or custom keyword.
* @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
*/
getKeyword(keyword: string): object | boolean;
/**
* Remove keyword
* @this Ajv
* @param {string} keyword pre-defined or custom keyword.
* @return {Ajv} this for method chaining
*/
removeKeyword(keyword: string): Ajv;
/**
* Validate keyword
* @this Ajv
* @param {object} definition keyword definition object
* @param {boolean} throwError true to throw exception if definition is invalid
* @return {boolean} validation result
*/
validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean;
/**
* Convert array of error message objects to string
* @param {Array<object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {object} options optional options with properties `separator` and `dataVar`.
* @return {string} human readable string with all errors descriptions
*/
errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string;
errors?: Array<ErrorObject> | null;
_opts: Options;
}
interface CustomLogger {
log(...args: any[]): any;
warn(...args: any[]): any;
error(...args: any[]): any;
}
interface ValidateFunction {
(
data: any,
dataPath?: string,
parentData?: object | Array<any>,
parentDataProperty?: string | number,
rootData?: object | Array<any>
): boolean | PromiseLike<any>;
schema?: object | boolean;
errors?: null | Array<ErrorObject>;
refs?: object;
refVal?: Array<any>;
root?: ValidateFunction | object;
$async?: true;
source?: object;
}
interface Options {
$data?: boolean;
allErrors?: boolean;
verbose?: boolean;
jsonPointers?: boolean;
uniqueItems?: boolean;
unicode?: boolean;
format?: false | string;
formats?: object;
keywords?: object;
unknownFormats?: true | string[] | 'ignore';
schemas?: Array<object> | object;
schemaId?: '$id' | 'id' | 'auto';
missingRefs?: true | 'ignore' | 'fail';
extendRefs?: true | 'ignore' | 'fail';
loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike<object | boolean>;
removeAdditional?: boolean | 'all' | 'failing';
useDefaults?: boolean | 'empty' | 'shared';
coerceTypes?: boolean | 'array';
strictDefaults?: boolean | 'log';
strictKeywords?: boolean | 'log';
strictNumbers?: boolean;
async?: boolean | string;
transpile?: string | ((code: string) => string);
meta?: boolean | object;
validateSchema?: boolean | 'log';
addUsedSchema?: boolean;
inlineRefs?: boolean | number;
passContext?: boolean;
loopRequired?: number;
ownProperties?: boolean;
multipleOfPrecision?: boolean | number;
errorDataPath?: string,
messages?: boolean;
sourceCode?: boolean;
processCode?: (code: string, schema: object) => string;
cache?: object;
logger?: CustomLogger | false;
nullable?: boolean;
serialize?: ((schema: object | boolean) => any) | false;
}
type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike<any>);
type NumberFormatValidator = ((data: number) => boolean | PromiseLike<any>);
interface NumberFormatDefinition {
type: "number",
validate: NumberFormatValidator;
compare?: (data1: number, data2: number) => number;
async?: boolean;
}
interface StringFormatDefinition {
type?: "string",
validate: FormatValidator;
compare?: (data1: string, data2: string) => number;
async?: boolean;
}
type FormatDefinition = NumberFormatDefinition | StringFormatDefinition;
interface KeywordDefinition {
type?: string | Array<string>;
async?: boolean;
$data?: boolean;
errors?: boolean | string;
metaSchema?: object;
// schema: false makes validate not to expect schema (ValidateFunction)
schema?: boolean;
statements?: boolean;
dependencies?: Array<string>;
modifying?: boolean;
valid?: boolean;
// one and only one of the following properties should be present
validate?: SchemaValidateFunction | ValidateFunction;
compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction;
macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean;
inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string;
}
interface CompilationContext {
level: number;
dataLevel: number;
dataPathArr: string[];
schema: any;
schemaPath: string;
baseId: string;
async: boolean;
opts: Options;
formats: {
[index: string]: FormatDefinition | undefined;
};
keywords: {
[index: string]: KeywordDefinition | undefined;
};
compositeRule: boolean;
validate: (schema: object) => boolean;
util: {
copy(obj: any, target?: any): any;
toHash(source: string[]): { [index: string]: true | undefined };
equal(obj: any, target: any): boolean;
getProperty(str: string): string;
schemaHasRules(schema: object, rules: any): string;
escapeQuotes(str: string): string;
toQuotedString(str: string): string;
getData(jsonPointer: string, dataLevel: number, paths: string[]): string;
escapeJsonPointer(str: string): string;
unescapeJsonPointer(str: string): string;
escapeFragment(str: string): string;
unescapeFragment(str: string): string;
};
self: Ajv;
}
interface SchemaValidateFunction {
(
schema: any,
data: any,
parentSchema?: object,
dataPath?: string,
parentData?: object | Array<any>,
parentDataProperty?: string | number,
rootData?: object | Array<any>
): boolean | PromiseLike<any>;
errors?: Array<ErrorObject>;
}
interface ErrorsTextOptions {
separator?: string;
dataVar?: string;
}
interface ErrorObject {
keyword: string;
dataPath: string;
schemaPath: string;
params: ErrorParameters;
// Added to validation errors of propertyNames keyword schema
propertyName?: string;
// Excluded if messages set to false.
message?: string;
// These are added with the `verbose` option.
schema?: any;
parentSchema?: object;
data?: any;
}
type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams |
DependenciesParams | FormatParams | ComparisonParams |
MultipleOfParams | PatternParams | RequiredParams |
TypeParams | UniqueItemsParams | CustomParams |
PatternRequiredParams | PropertyNamesParams |
IfParams | SwitchParams | NoParams | EnumParams;
interface RefParams {
ref: string;
}
interface LimitParams {
limit: number;
}
interface AdditionalPropertiesParams {
additionalProperty: string;
}
interface DependenciesParams {
property: string;
missingProperty: string;
depsCount: number;
deps: string;
}
interface FormatParams {
format: string
}
interface ComparisonParams {
comparison: string;
limit: number | string;
exclusive: boolean;
}
interface MultipleOfParams {
multipleOf: number;
}
interface PatternParams {
pattern: string;
}
interface RequiredParams {
missingProperty: string;
}
interface TypeParams {
type: string;
}
interface UniqueItemsParams {
i: number;
j: number;
}
interface CustomParams {
keyword: string;
}
interface PatternRequiredParams {
missingPattern: string;
}
interface PropertyNamesParams {
propertyName: string;
}
interface IfParams {
failingKeyword: string;
}
interface SwitchParams {
caseIndex: number;
}
interface NoParams { }
interface EnumParams {
allowedValues: Array<any>;
}
}
export = ajv;

506
node_modules/ajv/lib/ajv.js generated vendored Normal file
View File

@@ -0,0 +1,506 @@
'use strict';
var compileSchema = require('./compile')
, resolve = require('./compile/resolve')
, Cache = require('./cache')
, SchemaObject = require('./compile/schema_obj')
, stableStringify = require('fast-json-stable-stringify')
, formats = require('./compile/formats')
, rules = require('./compile/rules')
, $dataMetaSchema = require('./data')
, util = require('./compile/util');
module.exports = Ajv;
Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;
Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;
Ajv.prototype.compileAsync = require('./compile/async');
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;
var errorClasses = require('./compile/error_classes');
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
var META_SUPPORT_DATA = ['/properties'];
/**
* Creates validator instance.
* Usage: `Ajv(opts)`
* @param {Object} opts optional options
* @return {Object} ajv instance
*/
function Ajv(opts) {
if (!(this instanceof Ajv)) return new Ajv(opts);
opts = this._opts = util.copy(opts) || {};
setLogger(this);
this._schemas = {};
this._refs = {};
this._fragments = {};
this._formats = formats(opts.format);
this._cache = opts.cache || new Cache;
this._loadingSchemas = {};
this._compilations = [];
this.RULES = rules();
this._getId = chooseGetId(opts);
opts.loopRequired = opts.loopRequired || Infinity;
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
if (opts.serialize === undefined) opts.serialize = stableStringify;
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
if (opts.keywords) addInitialKeywords(this);
addDefaultMetaSchema(this);
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
addInitialSchemas(this);
}
/**
* Validate data using schema
* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
* @this Ajv
* @param {String|Object} schemaKeyRef key, ref or schema object
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
function validate(schemaKeyRef, data) {
var v;
if (typeof schemaKeyRef == 'string') {
v = this.getSchema(schemaKeyRef);
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
} else {
var schemaObj = this._addSchema(schemaKeyRef);
v = schemaObj.validate || this._compile(schemaObj);
}
var valid = v(data);
if (v.$async !== true) this.errors = v.errors;
return valid;
}
/**
* Create validating function for passed schema.
* @this Ajv
* @param {Object} schema schema object
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
* @return {Function} validating function
*/
function compile(schema, _meta) {
var schemaObj = this._addSchema(schema, undefined, _meta);
return schemaObj.validate || this._compile(schemaObj);
}
/**
* Adds schema to the instance.
* @this Ajv
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
* @return {Ajv} this for method chaining
*/
function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
return this;
}
var id = this._getId(schema);
if (id !== undefined && typeof id != 'string')
throw new Error('schema id must be string');
key = resolve.normalizeId(key || id);
checkUnique(this, key);
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
return this;
}
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @this Ajv
* @param {Object} schema schema object
* @param {String} key optional schema key
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
* @return {Ajv} this for method chaining
*/
function addMetaSchema(schema, key, skipValidation) {
this.addSchema(schema, key, skipValidation, true);
return this;
}
/**
* Validate schema
* @this Ajv
* @param {Object} schema schema to validate
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
* @return {Boolean} true if schema is valid
*/
function validateSchema(schema, throwOrLogError) {
var $schema = schema.$schema;
if ($schema !== undefined && typeof $schema != 'string')
throw new Error('$schema must be a string');
$schema = $schema || this._opts.defaultMeta || defaultMeta(this);
if (!$schema) {
this.logger.warn('meta-schema not available');
this.errors = null;
return true;
}
var valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
var message = 'schema is invalid: ' + this.errorsText();
if (this._opts.validateSchema == 'log') this.logger.error(message);
else throw new Error(message);
}
return valid;
}
function defaultMeta(self) {
var meta = self._opts.meta;
self._opts.defaultMeta = typeof meta == 'object'
? self._getId(meta) || meta
: self.getSchema(META_SCHEMA_ID)
? META_SCHEMA_ID
: undefined;
return self._opts.defaultMeta;
}
/**
* Get compiled schema from the instance by `key` or `ref`.
* @this Ajv
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
* @return {Function} schema validating function (with property `schema`).
*/
function getSchema(keyRef) {
var schemaObj = _getSchemaObj(this, keyRef);
switch (typeof schemaObj) {
case 'object': return schemaObj.validate || this._compile(schemaObj);
case 'string': return this.getSchema(schemaObj);
case 'undefined': return _getSchemaFragment(this, keyRef);
}
}
function _getSchemaFragment(self, ref) {
var res = resolve.schema.call(self, { schema: {} }, ref);
if (res) {
var schema = res.schema
, root = res.root
, baseId = res.baseId;
var v = compileSchema.call(self, schema, root, undefined, baseId);
self._fragments[ref] = new SchemaObject({
ref: ref,
fragment: true,
schema: schema,
root: root,
baseId: baseId,
validate: v
});
return v;
}
}
function _getSchemaObj(self, keyRef) {
keyRef = resolve.normalizeId(keyRef);
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}
/**
* Remove cached schema(s).
* If no parameter is passed all schemas but meta-schemas are removed.
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
* @this Ajv
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
* @return {Ajv} this for method chaining
*/
function removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
_removeAllSchemas(this, this._schemas, schemaKeyRef);
_removeAllSchemas(this, this._refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case 'undefined':
_removeAllSchemas(this, this._schemas);
_removeAllSchemas(this, this._refs);
this._cache.clear();
return this;
case 'string':
var schemaObj = _getSchemaObj(this, schemaKeyRef);
if (schemaObj) this._cache.del(schemaObj.cacheKey);
delete this._schemas[schemaKeyRef];
delete this._refs[schemaKeyRef];
return this;
case 'object':
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
this._cache.del(cacheKey);
var id = this._getId(schemaKeyRef);
if (id) {
id = resolve.normalizeId(id);
delete this._schemas[id];
delete this._refs[id];
}
}
return this;
}
function _removeAllSchemas(self, schemas, regex) {
for (var keyRef in schemas) {
var schemaObj = schemas[keyRef];
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
self._cache.del(schemaObj.cacheKey);
delete schemas[keyRef];
}
}
}
/* @this Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
if (typeof schema != 'object' && typeof schema != 'boolean')
throw new Error('schema should be object or boolean');
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schema) : schema;
var cached = this._cache.get(cacheKey);
if (cached) return cached;
shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
var id = resolve.normalizeId(this._getId(schema));
if (id && shouldAddSchema) checkUnique(this, id);
var willValidate = this._opts.validateSchema !== false && !skipValidation;
var recursiveMeta;
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
this.validateSchema(schema, true);
var localRefs = resolve.ids.call(this, schema);
var schemaObj = new SchemaObject({
id: id,
schema: schema,
localRefs: localRefs,
cacheKey: cacheKey,
meta: meta
});
if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
this._cache.put(cacheKey, schemaObj);
if (willValidate && recursiveMeta) this.validateSchema(schema, true);
return schemaObj;
}
/* @this Ajv */
function _compile(schemaObj, root) {
if (schemaObj.compiling) {
schemaObj.validate = callValidate;
callValidate.schema = schemaObj.schema;
callValidate.errors = null;
callValidate.root = root ? root : callValidate;
if (schemaObj.schema.$async === true)
callValidate.$async = true;
return callValidate;
}
schemaObj.compiling = true;
var currentOpts;
if (schemaObj.meta) {
currentOpts = this._opts;
this._opts = this._metaOpts;
}
var v;
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
catch(e) {
delete schemaObj.validate;
throw e;
}
finally {
schemaObj.compiling = false;
if (schemaObj.meta) this._opts = currentOpts;
}
schemaObj.validate = v;
schemaObj.refs = v.refs;
schemaObj.refVal = v.refVal;
schemaObj.root = v.root;
return v;
/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var _validate = schemaObj.validate;
var result = _validate.apply(this, arguments);
callValidate.errors = _validate.errors;
return result;
}
}
function chooseGetId(opts) {
switch (opts.schemaId) {
case 'auto': return _get$IdOrId;
case 'id': return _getId;
default: return _get$Id;
}
}
/* @this Ajv */
function _getId(schema) {
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
return schema.id;
}
/* @this Ajv */
function _get$Id(schema) {
if (schema.id) this.logger.warn('schema id ignored', schema.id);
return schema.$id;
}
function _get$IdOrId(schema) {
if (schema.$id && schema.id && schema.$id != schema.id)
throw new Error('schema $id is different from id');
return schema.$id || schema.id;
}
/**
* Convert array of error message objects to string
* @this Ajv
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {Object} options optional options with properties `separator` and `dataVar`.
* @return {String} human readable string with all errors descriptions
*/
function errorsText(errors, options) {
errors = errors || this.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = options.separator === undefined ? ', ' : options.separator;
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
var text = '';
for (var i=0; i<errors.length; i++) {
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
}
/**
* Add custom format
* @this Ajv
* @param {String} name format name
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
* @return {Ajv} this for method chaining
*/
function addFormat(name, format) {
if (typeof format == 'string') format = new RegExp(format);
this._formats[name] = format;
return this;
}
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = require('./refs/data.json');
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
}
if (self._opts.meta === false) return;
var metaSchema = require('./refs/json-schema-draft-07.json');
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}
function addInitialSchemas(self) {
var optsSchemas = self._opts.schemas;
if (!optsSchemas) return;
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}
function addInitialFormats(self) {
for (var name in self._opts.formats) {
var format = self._opts.formats[name];
self.addFormat(name, format);
}
}
function addInitialKeywords(self) {
for (var name in self._opts.keywords) {
var keyword = self._opts.keywords[name];
self.addKeyword(name, keyword);
}
}
function checkUnique(self, id) {
if (self._schemas[id] || self._refs[id])
throw new Error('schema with key or id "' + id + '" already exists');
}
function getMetaSchemaOptions(self) {
var metaOpts = util.copy(self._opts);
for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
delete metaOpts[META_IGNORE_OPTIONS[i]];
return metaOpts;
}
function setLogger(self) {
var logger = self._opts.logger;
if (logger === false) {
self.logger = {log: noop, warn: noop, error: noop};
} else {
if (logger === undefined) logger = console;
if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
throw new Error('logger must implement log, warn and error methods');
self.logger = logger;
}
}
function noop() {}

26
node_modules/ajv/lib/cache.js generated vendored Normal file
View File

@@ -0,0 +1,26 @@
'use strict';
var Cache = module.exports = function Cache() {
this._cache = {};
};
Cache.prototype.put = function Cache_put(key, value) {
this._cache[key] = value;
};
Cache.prototype.get = function Cache_get(key) {
return this._cache[key];
};
Cache.prototype.del = function Cache_del(key) {
delete this._cache[key];
};
Cache.prototype.clear = function Cache_clear() {
this._cache = {};
};

90
node_modules/ajv/lib/compile/async.js generated vendored Normal file
View File

@@ -0,0 +1,90 @@
'use strict';
var MissingRefError = require('./error_classes').MissingRef;
module.exports = compileAsync;
/**
* Creates validating function for passed schema with asynchronous loading of missing schemas.
* `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
* @this Ajv
* @param {Object} schema schema object
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
* @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
* @return {Promise} promise that resolves with a validating function.
*/
function compileAsync(schema, meta, callback) {
/* eslint no-shadow: 0 */
/* global Promise */
/* jshint validthis: true */
var self = this;
if (typeof this._opts.loadSchema != 'function')
throw new Error('options.loadSchema should be a function');
if (typeof meta == 'function') {
callback = meta;
meta = undefined;
}
var p = loadMetaSchemaOf(schema).then(function () {
var schemaObj = self._addSchema(schema, undefined, meta);
return schemaObj.validate || _compileAsync(schemaObj);
});
if (callback) {
p.then(
function(v) { callback(null, v); },
callback
);
}
return p;
function loadMetaSchemaOf(sch) {
var $schema = sch.$schema;
return $schema && !self.getSchema($schema)
? compileAsync.call(self, { $ref: $schema }, true)
: Promise.resolve();
}
function _compileAsync(schemaObj) {
try { return self._compile(schemaObj); }
catch(e) {
if (e instanceof MissingRefError) return loadMissingSchema(e);
throw e;
}
function loadMissingSchema(e) {
var ref = e.missingSchema;
if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
var schemaPromise = self._loadingSchemas[ref];
if (!schemaPromise) {
schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
schemaPromise.then(removePromise, removePromise);
}
return schemaPromise.then(function (sch) {
if (!added(ref)) {
return loadMetaSchemaOf(sch).then(function () {
if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
});
}
}).then(function() {
return _compileAsync(schemaObj);
});
function removePromise() {
delete self._loadingSchemas[ref];
}
function added(ref) {
return self._refs[ref] || self._schemas[ref];
}
}
}
}

5
node_modules/ajv/lib/compile/equal.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
'use strict';
// do NOT remove this file - it would break pre-compiled schemas
// https://github.com/ajv-validator/ajv/issues/889
module.exports = require('fast-deep-equal');

34
node_modules/ajv/lib/compile/error_classes.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
'use strict';
var resolve = require('./resolve');
module.exports = {
Validation: errorSubclass(ValidationError),
MissingRef: errorSubclass(MissingRefError)
};
function ValidationError(errors) {
this.message = 'validation failed';
this.errors = errors;
this.ajv = this.validation = true;
}
MissingRefError.message = function (baseId, ref) {
return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
};
function MissingRefError(baseId, ref, message) {
this.message = message || MissingRefError.message(baseId, ref);
this.missingRef = resolve.url(baseId, ref);
this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
}
function errorSubclass(Subclass) {
Subclass.prototype = Object.create(Error.prototype);
Subclass.prototype.constructor = Subclass;
return Subclass;
}

142
node_modules/ajv/lib/compile/formats.js generated vendored Normal file
View File

@@ -0,0 +1,142 @@
'use strict';
var util = require('./util');
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
// uri-template: https://tools.ietf.org/html/rfc6570
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
// For the source: https://gist.github.com/dperini/729294
// For test cases: https://mathiasbynens.be/demo/url-regex
// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
module.exports = formats;
function formats(mode) {
mode = mode == 'full' ? 'full' : 'fast';
return util.copy(formats[mode]);
}
formats.fast = {
// date: http://tools.ietf.org/html/rfc3339#section-5.6
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6
time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
'uri-template': URITEMPLATE,
url: URL,
// email (sources from jsen validator):
// http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
// http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
hostname: HOSTNAME,
// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
// optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
regex: regex,
// uuid: http://tools.ietf.org/html/rfc4122
uuid: UUID,
// JSON-pointer: https://tools.ietf.org/html/rfc6901
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
'json-pointer': JSON_POINTER,
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
'relative-json-pointer': RELATIVE_JSON_POINTER
};
formats.full = {
date: date,
time: time,
'date-time': date_time,
uri: uri,
'uri-reference': URIREF,
'uri-template': URITEMPLATE,
url: URL,
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
hostname: HOSTNAME,
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
regex: regex,
uuid: UUID,
'json-pointer': JSON_POINTER,
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
'relative-json-pointer': RELATIVE_JSON_POINTER
};
function isLeapYear(year) {
// https://tools.ietf.org/html/rfc3339#appendix-C
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function date(str) {
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6
var matches = str.match(DATE);
if (!matches) return false;
var year = +matches[1];
var month = +matches[2];
var day = +matches[3];
return month >= 1 && month <= 12 && day >= 1 &&
day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
}
function time(str, full) {
var matches = str.match(TIME);
if (!matches) return false;
var hour = matches[1];
var minute = matches[2];
var second = matches[3];
var timeZone = matches[5];
return ((hour <= 23 && minute <= 59 && second <= 59) ||
(hour == 23 && minute == 59 && second == 60)) &&
(!full || timeZone);
}
var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
// http://tools.ietf.org/html/rfc3339#section-5.6
var dateTime = str.split(DATE_TIME_SEPARATOR);
return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
}
var NOT_URI_FRAGMENT = /\/|:/;
function uri(str) {
// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
var Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
if (Z_ANCHOR.test(str)) return false;
try {
new RegExp(str);
return true;
} catch(e) {
return false;
}
}

387
node_modules/ajv/lib/compile/index.js generated vendored Normal file
View File

@@ -0,0 +1,387 @@
'use strict';
var resolve = require('./resolve')
, util = require('./util')
, errorClasses = require('./error_classes')
, stableStringify = require('fast-json-stable-stringify');
var validateGenerator = require('../dotjs/validate');
/**
* Functions below are used inside compiled validations function
*/
var ucs2length = util.ucs2length;
var equal = require('fast-deep-equal');
// this error is thrown by async schemas to return validation errors via exception
var ValidationError = errorClasses.Validation;
module.exports = compile;
/**
* Compiles schema to validation function
* @this Ajv
* @param {Object} schema schema object
* @param {Object} root object with information about the root schema for this schema
* @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
* @param {String} baseId base ID for IDs in the schema
* @return {Function} validation function
*/
function compile(schema, root, localRefs, baseId) {
/* jshint validthis: true, evil: true */
/* eslint no-shadow: 0 */
var self = this
, opts = this._opts
, refVal = [ undefined ]
, refs = {}
, patterns = []
, patternsHash = {}
, defaults = []
, defaultsHash = {}
, customRules = [];
root = root || { schema: schema, refVal: refVal, refs: refs };
var c = checkCompiling.call(this, schema, root, baseId);
var compilation = this._compilations[c.index];
if (c.compiling) return (compilation.callValidate = callValidate);
var formats = this._formats;
var RULES = this.RULES;
try {
var v = localCompile(schema, root, localRefs, baseId);
compilation.validate = v;
var cv = compilation.callValidate;
if (cv) {
cv.schema = v.schema;
cv.errors = null;
cv.refs = v.refs;
cv.refVal = v.refVal;
cv.root = v.root;
cv.$async = v.$async;
if (opts.sourceCode) cv.source = v.source;
}
return v;
} finally {
endCompiling.call(this, schema, root, baseId);
}
/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var validate = compilation.validate;
var result = validate.apply(this, arguments);
callValidate.errors = validate.errors;
return result;
}
function localCompile(_schema, _root, localRefs, baseId) {
var isRoot = !_root || (_root && _root.schema == _schema);
if (_root.schema != root.schema)
return compile.call(self, _schema, _root, localRefs, baseId);
var $async = _schema.$async === true;
var sourceCode = validateGenerator({
isTop: true,
schema: _schema,
isRoot: isRoot,
baseId: baseId,
root: _root,
schemaPath: '',
errSchemaPath: '#',
errorPath: '""',
MissingRefError: errorClasses.MissingRef,
RULES: RULES,
validate: validateGenerator,
util: util,
resolve: resolve,
resolveRef: resolveRef,
usePattern: usePattern,
useDefault: useDefault,
useCustomRule: useCustomRule,
opts: opts,
formats: formats,
logger: self.logger,
self: self
});
sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
+ vars(defaults, defaultCode) + vars(customRules, customRuleCode)
+ sourceCode;
if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
// console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
var validate;
try {
var makeValidate = new Function(
'self',
'RULES',
'formats',
'root',
'refVal',
'defaults',
'customRules',
'equal',
'ucs2length',
'ValidationError',
sourceCode
);
validate = makeValidate(
self,
RULES,
formats,
root,
refVal,
defaults,
customRules,
equal,
ucs2length,
ValidationError
);
refVal[0] = validate;
} catch(e) {
self.logger.error('Error compiling schema, function code:', sourceCode);
throw e;
}
validate.schema = _schema;
validate.errors = null;
validate.refs = refs;
validate.refVal = refVal;
validate.root = isRoot ? validate : _root;
if ($async) validate.$async = true;
if (opts.sourceCode === true) {
validate.source = {
code: sourceCode,
patterns: patterns,
defaults: defaults
};
}
return validate;
}
function resolveRef(baseId, ref, isRoot) {
ref = resolve.url(baseId, ref);
var refIndex = refs[ref];
var _refVal, refCode;
if (refIndex !== undefined) {
_refVal = refVal[refIndex];
refCode = 'refVal[' + refIndex + ']';
return resolvedRef(_refVal, refCode);
}
if (!isRoot && root.refs) {
var rootRefId = root.refs[ref];
if (rootRefId !== undefined) {
_refVal = root.refVal[rootRefId];
refCode = addLocalRef(ref, _refVal);
return resolvedRef(_refVal, refCode);
}
}
refCode = addLocalRef(ref);
var v = resolve.call(self, localCompile, root, ref);
if (v === undefined) {
var localSchema = localRefs && localRefs[ref];
if (localSchema) {
v = resolve.inlineRef(localSchema, opts.inlineRefs)
? localSchema
: compile.call(self, localSchema, root, localRefs, baseId);
}
}
if (v === undefined) {
removeLocalRef(ref);
} else {
replaceLocalRef(ref, v);
return resolvedRef(v, refCode);
}
}
function addLocalRef(ref, v) {
var refId = refVal.length;
refVal[refId] = v;
refs[ref] = refId;
return 'refVal' + refId;
}
function removeLocalRef(ref) {
delete refs[ref];
}
function replaceLocalRef(ref, v) {
var refId = refs[ref];
refVal[refId] = v;
}
function resolvedRef(refVal, code) {
return typeof refVal == 'object' || typeof refVal == 'boolean'
? { code: code, schema: refVal, inline: true }
: { code: code, $async: refVal && !!refVal.$async };
}
function usePattern(regexStr) {
var index = patternsHash[regexStr];
if (index === undefined) {
index = patternsHash[regexStr] = patterns.length;
patterns[index] = regexStr;
}
return 'pattern' + index;
}
function useDefault(value) {
switch (typeof value) {
case 'boolean':
case 'number':
return '' + value;
case 'string':
return util.toQuotedString(value);
case 'object':
if (value === null) return 'null';
var valueStr = stableStringify(value);
var index = defaultsHash[valueStr];
if (index === undefined) {
index = defaultsHash[valueStr] = defaults.length;
defaults[index] = value;
}
return 'default' + index;
}
}
function useCustomRule(rule, schema, parentSchema, it) {
if (self._opts.validateSchema !== false) {
var deps = rule.definition.dependencies;
if (deps && !deps.every(function(keyword) {
return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
}))
throw new Error('parent schema must have all required keywords: ' + deps.join(','));
var validateSchema = rule.definition.validateSchema;
if (validateSchema) {
var valid = validateSchema(schema);
if (!valid) {
var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
if (self._opts.validateSchema == 'log') self.logger.error(message);
else throw new Error(message);
}
}
}
var compile = rule.definition.compile
, inline = rule.definition.inline
, macro = rule.definition.macro;
var validate;
if (compile) {
validate = compile.call(self, schema, parentSchema, it);
} else if (macro) {
validate = macro.call(self, schema, parentSchema, it);
if (opts.validateSchema !== false) self.validateSchema(validate, true);
} else if (inline) {
validate = inline.call(self, it, rule.keyword, schema, parentSchema);
} else {
validate = rule.definition.validate;
if (!validate) return;
}
if (validate === undefined)
throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
var index = customRules.length;
customRules[index] = validate;
return {
code: 'customRule' + index,
validate: validate
};
}
}
/**
* Checks if the schema is currently compiled
* @this Ajv
* @param {Object} schema schema to compile
* @param {Object} root root object
* @param {String} baseId base schema ID
* @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
*/
function checkCompiling(schema, root, baseId) {
/* jshint validthis: true */
var index = compIndex.call(this, schema, root, baseId);
if (index >= 0) return { index: index, compiling: true };
index = this._compilations.length;
this._compilations[index] = {
schema: schema,
root: root,
baseId: baseId
};
return { index: index, compiling: false };
}
/**
* Removes the schema from the currently compiled list
* @this Ajv
* @param {Object} schema schema to compile
* @param {Object} root root object
* @param {String} baseId base schema ID
*/
function endCompiling(schema, root, baseId) {
/* jshint validthis: true */
var i = compIndex.call(this, schema, root, baseId);
if (i >= 0) this._compilations.splice(i, 1);
}
/**
* Index of schema compilation in the currently compiled list
* @this Ajv
* @param {Object} schema schema to compile
* @param {Object} root root object
* @param {String} baseId base schema ID
* @return {Integer} compilation index
*/
function compIndex(schema, root, baseId) {
/* jshint validthis: true */
for (var i=0; i<this._compilations.length; i++) {
var c = this._compilations[i];
if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
}
return -1;
}
function patternCode(i, patterns) {
return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
}
function defaultCode(i) {
return 'var default' + i + ' = defaults[' + i + '];';
}
function refValCode(i, refVal) {
return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
}
function customRuleCode(i) {
return 'var customRule' + i + ' = customRules[' + i + '];';
}
function vars(arr, statement) {
if (!arr.length) return '';
var code = '';
for (var i=0; i<arr.length; i++)
code += statement(i, arr);
return code;
}

270
node_modules/ajv/lib/compile/resolve.js generated vendored Normal file
View File

@@ -0,0 +1,270 @@
'use strict';
var URI = require('uri-js')
, equal = require('fast-deep-equal')
, util = require('./util')
, SchemaObject = require('./schema_obj')
, traverse = require('json-schema-traverse');
module.exports = resolve;
resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;
/**
* [resolve and compile the references ($ref)]
* @this Ajv
* @param {Function} compile reference to schema compilation funciton (localCompile)
* @param {Object} root object with information about the root schema for the current schema
* @param {String} ref reference to resolve
* @return {Object|Function} schema object (if the schema can be inlined) or validation function
*/
function resolve(compile, root, ref) {
/* jshint validthis: true */
var refVal = this._refs[ref];
if (typeof refVal == 'string') {
if (this._refs[refVal]) refVal = this._refs[refVal];
else return resolve.call(this, compile, root, refVal);
}
refVal = refVal || this._schemas[ref];
if (refVal instanceof SchemaObject) {
return inlineRef(refVal.schema, this._opts.inlineRefs)
? refVal.schema
: refVal.validate || this._compile(refVal);
}
var res = resolveSchema.call(this, root, ref);
var schema, v, baseId;
if (res) {
schema = res.schema;
root = res.root;
baseId = res.baseId;
}
if (schema instanceof SchemaObject) {
v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
} else if (schema !== undefined) {
v = inlineRef(schema, this._opts.inlineRefs)
? schema
: compile.call(this, schema, root, undefined, baseId);
}
return v;
}
/**
* Resolve schema, its root and baseId
* @this Ajv
* @param {Object} root root object with properties schema, refVal, refs
* @param {String} ref reference to resolve
* @return {Object} object with properties schema, root, baseId
*/
function resolveSchema(root, ref) {
/* jshint validthis: true */
var p = URI.parse(ref)
, refPath = _getFullPath(p)
, baseId = getFullPath(this._getId(root.schema));
if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
var id = normalizeId(refPath);
var refVal = this._refs[id];
if (typeof refVal == 'string') {
return resolveRecursive.call(this, root, refVal, p);
} else if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
root = refVal;
} else {
refVal = this._schemas[id];
if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
if (id == normalizeId(ref))
return { schema: refVal, root: root, baseId: baseId };
root = refVal;
} else {
return;
}
}
if (!root.schema) return;
baseId = getFullPath(this._getId(root.schema));
}
return getJsonPointer.call(this, p, baseId, root.schema, root);
}
/* @this Ajv */
function resolveRecursive(root, ref, parsedRef) {
/* jshint validthis: true */
var res = resolveSchema.call(this, root, ref);
if (res) {
var schema = res.schema;
var baseId = res.baseId;
root = res.root;
var id = this._getId(schema);
if (id) baseId = resolveUrl(baseId, id);
return getJsonPointer.call(this, parsedRef, baseId, schema, root);
}
}
var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
/* jshint validthis: true */
parsedRef.fragment = parsedRef.fragment || '';
if (parsedRef.fragment.slice(0,1) != '/') return;
var parts = parsedRef.fragment.split('/');
for (var i = 1; i < parts.length; i++) {
var part = parts[i];
if (part) {
part = util.unescapeFragment(part);
schema = schema[part];
if (schema === undefined) break;
var id;
if (!PREVENT_SCOPE_CHANGE[part]) {
id = this._getId(schema);
if (id) baseId = resolveUrl(baseId, id);
if (schema.$ref) {
var $ref = resolveUrl(baseId, schema.$ref);
var res = resolveSchema.call(this, root, $ref);
if (res) {
schema = res.schema;
root = res.root;
baseId = res.baseId;
}
}
}
}
}
if (schema !== undefined && schema !== root.schema)
return { schema: schema, root: root, baseId: baseId };
}
var SIMPLE_INLINED = util.toHash([
'type', 'format', 'pattern',
'maxLength', 'minLength',
'maxProperties', 'minProperties',
'maxItems', 'minItems',
'maximum', 'minimum',
'uniqueItems', 'multipleOf',
'required', 'enum'
]);
function inlineRef(schema, limit) {
if (limit === false) return false;
if (limit === undefined || limit === true) return checkNoRef(schema);
else if (limit) return countKeys(schema) <= limit;
}
function checkNoRef(schema) {
var item;
if (Array.isArray(schema)) {
for (var i=0; i<schema.length; i++) {
item = schema[i];
if (typeof item == 'object' && !checkNoRef(item)) return false;
}
} else {
for (var key in schema) {
if (key == '$ref') return false;
item = schema[key];
if (typeof item == 'object' && !checkNoRef(item)) return false;
}
}
return true;
}
function countKeys(schema) {
var count = 0, item;
if (Array.isArray(schema)) {
for (var i=0; i<schema.length; i++) {
item = schema[i];
if (typeof item == 'object') count += countKeys(item);
if (count == Infinity) return Infinity;
}
} else {
for (var key in schema) {
if (key == '$ref') return Infinity;
if (SIMPLE_INLINED[key]) {
count++;
} else {
item = schema[key];
if (typeof item == 'object') count += countKeys(item) + 1;
if (count == Infinity) return Infinity;
}
}
}
return count;
}
function getFullPath(id, normalize) {
if (normalize !== false) id = normalizeId(id);
var p = URI.parse(id);
return _getFullPath(p);
}
function _getFullPath(p) {
return URI.serialize(p).split('#')[0] + '#';
}
var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}
function resolveUrl(baseId, id) {
id = normalizeId(id);
return URI.resolve(baseId, id);
}
/* @this Ajv */
function resolveIds(schema) {
var schemaId = normalizeId(this._getId(schema));
var baseIds = {'': schemaId};
var fullPaths = {'': getFullPath(schemaId, false)};
var localRefs = {};
var self = this;
traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if (jsonPtr === '') return;
var id = self._getId(sch);
var baseId = baseIds[parentJsonPtr];
var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
if (keyIndex !== undefined)
fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
if (typeof id == 'string') {
id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
var refVal = self._refs[id];
if (typeof refVal == 'string') refVal = self._refs[refVal];
if (refVal && refVal.schema) {
if (!equal(sch, refVal.schema))
throw new Error('id "' + id + '" resolves to more than one schema');
} else if (id != normalizeId(fullPath)) {
if (id[0] == '#') {
if (localRefs[id] && !equal(sch, localRefs[id]))
throw new Error('id "' + id + '" resolves to more than one schema');
localRefs[id] = sch;
} else {
self._refs[id] = fullPath;
}
}
}
baseIds[jsonPtr] = baseId;
fullPaths[jsonPtr] = fullPath;
});
return localRefs;
}

66
node_modules/ajv/lib/compile/rules.js generated vendored Normal file
View File

@@ -0,0 +1,66 @@
'use strict';
var ruleModules = require('../dotjs')
, toHash = require('./util').toHash;
module.exports = function rules() {
var RULES = [
{ type: 'number',
rules: [ { 'maximum': ['exclusiveMaximum'] },
{ 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
{ type: 'string',
rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
{ type: 'array',
rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
{ type: 'object',
rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
{ 'properties': ['additionalProperties', 'patternProperties'] } ] },
{ rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
];
var ALL = [ 'type', '$comment' ];
var KEYWORDS = [
'$schema', '$id', 'id', '$data', '$async', 'title',
'description', 'default', 'definitions',
'examples', 'readOnly', 'writeOnly',
'contentMediaType', 'contentEncoding',
'additionalItems', 'then', 'else'
];
var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
RULES.all = toHash(ALL);
RULES.types = toHash(TYPES);
RULES.forEach(function (group) {
group.rules = group.rules.map(function (keyword) {
var implKeywords;
if (typeof keyword == 'object') {
var key = Object.keys(keyword)[0];
implKeywords = keyword[key];
keyword = key;
implKeywords.forEach(function (k) {
ALL.push(k);
RULES.all[k] = true;
});
}
ALL.push(keyword);
var rule = RULES.all[keyword] = {
keyword: keyword,
code: ruleModules[keyword],
implements: implKeywords
};
return rule;
});
RULES.all.$comment = {
keyword: '$comment',
code: ruleModules.$comment
};
if (group.type) RULES.types[group.type] = group;
});
RULES.keywords = toHash(ALL.concat(KEYWORDS));
RULES.custom = {};
return RULES;
};

9
node_modules/ajv/lib/compile/schema_obj.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
'use strict';
var util = require('./util');
module.exports = SchemaObject;
function SchemaObject(obj) {
util.copy(obj, this);
}

20
node_modules/ajv/lib/compile/ucs2length.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
'use strict';
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
module.exports = function ucs2length(str) {
var length = 0
, len = str.length
, pos = 0
, value;
while (pos < len) {
length++;
value = str.charCodeAt(pos++);
if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
// high surrogate, and there is a next character
value = str.charCodeAt(pos);
if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
}
}
return length;
};

239
node_modules/ajv/lib/compile/util.js generated vendored Normal file
View File

@@ -0,0 +1,239 @@
'use strict';
module.exports = {
copy: copy,
checkDataType: checkDataType,
checkDataTypes: checkDataTypes,
coerceToTypes: coerceToTypes,
toHash: toHash,
getProperty: getProperty,
escapeQuotes: escapeQuotes,
equal: require('fast-deep-equal'),
ucs2length: require('./ucs2length'),
varOccurences: varOccurences,
varReplace: varReplace,
schemaHasRules: schemaHasRules,
schemaHasRulesExcept: schemaHasRulesExcept,
schemaUnknownRules: schemaUnknownRules,
toQuotedString: toQuotedString,
getPathExpr: getPathExpr,
getPath: getPath,
getData: getData,
unescapeFragment: unescapeFragment,
unescapeJsonPointer: unescapeJsonPointer,
escapeFragment: escapeFragment,
escapeJsonPointer: escapeJsonPointer
};
function copy(o, to) {
to = to || {};
for (var key in o) to[key] = o[key];
return to;
}
function checkDataType(dataType, data, strictNumbers, negate) {
var EQUAL = negate ? ' !== ' : ' === '
, AND = negate ? ' || ' : ' && '
, OK = negate ? '!' : ''
, NOT = negate ? '' : '!';
switch (dataType) {
case 'null': return data + EQUAL + 'null';
case 'array': return OK + 'Array.isArray(' + data + ')';
case 'object': return '(' + OK + data + AND +
'typeof ' + data + EQUAL + '"object"' + AND +
NOT + 'Array.isArray(' + data + '))';
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
NOT + '(' + data + ' % 1)' +
AND + data + EQUAL + data +
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
}
}
function checkDataTypes(dataTypes, data, strictNumbers) {
switch (dataTypes.length) {
case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
default:
var code = '';
var types = toHash(dataTypes);
if (types.array && types.object) {
code = types.null ? '(': '(!' + data + ' || ';
code += 'typeof ' + data + ' !== "object")';
delete types.null;
delete types.array;
delete types.object;
}
if (types.number) delete types.integer;
for (var t in types)
code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);
return code;
}
}
var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
if (Array.isArray(dataTypes)) {
var types = [];
for (var i=0; i<dataTypes.length; i++) {
var t = dataTypes[i];
if (COERCE_TO_TYPES[t]) types[types.length] = t;
else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
}
if (types.length) return types;
} else if (COERCE_TO_TYPES[dataTypes]) {
return [dataTypes];
} else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
return ['array'];
}
}
function toHash(arr) {
var hash = {};
for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
return hash;
}
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
return typeof key == 'number'
? '[' + key + ']'
: IDENTIFIER.test(key)
? '.' + key
: "['" + escapeQuotes(key) + "']";
}
function escapeQuotes(str) {
return str.replace(SINGLE_QUOTE, '\\$&')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\f/g, '\\f')
.replace(/\t/g, '\\t');
}
function varOccurences(str, dataVar) {
dataVar += '[^0-9]';
var matches = str.match(new RegExp(dataVar, 'g'));
return matches ? matches.length : 0;
}
function varReplace(str, dataVar, expr) {
dataVar += '([^0-9])';
expr = expr.replace(/\$/g, '$$$$');
return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}
function schemaHasRules(schema, rules) {
if (typeof schema == 'boolean') return !schema;
for (var key in schema) if (rules[key]) return true;
}
function schemaHasRulesExcept(schema, rules, exceptKeyword) {
if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}
function schemaUnknownRules(schema, rules) {
if (typeof schema == 'boolean') return;
for (var key in schema) if (!rules[key]) return key;
}
function toQuotedString(str) {
return '\'' + escapeQuotes(str) + '\'';
}
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
var path = jsonPointers // false by default
? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
: (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
return joinPaths(currentPath, path);
}
function getPath(currentPath, prop, jsonPointers) {
var path = jsonPointers // false by default
? toQuotedString('/' + escapeJsonPointer(prop))
: toQuotedString(getProperty(prop));
return joinPaths(currentPath, path);
}
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
var up, jsonPointer, data, matches;
if ($data === '') return 'rootData';
if ($data[0] == '/') {
if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
jsonPointer = $data;
data = 'rootData';
} else {
matches = $data.match(RELATIVE_JSON_POINTER);
if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
up = +matches[1];
jsonPointer = matches[2];
if (jsonPointer == '#') {
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
return paths[lvl - up];
}
if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
data = 'data' + ((lvl - up) || '');
if (!jsonPointer) return data;
}
var expr = data;
var segments = jsonPointer.split('/');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
if (segment) {
data += getProperty(unescapeJsonPointer(segment));
expr += ' && ' + data;
}
}
return expr;
}
function joinPaths (a, b) {
if (a == '""') return b;
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
}
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
function escapeJsonPointer(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function unescapeJsonPointer(str) {
return str.replace(/~1/g, '/').replace(/~0/g, '~');
}

49
node_modules/ajv/lib/data.js generated vendored Normal file
View File

@@ -0,0 +1,49 @@
'use strict';
var KEYWORDS = [
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum',
'maxLength',
'minLength',
'pattern',
'additionalItems',
'maxItems',
'minItems',
'uniqueItems',
'maxProperties',
'minProperties',
'required',
'additionalProperties',
'enum',
'format',
'const'
];
module.exports = function (metaSchema, keywordsJsonPointers) {
for (var i=0; i<keywordsJsonPointers.length; i++) {
metaSchema = JSON.parse(JSON.stringify(metaSchema));
var segments = keywordsJsonPointers[i].split('/');
var keywords = metaSchema;
var j;
for (j=1; j<segments.length; j++)
keywords = keywords[segments[j]];
for (j=0; j<KEYWORDS.length; j++) {
var key = KEYWORDS[j];
var schema = keywords[key];
if (schema) {
keywords[key] = {
anyOf: [
schema,
{ $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
]
};
}
}
}
return metaSchema;
};

37
node_modules/ajv/lib/definition_schema.js generated vendored Normal file
View File

@@ -0,0 +1,37 @@
'use strict';
var metaSchema = require('./refs/json-schema-draft-07.json');
module.exports = {
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
definitions: {
simpleTypes: metaSchema.definitions.simpleTypes
},
type: 'object',
dependencies: {
schema: ['validate'],
$data: ['validate'],
statements: ['inline'],
valid: {not: {required: ['macro']}}
},
properties: {
type: metaSchema.properties.type,
schema: {type: 'boolean'},
statements: {type: 'boolean'},
dependencies: {
type: 'array',
items: {type: 'string'}
},
metaSchema: {type: 'object'},
modifying: {type: 'boolean'},
valid: {type: 'boolean'},
$data: {type: 'boolean'},
async: {type: 'boolean'},
errors: {
anyOf: [
{type: 'boolean'},
{const: 'full'}
]
}
}
};

113
node_modules/ajv/lib/dot/_limit.jst generated vendored Normal file
View File

@@ -0,0 +1,113 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{## def.setExclusiveLimit:
$exclusive = true;
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
#}}
{{
var $isMax = $keyword == 'maximum'
, $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum'
, $schemaExcl = it.schema[$exclusiveKeyword]
, $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data
, $op = $isMax ? '<' : '>'
, $notOp = $isMax ? '>' : '<'
, $errorKeyword = undefined;
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
throw new Error($keyword + ' must be number');
}
if (!($isDataExcl || $schemaExcl === undefined
|| typeof $schemaExcl == 'number'
|| typeof $schemaExcl == 'boolean')) {
throw new Error($exclusiveKeyword + ' must be number or boolean');
}
}}
{{? $isDataExcl }}
{{
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr)
, $exclusive = 'exclusive' + $lvl
, $exclType = 'exclType' + $lvl
, $exclIsNumber = 'exclIsNumber' + $lvl
, $opExpr = 'op' + $lvl
, $opStr = '\' + ' + $opExpr + ' + \'';
}}
var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}};
{{ $schemaValueExcl = 'schemaExcl' + $lvl; }}
var {{=$exclusive}};
var {{=$exclType}} = typeof {{=$schemaValueExcl}};
if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') {
{{ var $errorKeyword = $exclusiveKeyword; }}
{{# def.error:'_exclusiveLimit' }}
} else if ({{# def.$dataNotType:'number' }}
{{=$exclType}} == 'number'
? (
({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}})
? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}}
: {{=$data}} {{=$notOp}} {{=$schemaValue}}
)
: (
({{=$exclusive}} = {{=$schemaValueExcl}} === true)
? {{=$data}} {{=$notOp}}= {{=$schemaValue}}
: {{=$data}} {{=$notOp}} {{=$schemaValue}}
)
|| {{=$data}} !== {{=$data}}) {
var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}=';
{{
if ($schema === undefined) {
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaValueExcl;
$isData = $isDataExcl;
}
}}
{{??}}
{{
var $exclIsNumber = typeof $schemaExcl == 'number'
, $opStr = $op; /*used in error*/
}}
{{? $exclIsNumber && $isData }}
{{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }}
if ({{# def.$dataNotType:'number' }}
( {{=$schemaValue}} === undefined
|| {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}}
? {{=$data}} {{=$notOp}}= {{=$schemaExcl}}
: {{=$data}} {{=$notOp}} {{=$schemaValue}} )
|| {{=$data}} !== {{=$data}}) {
{{??}}
{{
if ($exclIsNumber && $schema === undefined) {
{{# def.setExclusiveLimit }}
$schemaValue = $schemaExcl;
$notOp += '=';
} else {
if ($exclIsNumber)
$schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
{{# def.setExclusiveLimit }}
$notOp += '=';
} else {
$exclusive = false;
$opStr += '=';
}
}
var $opExpr = '\'' + $opStr + '\''; /*used in error*/
}}
if ({{# def.$dataNotType:'number' }}
{{=$data}} {{=$notOp}} {{=$schemaValue}}
|| {{=$data}} !== {{=$data}}) {
{{?}}
{{?}}
{{ $errorKeyword = $errorKeyword || $keyword; }}
{{# def.error:'_limit' }}
} {{? $breakOnError }} else { {{?}}

12
node_modules/ajv/lib/dot/_limitItems.jst generated vendored Normal file
View File

@@ -0,0 +1,12 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{# def.numberKeyword }}
{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }}
if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) {
{{ var $errorKeyword = $keyword; }}
{{# def.error:'_limitItems' }}
} {{? $breakOnError }} else { {{?}}

12
node_modules/ajv/lib/dot/_limitLength.jst generated vendored Normal file
View File

@@ -0,0 +1,12 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{# def.numberKeyword }}
{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }}
if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) {
{{ var $errorKeyword = $keyword; }}
{{# def.error:'_limitLength' }}
} {{? $breakOnError }} else { {{?}}

12
node_modules/ajv/lib/dot/_limitProperties.jst generated vendored Normal file
View File

@@ -0,0 +1,12 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{# def.numberKeyword }}
{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }}
if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) {
{{ var $errorKeyword = $keyword; }}
{{# def.error:'_limitProperties' }}
} {{? $breakOnError }} else { {{?}}

32
node_modules/ajv/lib/dot/allOf.jst generated vendored Normal file
View File

@@ -0,0 +1,32 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{
var $currentBaseId = $it.baseId
, $allSchemasEmpty = true;
}}
{{~ $schema:$sch:$i }}
{{? {{# def.nonEmptySchema:$sch }} }}
{{
$allSchemasEmpty = false;
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
}}
{{# def.insertSubschemaCode }}
{{# def.ifResultValid }}
{{?}}
{{~}}
{{? $breakOnError }}
{{? $allSchemasEmpty }}
if (true) {
{{??}}
{{= $closingBraces.slice(0,-1) }}
{{?}}
{{?}}

46
node_modules/ajv/lib/dot/anyOf.jst generated vendored Normal file
View File

@@ -0,0 +1,46 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{
var $noEmptySchema = $schema.every(function($sch) {
return {{# def.nonEmptySchema:$sch }};
});
}}
{{? $noEmptySchema }}
{{ var $currentBaseId = $it.baseId; }}
var {{=$errs}} = errors;
var {{=$valid}} = false;
{{# def.setCompositeRule }}
{{~ $schema:$sch:$i }}
{{
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
}}
{{# def.insertSubschemaCode }}
{{=$valid}} = {{=$valid}} || {{=$nextValid}};
if (!{{=$valid}}) {
{{ $closingBraces += '}'; }}
{{~}}
{{# def.resetCompositeRule }}
{{= $closingBraces }}
if (!{{=$valid}}) {
{{# def.extraError:'anyOf' }}
} else {
{{# def.resetErrors }}
{{? it.opts.allErrors }} } {{?}}
{{??}}
{{? $breakOnError }}
if (true) {
{{?}}
{{?}}

51
node_modules/ajv/lib/dot/coerce.def generated vendored Normal file
View File

@@ -0,0 +1,51 @@
{{## def.coerceType:
{{
var $dataType = 'dataType' + $lvl
, $coerced = 'coerced' + $lvl;
}}
var {{=$dataType}} = typeof {{=$data}};
var {{=$coerced}} = undefined;
{{? it.opts.coerceTypes == 'array' }}
if ({{=$dataType}} == 'object' && Array.isArray({{=$data}}) && {{=$data}}.length == 1) {
{{=$data}} = {{=$data}}[0];
{{=$dataType}} = typeof {{=$data}};
if ({{=it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)}}) {{=$coerced}} = {{=$data}};
}
{{?}}
if ({{=$coerced}} !== undefined) ;
{{~ $coerceToTypes:$type:$i }}
{{? $type == 'string' }}
else if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean')
{{=$coerced}} = '' + {{=$data}};
else if ({{=$data}} === null) {{=$coerced}} = '';
{{?? $type == 'number' || $type == 'integer' }}
else if ({{=$dataType}} == 'boolean' || {{=$data}} === null
|| ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}}
{{? $type == 'integer' }} && !({{=$data}} % 1){{?}}))
{{=$coerced}} = +{{=$data}};
{{?? $type == 'boolean' }}
else if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null)
{{=$coerced}} = false;
else if ({{=$data}} === 'true' || {{=$data}} === 1)
{{=$coerced}} = true;
{{?? $type == 'null' }}
else if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false)
{{=$coerced}} = null;
{{?? it.opts.coerceTypes == 'array' && $type == 'array' }}
else if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null)
{{=$coerced}} = [{{=$data}}];
{{?}}
{{~}}
else {
{{# def.error:'type' }}
}
if ({{=$coerced}} !== undefined) {
{{# def.setParentData }}
{{=$data}} = {{=$coerced}};
{{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}}
{{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}};
}
#}}

9
node_modules/ajv/lib/dot/comment.jst generated vendored Normal file
View File

@@ -0,0 +1,9 @@
{{# def.definitions }}
{{# def.setupKeyword }}
{{ var $comment = it.util.toQuotedString($schema); }}
{{? it.opts.$comment === true }}
console.log({{=$comment}});
{{?? typeof it.opts.$comment == 'function' }}
self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema);
{{?}}

11
node_modules/ajv/lib/dot/const.jst generated vendored Normal file
View File

@@ -0,0 +1,11 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{? !$isData }}
var schema{{=$lvl}} = validate.schema{{=$schemaPath}};
{{?}}
var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}});
{{# def.checkError:'const' }}
{{? $breakOnError }} else { {{?}}

55
node_modules/ajv/lib/dot/contains.jst generated vendored Normal file
View File

@@ -0,0 +1,55 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{
var $idx = 'i' + $lvl
, $dataNxt = $it.dataLevel = it.dataLevel + 1
, $nextData = 'data' + $dataNxt
, $currentBaseId = it.baseId
, $nonEmptySchema = {{# def.nonEmptySchema:$schema }};
}}
var {{=$errs}} = errors;
var {{=$valid}};
{{? $nonEmptySchema }}
{{# def.setCompositeRule }}
{{
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
}}
var {{=$nextValid}} = false;
for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
{{
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
}}
{{# def.generateSubschemaCode }}
{{# def.optimizeValidate }}
if ({{=$nextValid}}) break;
}
{{# def.resetCompositeRule }}
{{= $closingBraces }}
if (!{{=$nextValid}}) {
{{??}}
if ({{=$data}}.length == 0) {
{{?}}
{{# def.error:'contains' }}
} else {
{{? $nonEmptySchema }}
{{# def.resetErrors }}
{{?}}
{{? it.opts.allErrors }} } {{?}}

191
node_modules/ajv/lib/dot/custom.jst generated vendored Normal file
View File

@@ -0,0 +1,191 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{
var $rule = this
, $definition = 'definition' + $lvl
, $rDef = $rule.definition
, $closingBraces = '';
var $validate = $rDef.validate;
var $compile, $inline, $macro, $ruleValidate, $validateCode;
}}
{{? $isData && $rDef.$data }}
{{
$validateCode = 'keywordValidate' + $lvl;
var $validateSchema = $rDef.validateSchema;
}}
var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition;
var {{=$validateCode}} = {{=$definition}}.validate;
{{??}}
{{
$ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
if (!$ruleValidate) return;
$schemaValue = 'validate.schema' + $schemaPath;
$validateCode = $ruleValidate.code;
$compile = $rDef.compile;
$inline = $rDef.inline;
$macro = $rDef.macro;
}}
{{?}}
{{
var $ruleErrs = $validateCode + '.errors'
, $i = 'i' + $lvl
, $ruleErr = 'ruleErr' + $lvl
, $asyncKeyword = $rDef.async;
if ($asyncKeyword && !it.async)
throw new Error('async keyword in sync schema');
}}
{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}}
var {{=$errs}} = errors;
var {{=$valid}};
{{## def.callRuleValidate:
{{=$validateCode}}.call(
{{? it.opts.passContext }}this{{??}}self{{?}}
{{? $compile || $rDef.schema === false }}
, {{=$data}}
{{??}}
, {{=$schemaValue}}
, {{=$data}}
, validate.schema{{=it.schemaPath}}
{{?}}
, {{# def.dataPath }}
{{# def.passParentData }}
, rootData
)
#}}
{{## def.extendErrors:_inline:
for (var {{=$i}}={{=$errs}}; {{=$i}}<errors; {{=$i}}++) {
var {{=$ruleErr}} = vErrors[{{=$i}}];
if ({{=$ruleErr}}.dataPath === undefined)
{{=$ruleErr}}.dataPath = (dataPath || '') + {{= it.errorPath }};
{{# _inline ? 'if (\{\{=$ruleErr\}\}.schemaPath === undefined) {' : '' }}
{{=$ruleErr}}.schemaPath = "{{=$errSchemaPath}}";
{{# _inline ? '}' : '' }}
{{? it.opts.verbose }}
{{=$ruleErr}}.schema = {{=$schemaValue}};
{{=$ruleErr}}.data = {{=$data}};
{{?}}
}
#}}
{{? $isData && $rDef.$data }}
{{ $closingBraces += '}'; }}
if ({{=$schemaValue}} === undefined) {
{{=$valid}} = true;
} else {
{{? $validateSchema }}
{{ $closingBraces += '}'; }}
{{=$valid}} = {{=$definition}}.validateSchema({{=$schemaValue}});
if ({{=$valid}}) {
{{?}}
{{?}}
{{? $inline }}
{{? $rDef.statements }}
{{= $ruleValidate.validate }}
{{??}}
{{=$valid}} = {{= $ruleValidate.validate }};
{{?}}
{{?? $macro }}
{{# def.setupNextLevel }}
{{
$it.schema = $ruleValidate.validate;
$it.schemaPath = '';
}}
{{# def.setCompositeRule }}
{{ var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); }}
{{# def.resetCompositeRule }}
{{= $code }}
{{??}}
{{# def.beginDefOut}}
{{# def.callRuleValidate }}
{{# def.storeDefOut:def_callRuleValidate }}
{{? $rDef.errors === false }}
{{=$valid}} = {{? $asyncKeyword }}await {{?}}{{= def_callRuleValidate }};
{{??}}
{{? $asyncKeyword }}
{{ $ruleErrs = 'customErrors' + $lvl; }}
var {{=$ruleErrs}} = null;
try {
{{=$valid}} = await {{= def_callRuleValidate }};
} catch (e) {
{{=$valid}} = false;
if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors;
else throw e;
}
{{??}}
{{=$ruleErrs}} = null;
{{=$valid}} = {{= def_callRuleValidate }};
{{?}}
{{?}}
{{?}}
{{? $rDef.modifying }}
if ({{=$parentData}}) {{=$data}} = {{=$parentData}}[{{=$parentDataProperty}}];
{{?}}
{{= $closingBraces }}
{{## def.notValidationResult:
{{? $rDef.valid === undefined }}
!{{? $macro }}{{=$nextValid}}{{??}}{{=$valid}}{{?}}
{{??}}
{{= !$rDef.valid }}
{{?}}
#}}
{{? $rDef.valid }}
{{? $breakOnError }} if (true) { {{?}}
{{??}}
if ({{# def.notValidationResult }}) {
{{ $errorKeyword = $rule.keyword; }}
{{# def.beginDefOut}}
{{# def.error:'custom' }}
{{# def.storeDefOut:def_customError }}
{{? $inline }}
{{? $rDef.errors }}
{{? $rDef.errors != 'full' }}
{{# def.extendErrors:true }}
{{?}}
{{??}}
{{? $rDef.errors === false}}
{{= def_customError }}
{{??}}
if ({{=$errs}} == errors) {
{{= def_customError }}
} else {
{{# def.extendErrors:true }}
}
{{?}}
{{?}}
{{?? $macro }}
{{# def.extraError:'custom' }}
{{??}}
{{? $rDef.errors === false}}
{{= def_customError }}
{{??}}
if (Array.isArray({{=$ruleErrs}})) {
if (vErrors === null) vErrors = {{=$ruleErrs}};
else vErrors = vErrors.concat({{=$ruleErrs}});
errors = vErrors.length;
{{# def.extendErrors:false }}
} else {
{{= def_customError }}
}
{{?}}
{{?}}
} {{? $breakOnError }} else { {{?}}
{{?}}

47
node_modules/ajv/lib/dot/defaults.def generated vendored Normal file
View File

@@ -0,0 +1,47 @@
{{## def.assignDefault:
{{? it.compositeRule }}
{{
if (it.opts.strictDefaults) {
var $defaultMsg = 'default is ignored for: ' + $passData;
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
else throw new Error($defaultMsg);
}
}}
{{??}}
if ({{=$passData}} === undefined
{{? it.opts.useDefaults == 'empty' }}
|| {{=$passData}} === null
|| {{=$passData}} === ''
{{?}}
)
{{=$passData}} = {{? it.opts.useDefaults == 'shared' }}
{{= it.useDefault($sch.default) }}
{{??}}
{{= JSON.stringify($sch.default) }}
{{?}};
{{?}}
#}}
{{## def.defaultProperties:
{{
var $schema = it.schema.properties
, $schemaKeys = Object.keys($schema); }}
{{~ $schemaKeys:$propertyKey }}
{{ var $sch = $schema[$propertyKey]; }}
{{? $sch.default !== undefined }}
{{ var $passData = $data + it.util.getProperty($propertyKey); }}
{{# def.assignDefault }}
{{?}}
{{~}}
#}}
{{## def.defaultItems:
{{~ it.schema.items:$sch:$i }}
{{? $sch.default !== undefined }}
{{ var $passData = $data + '[' + $i + ']'; }}
{{# def.assignDefault }}
{{?}}
{{~}}
#}}

203
node_modules/ajv/lib/dot/definitions.def generated vendored Normal file
View File

@@ -0,0 +1,203 @@
{{## def.setupKeyword:
{{
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
}}
#}}
{{## def.setCompositeRule:
{{
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
}}
#}}
{{## def.resetCompositeRule:
{{ it.compositeRule = $it.compositeRule = $wasComposite; }}
#}}
{{## def.setupNextLevel:
{{
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
}}
#}}
{{## def.ifValid:
{{? $breakOnError }}
if ({{=$valid}}) {
{{ $closingBraces += '}'; }}
{{?}}
#}}
{{## def.ifResultValid:
{{? $breakOnError }}
if ({{=$nextValid}}) {
{{ $closingBraces += '}'; }}
{{?}}
#}}
{{## def.elseIfValid:
{{? $breakOnError }}
{{ $closingBraces += '}'; }}
else {
{{?}}
#}}
{{## def.nonEmptySchema:_schema:
(it.opts.strictKeywords
? (typeof _schema == 'object' && Object.keys(_schema).length > 0)
|| _schema === false
: it.util.schemaHasRules(_schema, it.RULES.all))
#}}
{{## def.strLength:
{{? it.opts.unicode === false }}
{{=$data}}.length
{{??}}
ucs2length({{=$data}})
{{?}}
#}}
{{## def.willOptimize:
it.util.varOccurences($code, $nextData) < 2
#}}
{{## def.generateSubschemaCode:
{{
var $code = it.validate($it);
$it.baseId = $currentBaseId;
}}
#}}
{{## def.insertSubschemaCode:
{{= it.validate($it) }}
{{ $it.baseId = $currentBaseId; }}
#}}
{{## def._optimizeValidate:
it.util.varReplace($code, $nextData, $passData)
#}}
{{## def.optimizeValidate:
{{? {{# def.willOptimize}} }}
{{= {{# def._optimizeValidate }} }}
{{??}}
var {{=$nextData}} = {{=$passData}};
{{= $code }}
{{?}}
#}}
{{## def.$data:
{{
var $isData = it.opts.$data && $schema && $schema.$data
, $schemaValue;
}}
{{? $isData }}
var schema{{=$lvl}} = {{= it.util.getData($schema.$data, $dataLvl, it.dataPathArr) }};
{{ $schemaValue = 'schema' + $lvl; }}
{{??}}
{{ $schemaValue = $schema; }}
{{?}}
#}}
{{## def.$dataNotType:_type:
{{?$isData}} ({{=$schemaValue}} !== undefined && typeof {{=$schemaValue}} != _type) || {{?}}
#}}
{{## def.check$dataIsArray:
if (schema{{=$lvl}} === undefined) {{=$valid}} = true;
else if (!Array.isArray(schema{{=$lvl}})) {{=$valid}} = false;
else {
#}}
{{## def.numberKeyword:
{{? !($isData || typeof $schema == 'number') }}
{{ throw new Error($keyword + ' must be number'); }}
{{?}}
#}}
{{## def.beginDefOut:
{{
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
}}
#}}
{{## def.storeDefOut:_variable:
{{
var _variable = out;
out = $$outStack.pop();
}}
#}}
{{## def.dataPath:(dataPath || ''){{? it.errorPath != '""'}} + {{= it.errorPath }}{{?}}#}}
{{## def.setParentData:
{{
var $parentData = $dataLvl ? 'data' + (($dataLvl-1)||'') : 'parentData'
, $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
}}
#}}
{{## def.passParentData:
{{# def.setParentData }}
, {{= $parentData }}
, {{= $parentDataProperty }}
#}}
{{## def.iterateProperties:
{{? $ownProperties }}
{{=$dataProperties}} = {{=$dataProperties}} || Object.keys({{=$data}});
for (var {{=$idx}}=0; {{=$idx}}<{{=$dataProperties}}.length; {{=$idx}}++) {
var {{=$key}} = {{=$dataProperties}}[{{=$idx}}];
{{??}}
for (var {{=$key}} in {{=$data}}) {
{{?}}
#}}
{{## def.noPropertyInData:
{{=$useData}} === undefined
{{? $ownProperties }}
|| !{{# def.isOwnProperty }}
{{?}}
#}}
{{## def.isOwnProperty:
Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($propertyKey)}}')
#}}

79
node_modules/ajv/lib/dot/dependencies.jst generated vendored Normal file
View File

@@ -0,0 +1,79 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.missing }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{## def.propertyInData:
{{=$data}}{{= it.util.getProperty($property) }} !== undefined
{{? $ownProperties }}
&& Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($property)}}')
{{?}}
#}}
{{
var $schemaDeps = {}
, $propertyDeps = {}
, $ownProperties = it.opts.ownProperties;
for ($property in $schema) {
if ($property == '__proto__') continue;
var $sch = $schema[$property];
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
$deps[$property] = $sch;
}
}}
var {{=$errs}} = errors;
{{ var $currentErrorPath = it.errorPath; }}
var missing{{=$lvl}};
{{ for (var $property in $propertyDeps) { }}
{{ $deps = $propertyDeps[$property]; }}
{{? $deps.length }}
if ({{# def.propertyInData }}
{{? $breakOnError }}
&& ({{# def.checkMissingProperty:$deps }})) {
{{# def.errorMissingProperty:'dependencies' }}
{{??}}
) {
{{~ $deps:$propertyKey }}
{{# def.allErrorsMissingProperty:'dependencies' }}
{{~}}
{{?}}
} {{# def.elseIfValid }}
{{?}}
{{ } }}
{{
it.errorPath = $currentErrorPath;
var $currentBaseId = $it.baseId;
}}
{{ for (var $property in $schemaDeps) { }}
{{ var $sch = $schemaDeps[$property]; }}
{{? {{# def.nonEmptySchema:$sch }} }}
{{=$nextValid}} = true;
if ({{# def.propertyInData }}) {
{{
$it.schema = $sch;
$it.schemaPath = $schemaPath + it.util.getProperty($property);
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
}}
{{# def.insertSubschemaCode }}
}
{{# def.ifResultValid }}
{{?}}
{{ } }}
{{? $breakOnError }}
{{= $closingBraces }}
if ({{=$errs}} == errors) {
{{?}}

30
node_modules/ajv/lib/dot/enum.jst generated vendored Normal file
View File

@@ -0,0 +1,30 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{
var $i = 'i' + $lvl
, $vSchema = 'schema' + $lvl;
}}
{{? !$isData }}
var {{=$vSchema}} = validate.schema{{=$schemaPath}};
{{?}}
var {{=$valid}};
{{?$isData}}{{# def.check$dataIsArray }}{{?}}
{{=$valid}} = false;
for (var {{=$i}}=0; {{=$i}}<{{=$vSchema}}.length; {{=$i}}++)
if (equal({{=$data}}, {{=$vSchema}}[{{=$i}}])) {
{{=$valid}} = true;
break;
}
{{? $isData }} } {{?}}
{{# def.checkError:'enum' }}
{{? $breakOnError }} else { {{?}}

194
node_modules/ajv/lib/dot/errors.def generated vendored Normal file
View File

@@ -0,0 +1,194 @@
{{# def.definitions }}
{{## def._error:_rule:
{{ 'istanbul ignore else'; }}
{{? it.createErrors !== false }}
{
keyword: '{{= $errorKeyword || _rule }}'
, dataPath: (dataPath || '') + {{= it.errorPath }}
, schemaPath: {{=it.util.toQuotedString($errSchemaPath)}}
, params: {{# def._errorParams[_rule] }}
{{? it.opts.messages !== false }}
, message: {{# def._errorMessages[_rule] }}
{{?}}
{{? it.opts.verbose }}
, schema: {{# def._errorSchemas[_rule] }}
, parentSchema: validate.schema{{=it.schemaPath}}
, data: {{=$data}}
{{?}}
}
{{??}}
{}
{{?}}
#}}
{{## def._addError:_rule:
if (vErrors === null) vErrors = [err];
else vErrors.push(err);
errors++;
#}}
{{## def.addError:_rule:
var err = {{# def._error:_rule }};
{{# def._addError:_rule }}
#}}
{{## def.error:_rule:
{{# def.beginDefOut}}
{{# def._error:_rule }}
{{# def.storeDefOut:__err }}
{{? !it.compositeRule && $breakOnError }}
{{ 'istanbul ignore if'; }}
{{? it.async }}
throw new ValidationError([{{=__err}}]);
{{??}}
validate.errors = [{{=__err}}];
return false;
{{?}}
{{??}}
var err = {{=__err}};
{{# def._addError:_rule }}
{{?}}
#}}
{{## def.extraError:_rule:
{{# def.addError:_rule}}
{{? !it.compositeRule && $breakOnError }}
{{ 'istanbul ignore if'; }}
{{? it.async }}
throw new ValidationError(vErrors);
{{??}}
validate.errors = vErrors;
return false;
{{?}}
{{?}}
#}}
{{## def.checkError:_rule:
if (!{{=$valid}}) {
{{# def.error:_rule }}
}
#}}
{{## def.resetErrors:
errors = {{=$errs}};
if (vErrors !== null) {
if ({{=$errs}}) vErrors.length = {{=$errs}};
else vErrors = null;
}
#}}
{{## def.concatSchema:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=$schema}}{{?}}#}}
{{## def.appendSchema:{{?$isData}}' + {{=$schemaValue}}{{??}}{{=$schemaValue}}'{{?}}#}}
{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}}
{{## def._errorMessages = {
'false schema': "'boolean schema is false'",
$ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'",
additionalItems: "'should NOT have more than {{=$schema.length}} items'",
additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'",
anyOf: "'should match some schema in anyOf'",
const: "'should be equal to constant'",
contains: "'should contain a valid item'",
dependencies: "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'",
'enum': "'should be equal to one of the allowed values'",
format: "'should match format \"{{#def.concatSchemaEQ}}\"'",
'if': "'should match \"' + {{=$ifClause}} + '\" schema'",
_limit: "'should be {{=$opStr}} {{#def.appendSchema}}",
_exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'",
_limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'",
_limitLength: "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'",
_limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'",
multipleOf: "'should be multiple of {{#def.appendSchema}}",
not: "'should NOT be valid'",
oneOf: "'should match exactly one schema in oneOf'",
pattern: "'should match pattern \"{{#def.concatSchemaEQ}}\"'",
propertyNames: "'property name \\'{{=$invalidName}}\\' is invalid'",
required: "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'",
type: "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'",
uniqueItems: "'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)'",
custom: "'should pass \"{{=$rule.keyword}}\" keyword validation'",
patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''",
switch: "'should pass \"switch\" keyword validation'",
_formatLimit: "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'",
_formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'"
} #}}
{{## def.schemaRefOrVal: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=$schema}}{{?}} #}}
{{## def.schemaRefOrQS: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}
{{## def._errorSchemas = {
'false schema': "false",
$ref: "{{=it.util.toQuotedString($schema)}}",
additionalItems: "false",
additionalProperties: "false",
anyOf: "validate.schema{{=$schemaPath}}",
const: "validate.schema{{=$schemaPath}}",
contains: "validate.schema{{=$schemaPath}}",
dependencies: "validate.schema{{=$schemaPath}}",
'enum': "validate.schema{{=$schemaPath}}",
format: "{{#def.schemaRefOrQS}}",
'if': "validate.schema{{=$schemaPath}}",
_limit: "{{#def.schemaRefOrVal}}",
_exclusiveLimit: "validate.schema{{=$schemaPath}}",
_limitItems: "{{#def.schemaRefOrVal}}",
_limitLength: "{{#def.schemaRefOrVal}}",
_limitProperties:"{{#def.schemaRefOrVal}}",
multipleOf: "{{#def.schemaRefOrVal}}",
not: "validate.schema{{=$schemaPath}}",
oneOf: "validate.schema{{=$schemaPath}}",
pattern: "{{#def.schemaRefOrQS}}",
propertyNames: "validate.schema{{=$schemaPath}}",
required: "validate.schema{{=$schemaPath}}",
type: "validate.schema{{=$schemaPath}}",
uniqueItems: "{{#def.schemaRefOrVal}}",
custom: "validate.schema{{=$schemaPath}}",
patternRequired: "validate.schema{{=$schemaPath}}",
switch: "validate.schema{{=$schemaPath}}",
_formatLimit: "{{#def.schemaRefOrQS}}",
_formatExclusiveLimit: "validate.schema{{=$schemaPath}}"
} #}}
{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}
{{## def._errorParams = {
'false schema': "{}",
$ref: "{ ref: '{{=it.util.escapeQuotes($schema)}}' }",
additionalItems: "{ limit: {{=$schema.length}} }",
additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }",
anyOf: "{}",
const: "{ allowedValue: schema{{=$lvl}} }",
contains: "{}",
dependencies: "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }",
'enum': "{ allowedValues: schema{{=$lvl}} }",
format: "{ format: {{#def.schemaValueQS}} }",
'if': "{ failingKeyword: {{=$ifClause}} }",
_limit: "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }",
_exclusiveLimit: "{}",
_limitItems: "{ limit: {{=$schemaValue}} }",
_limitLength: "{ limit: {{=$schemaValue}} }",
_limitProperties:"{ limit: {{=$schemaValue}} }",
multipleOf: "{ multipleOf: {{=$schemaValue}} }",
not: "{}",
oneOf: "{ passingSchemas: {{=$passingSchemas}} }",
pattern: "{ pattern: {{#def.schemaValueQS}} }",
propertyNames: "{ propertyName: '{{=$invalidName}}' }",
required: "{ missingProperty: '{{=$missingProperty}}' }",
type: "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }",
uniqueItems: "{ i: i, j: j }",
custom: "{ keyword: '{{=$rule.keyword}}' }",
patternRequired: "{ missingPattern: '{{=$missingPattern}}' }",
switch: "{ caseIndex: {{=$caseIndex}} }",
_formatLimit: "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }",
_formatExclusiveLimit: "{}"
} #}}

106
node_modules/ajv/lib/dot/format.jst generated vendored Normal file
View File

@@ -0,0 +1,106 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{## def.skipFormat:
{{? $breakOnError }} if (true) { {{?}}
{{ return out; }}
#}}
{{? it.opts.format === false }}{{# def.skipFormat }}{{?}}
{{# def.$data }}
{{## def.$dataCheckFormat:
{{# def.$dataNotType:'string' }}
({{? $unknownFormats != 'ignore' }}
({{=$schemaValue}} && !{{=$format}}
{{? $allowUnknown }}
&& self._opts.unknownFormats.indexOf({{=$schemaValue}}) == -1
{{?}}) ||
{{?}}
({{=$format}} && {{=$formatType}} == '{{=$ruleType}}'
&& !(typeof {{=$format}} == 'function'
? {{? it.async}}
(async{{=$lvl}} ? await {{=$format}}({{=$data}}) : {{=$format}}({{=$data}}))
{{??}}
{{=$format}}({{=$data}})
{{?}}
: {{=$format}}.test({{=$data}}))))
#}}
{{## def.checkFormat:
{{
var $formatRef = 'formats' + it.util.getProperty($schema);
if ($isObject) $formatRef += '.validate';
}}
{{? typeof $format == 'function' }}
{{=$formatRef}}({{=$data}})
{{??}}
{{=$formatRef}}.test({{=$data}})
{{?}}
#}}
{{
var $unknownFormats = it.opts.unknownFormats
, $allowUnknown = Array.isArray($unknownFormats);
}}
{{? $isData }}
{{
var $format = 'format' + $lvl
, $isObject = 'isObject' + $lvl
, $formatType = 'formatType' + $lvl;
}}
var {{=$format}} = formats[{{=$schemaValue}}];
var {{=$isObject}} = typeof {{=$format}} == 'object'
&& !({{=$format}} instanceof RegExp)
&& {{=$format}}.validate;
var {{=$formatType}} = {{=$isObject}} && {{=$format}}.type || 'string';
if ({{=$isObject}}) {
{{? it.async}}
var async{{=$lvl}} = {{=$format}}.async;
{{?}}
{{=$format}} = {{=$format}}.validate;
}
if ({{# def.$dataCheckFormat }}) {
{{??}}
{{ var $format = it.formats[$schema]; }}
{{? !$format }}
{{? $unknownFormats == 'ignore' }}
{{ it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); }}
{{# def.skipFormat }}
{{?? $allowUnknown && $unknownFormats.indexOf($schema) >= 0 }}
{{# def.skipFormat }}
{{??}}
{{ throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); }}
{{?}}
{{?}}
{{
var $isObject = typeof $format == 'object'
&& !($format instanceof RegExp)
&& $format.validate;
var $formatType = $isObject && $format.type || 'string';
if ($isObject) {
var $async = $format.async === true;
$format = $format.validate;
}
}}
{{? $formatType != $ruleType }}
{{# def.skipFormat }}
{{?}}
{{? $async }}
{{
if (!it.async) throw new Error('async format in sync schema');
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
}}
if (!(await {{=$formatRef}}({{=$data}}))) {
{{??}}
if (!{{# def.checkFormat }}) {
{{?}}
{{?}}
{{# def.error:'format' }}
} {{? $breakOnError }} else { {{?}}

73
node_modules/ajv/lib/dot/if.jst generated vendored Normal file
View File

@@ -0,0 +1,73 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{## def.validateIfClause:_clause:
{{
$it.schema = it.schema['_clause'];
$it.schemaPath = it.schemaPath + '._clause';
$it.errSchemaPath = it.errSchemaPath + '/_clause';
}}
{{# def.insertSubschemaCode }}
{{=$valid}} = {{=$nextValid}};
{{? $thenPresent && $elsePresent }}
{{ $ifClause = 'ifClause' + $lvl; }}
var {{=$ifClause}} = '_clause';
{{??}}
{{ $ifClause = '\'_clause\''; }}
{{?}}
#}}
{{
var $thenSch = it.schema['then']
, $elseSch = it.schema['else']
, $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }}
, $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }}
, $currentBaseId = $it.baseId;
}}
{{? $thenPresent || $elsePresent }}
{{
var $ifClause;
$it.createErrors = false;
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
}}
var {{=$errs}} = errors;
var {{=$valid}} = true;
{{# def.setCompositeRule }}
{{# def.insertSubschemaCode }}
{{ $it.createErrors = true; }}
{{# def.resetErrors }}
{{# def.resetCompositeRule }}
{{? $thenPresent }}
if ({{=$nextValid}}) {
{{# def.validateIfClause:then }}
}
{{? $elsePresent }}
else {
{{?}}
{{??}}
if (!{{=$nextValid}}) {
{{?}}
{{? $elsePresent }}
{{# def.validateIfClause:else }}
}
{{?}}
if (!{{=$valid}}) {
{{# def.extraError:'if' }}
}
{{? $breakOnError }} else { {{?}}
{{??}}
{{? $breakOnError }}
if (true) {
{{?}}
{{?}}

98
node_modules/ajv/lib/dot/items.jst generated vendored Normal file
View File

@@ -0,0 +1,98 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{## def.validateItems:startFrom:
for (var {{=$idx}} = {{=startFrom}}; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
{{
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
}}
{{# def.generateSubschemaCode }}
{{# def.optimizeValidate }}
{{? $breakOnError }}
if (!{{=$nextValid}}) break;
{{?}}
}
#}}
{{
var $idx = 'i' + $lvl
, $dataNxt = $it.dataLevel = it.dataLevel + 1
, $nextData = 'data' + $dataNxt
, $currentBaseId = it.baseId;
}}
var {{=$errs}} = errors;
var {{=$valid}};
{{? Array.isArray($schema) }}
{{ /* 'items' is an array of schemas */}}
{{ var $additionalItems = it.schema.additionalItems; }}
{{? $additionalItems === false }}
{{=$valid}} = {{=$data}}.length <= {{= $schema.length }};
{{
var $currErrSchemaPath = $errSchemaPath;
$errSchemaPath = it.errSchemaPath + '/additionalItems';
}}
{{# def.checkError:'additionalItems' }}
{{ $errSchemaPath = $currErrSchemaPath; }}
{{# def.elseIfValid}}
{{?}}
{{~ $schema:$sch:$i }}
{{? {{# def.nonEmptySchema:$sch }} }}
{{=$nextValid}} = true;
if ({{=$data}}.length > {{=$i}}) {
{{
var $passData = $data + '[' + $i + ']';
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
$it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
$it.dataPathArr[$dataNxt] = $i;
}}
{{# def.generateSubschemaCode }}
{{# def.optimizeValidate }}
}
{{# def.ifResultValid }}
{{?}}
{{~}}
{{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }}
{{
$it.schema = $additionalItems;
$it.schemaPath = it.schemaPath + '.additionalItems';
$it.errSchemaPath = it.errSchemaPath + '/additionalItems';
}}
{{=$nextValid}} = true;
if ({{=$data}}.length > {{= $schema.length }}) {
{{# def.validateItems: $schema.length }}
}
{{# def.ifResultValid }}
{{?}}
{{?? {{# def.nonEmptySchema:$schema }} }}
{{ /* 'items' is a single schema */}}
{{
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
}}
{{# def.validateItems: 0 }}
{{?}}
{{? $breakOnError }}
{{= $closingBraces }}
if ({{=$errs}} == errors) {
{{?}}

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