trading process

This commit is contained in:
Luis Fernando Molina committed 2020-12-03 09:34:09 +01:00
1 parent e4aa988cb2
commit fa6569299c
102 files changed
+13294 -1063

No files matched your search

+7
View File
@@ -554,6 +554,13 @@
"functionName": "newSuperalgosBotModulesTelegramBot",
"fileName": "TelegramBot.js",
"folderName": "Trading-Bot/Announcements"
},
{
"name": "Trading Process",
"propertyName": "tradingProcess",
"functionName": "newSuperalgosBotModulesTradingProcess",
"fileName": "TradingProcess.js",
"folderName": "Trading-Bot/Low-Frequency-Trading"
}
]
},
@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../telegraf/bin/telegraf" "$@"
ret=$?
else
node "$basedir/../telegraf/bin/telegraf" "$@"
ret=$?
fi
exit $ret
@@ -0,0 +1,17 @@
@ECHO off
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
"%_prog%" "%dp0%\..\telegraf\bin\telegraf" %*
ENDLOCAL
EXIT /b %errorlevel%
:find_dp0
SET dp0=%~dp0
EXIT /b
@@ -0,0 +1,18 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
& "$basedir/node$exe" "$basedir/../telegraf/bin/telegraf" $args
$ret=$LASTEXITCODE
} else {
& "node$exe" "$basedir/../telegraf/bin/telegraf" $args
$ret=$LASTEXITCODE
}
exit $ret
@@ -0,0 +1,19 @@
(The MIT License)
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,455 @@
# debug
[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
`disable()`
Will disable all namespaces. The functions returns the namespaces currently
enabled (and skipped). This can be useful if you want to disable debugging
temporarily without knowing what was enabled to begin with.
For example:
```js
let debug = require('debug');
debug.enable('foo:*,-foo:bar');
let namespaces = debug.disable();
debug.enable(namespaces);
```
Note: There is no guarantee that the string will be identical to the initial
enable string, but semantically they will be identical.
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
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.
@@ -1,8 +1,8 @@
{
"_from": "debug@^4.0.1",
"_id": "debug@4.1.1",
"_id": "debug@4.3.1",
"_inBundle": false,
"_integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
"_integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==",
"_location": "/debug",
"_phantomChildren": {},
"_requested": {
@@ -18,10 +18,10 @@
"_requiredBy": [
"/telegraf"
],
"_resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
"_shasum": "3b72260255109c6b589cee050f1d516139664791",
"_resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz",
"_shasum": "f0d229c505e0c6d8c49ac553d1b13dc183f6b2ee",
"_spec": "debug@^4.0.1",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\telegraf",
"_where": "c:\\Superalgos\\Projects\\Superalgos\\TS\\Bot-Modules\\Trading-Bot\\Announcements\\node_modules\\telegraf",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
@@ -40,34 +40,35 @@
{
"name": "Andrew Rhyne",
"email": "rhyneandrew@gmail.com"
},
{
"name": "Josh Junon",
"email": "josh@junon.me"
}
],
"dependencies": {
"ms": "^2.1.1"
"ms": "2.1.2"
},
"deprecated": false,
"description": "small debugging utility",
"devDependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"browserify": "14.4.0",
"chai": "^3.5.0",
"concurrently": "^3.1.0",
"brfs": "^2.0.1",
"browserify": "^16.2.3",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.0.0",
"karma-chai": "^0.1.0",
"karma": "^3.1.4",
"karma-browserify": "^6.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"rimraf": "^2.5.4",
"xo": "^0.23.0"
},
"engines": {
"node": ">=6.0"
},
"files": [
"src",
"dist/debug.js",
"LICENSE",
"README.md"
],
@@ -80,23 +81,21 @@
"license": "MIT",
"main": "./src/index.js",
"name": "debug",
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
},
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"scripts": {
"build": "npm run build:debug && npm run build:test",
"build:debug": "babel -o dist/debug.js dist/debug.es6.js > dist/debug.js",
"build:test": "babel -d dist test.js",
"clean": "rimraf dist coverage",
"lint": "xo",
"prebuild:debug": "mkdir -p dist && browserify --standalone debug -o dist/debug.es6.js .",
"pretest:browser": "npm run build",
"test": "npm run test:node && npm run test:browser",
"test": "npm run test:node && npm run test:browser && npm run lint",
"test:browser": "karma start --single-run",
"test:coverage": "cat ./coverage/lcov.info | coveralls",
"test:node": "istanbul cover _mocha -- test.js"
},
"unpkg": "./dist/debug.js",
"version": "4.1.1"
"version": "4.3.1"
}
@@ -4,12 +4,21 @@
* This is the web browser implementation of `debug()`.
*/
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
@@ -170,18 +179,14 @@ function formatArgs(args) {
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
function log(...args) {
// This hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return typeof console === 'object' &&
console.log &&
console.log(...args);
}
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
@@ -12,16 +12,12 @@ function setup(env) {
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
@@ -63,6 +59,7 @@ function setup(env) {
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
function debug(...args) {
// Disabled?
@@ -92,7 +89,7 @@ function setup(env) {
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
return '%';
}
index++;
const formatter = createDebug.formatters[format];
@@ -115,33 +112,28 @@ function setup(env) {
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
// Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
// env-specific initialization logic for debug instances
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
const index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
@@ -179,11 +171,6 @@ function setup(env) {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
const instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
@@ -258,6 +245,14 @@ function setup(env) {
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
@@ -15,6 +15,10 @@ exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
@@ -244,7 +248,9 @@ const {formatters} = module.exports;
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.replace(/\s*\n\s*/g, ' ');
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
@@ -0,0 +1,8 @@
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
- "iojs"
before_install:
- npm install -g npm@~1.4.6
@@ -0,0 +1,18 @@
This software is released under the MIT license:
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.
@@ -21,7 +21,7 @@
"_resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
"_shasum": "67d66014b66a6a8aaa0c083c5fd58df4e4e97602",
"_spec": "minimist@^1.2.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\telegraf",
"_where": "c:\\Superalgos\\Projects\\Superalgos\\TS\\Bot-Modules\\Trading-Bot\\Announcements\\node_modules\\telegraf",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
@@ -0,0 +1,95 @@
# minimist
parse argument options
This module is the guts of optimist's argument parser without all the
fanciful decoration.
# example
``` js
var argv = require('minimist')(process.argv.slice(2));
console.log(argv);
```
```
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
```
```
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
x: 3,
y: 4,
n: 5,
a: true,
b: true,
c: true,
beep: 'boop' }
```
# security
Previous versions had a prototype pollution bug that could cause privilege
escalation in some circumstances when handling untrusted user input.
Please use version 1.2.3 or later: https://snyk.io/vuln/SNYK-JS-MINIMIST-559764
# methods
``` js
var parseArgs = require('minimist')
```
## var argv = parseArgs(args, opts={})
Return an argument object `argv` populated with the array arguments from `args`.
`argv._` contains all the arguments that didn't have an option associated with
them.
Numeric-looking arguments will be returned as numbers unless `opts.string` or
`opts.boolean` is set for that argument name.
Any arguments after `'--'` will not be parsed and will end up in `argv._`.
options can be:
* `opts.string` - a string or array of strings argument names to always treat as
strings
* `opts.boolean` - a boolean, string or array of strings to always treat as
booleans. if `true` will treat all double hyphenated arguments without equal signs
as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`)
* `opts.alias` - an object mapping string names to strings or arrays of string
argument names to use as aliases
* `opts.default` - an object mapping string argument names to default values
* `opts.stopEarly` - when true, populate `argv._` with everything after the
first non-option
* `opts['--']` - when true, populate `argv._` with everything before the `--`
and `argv['--']` with everything after the `--`. Here's an example:
```
> require('./')('one two three -- four five --six'.split(' '), { '--': true })
{ _: [ 'one', 'two', 'three' ],
'--': [ 'four', 'five', '--six' ] }
```
Note that with `opts['--']` set, parsing for arguments still stops after the
`--`.
* `opts.unknown` - a function which is invoked with a command line parameter not
defined in the `opts` configuration object. If the function returns `false`, the
unknown option is not added to `argv`.
# install
With [npm](https://npmjs.org) do:
```
npm install minimist
```
# license
MIT
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018, Nick Gavrilov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,159 @@
# module-alias
[![NPM Version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
Create aliases of directories and register custom module paths in NodeJS like a boss!
No more shit-coding paths in Node like so:
```js
require('../../../../some/very/deep/module')
```
Enough of this madness!
Just create an alias and do it the right way:
```js
var module = require('@deep/module')
// Or ES6
import module from '@deep/module'
```
It also allows you to register directories that will act just like `node_modules` but with your own private modules, so that you can access them directly:
```js
require('my_private_module');
// Or ES6
import module from 'my_private_module'
```
**WARNING:** This module should not be used in other npm modules since it modifies the default `require` behavior! It is designed to be used for development of final projects i.e. web-sites, applications etc.
## Install
```
npm i --save module-alias
```
## Usage
Add your custom configuration to your `package.json` (in your application's root)
```js
// Aliases
"_moduleAliases": {
"@root" : ".", // Application's root
"@deep" : "src/some/very/deep/directory/or/file",
"@my_module" : "lib/some-file.js",
"something" : "src/foo", // Or without @. Actually, it could be any string
}
// Custom module directories, just like `node_modules` but with your private modules (optional)
"_moduleDirectories": ["node_modules_custom"],
```
Then add this line at the very main file of your app, before any code
```js
require('module-alias/register')
```
**And you're all set!** Now you can do stuff like:
```js
require('something')
const module = require('@root/some-module')
const veryDeepModule = require('@deep/my-module')
const customModule = require('my_private_module') // module from `node_modules_custom` directory
// Or ES6
import 'something'
import module from '@root/some-module'
import veryDeepModule from '@deep/my-module'
import customModule from 'my_private_module' // module from `node_modules_custom` directory
```
## Advanced usage
If you don't want to modify your `package.json` or you just prefer to set it all up programmatically, then the following methods are available for you:
* `addAlias('alias', 'target_path')` - register a single alias
* `addAliases({ 'alias': 'target_path', ... }) ` - register multiple aliases
* `addPath(path)` - Register custom modules directory (like node_modules, but with your own modules)
_Examples:_
```js
const moduleAlias = require('module-alias')
//
// Register alias
//
moduleAlias.addAlias('@client', __dirname + '/src/client')
// Or multiple aliases
moduleAlias.addAliases({
'@root' : __dirname,
'@client': __dirname + '/src/client',
...
})
// Custom handler function (starting from v2.1)
moduleAlias.addAlias('@src', (fromPath, request, alias) => {
// fromPath - Full path of the file from which `require` was called
// request - The path (first argument) that was passed into `require`
// alias - The same alias that was passed as first argument to `addAlias` (`@src` in this case)
// Return any custom target path for the `@src` alias depending on arguments
if (fromPath.startsWith(__dirname + '/others')) return __dirname + '/others'
return __dirname + '/src'
})
//
// Register custom modules directory
//
moduleAlias.addPath(__dirname + '/node_modules_custom')
moduleAlias.addPath(__dirname + '/src')
//
// Import settings from a specific package.json
//
moduleAlias(__dirname + '/package.json')
// Or let module-alias to figure where your package.json is
// located. By default it will look in the same directory
// where you have your node_modules (application's root)
moduleAlias()
```
## Usage with WebPack
Luckily, WebPack has a built in support for aliases and custom modules directories so it's easy to make it work on the client side as well!
```js
// webpack.config.js
const npm_package = require('./package.json')
module.exports = {
entry: { ... },
resolve: {
root: __dirname,
alias: npm_package._moduleAliases || {},
modules: npm_package._moduleDirectories || [] // eg: ["node_modules", "node_modules_custom", "src"]
}
}
```
## How it works?
In order to register an alias it modifies the internal `Module._resolveFilename` method so that when you use `require` or `import` it first checks whether the given string starts with one of the registered aliases, if so, it replaces the alias in the string with the target path of the alias.
In order to register a custom modules path (`addPath`) it modifies the internal `Module._nodeModulePaths` method so that the given directory then acts like it's the `node_modules` directory.
[npm-image]: https://img.shields.io/npm/v/module-alias.svg
[npm-url]: https://npmjs.org/package/module-alias
[travis-image]: https://img.shields.io/travis/ilearnio/module-alias/master.svg
[travis-url]: https://travis-ci.org/ilearnio/module-alias
## Refactor your code (for already existing projects)
If you are using this on an existing project, you can use [relative-to-alias](https://github.com/s-yadav/relative-to-alias) to refactor your code to start using aliases.
@@ -21,7 +21,7 @@
"_resolved": "https://registry.npmjs.org/module-alias/-/module-alias-2.2.2.tgz",
"_shasum": "151cdcecc24e25739ff0aa6e51e1c5716974c0e0",
"_spec": "module-alias@^2.2.2",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\telegraf",
"_where": "c:\\Superalgos\\Projects\\Superalgos\\TS\\Bot-Modules\\Trading-Bot\\Announcements\\node_modules\\telegraf",
"author": {
"name": "Nick Gavrilov",
"email": "artnikpro@gmail.com"
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Zeit, Inc.
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.
@@ -1,27 +1,27 @@
{
"_from": "ms@^2.1.1",
"_from": "ms@2.1.2",
"_id": "ms@2.1.2",
"_inBundle": false,
"_integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
"_location": "/ms",
"_phantomChildren": {},
"_requested": {
"type": "range",
"type": "version",
"registry": true,
"raw": "ms@^2.1.1",
"raw": "ms@2.1.2",
"name": "ms",
"escapedName": "ms",
"rawSpec": "^2.1.1",
"rawSpec": "2.1.2",
"saveSpec": null,
"fetchSpec": "^2.1.1"
"fetchSpec": "2.1.2"
},
"_requiredBy": [
"/debug"
],
"_resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"_shasum": "d09d1f357b443f493382a8eb3ccd183872ae6009",
"_spec": "ms@^2.1.1",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\debug",
"_spec": "ms@2.1.2",
"_where": "c:\\Superalgos\\Projects\\Superalgos\\TS\\Bot-Modules\\Trading-Bot\\Announcements\\node_modules\\debug",
"bugs": {
"url": "https://github.com/zeit/ms/issues"
},
@@ -0,0 +1,60 @@
# ms
[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms)
[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`
@@ -0,0 +1,272 @@
Changelog
=========
# 2.x release
## v2.6.1
**This is an important security release. It is strongly recommended to update as soon as possible.**
- Fix: honor the `size` option after following a redirect.
## v2.6.0
- Enhance: `options.agent`, it now accepts a function that returns custom http(s).Agent instance based on current URL, see readme for more information.
- Fix: incorrect `Content-Length` was returned for stream body in 2.5.0 release; note that `node-fetch` doesn't calculate content length for stream body.
- Fix: `Response.url` should return empty string instead of `null` by default.
## v2.5.0
- Enhance: `Response` object now includes `redirected` property.
- Enhance: `fetch()` now accepts third-party `Blob` implementation as body.
- Other: disable `package-lock.json` generation as we never commit them.
- Other: dev dependency update.
- Other: readme update.
## v2.4.1
- Fix: `Blob` import rule for node < 10, as `Readable` isn't a named export.
## v2.4.0
- Enhance: added `Brotli` compression support (using node's zlib).
- Enhance: updated `Blob` implementation per spec.
- Fix: set content type automatically for `URLSearchParams`.
- Fix: `Headers` now reject empty header names.
- Fix: test cases, as node 12+ no longer accepts invalid header response.
## v2.3.0
- Enhance: added `AbortSignal` support, with README example.
- Enhance: handle invalid `Location` header during redirect by rejecting them explicitly with `FetchError`.
- Fix: update `browser.js` to support react-native environment, where `self` isn't available globally.
## v2.2.1
- Fix: `compress` flag shouldn't overwrite existing `Accept-Encoding` header.
- Fix: multiple `import` rules, where `PassThrough` etc. doesn't have a named export when using node <10 and `--exerimental-modules` flag.
- Other: Better README.
## v2.2.0
- Enhance: Support all `ArrayBuffer` view types
- Enhance: Support Web Workers
- Enhance: Support Node.js' `--experimental-modules` mode; deprecate `.es.js` file
- Fix: Add `__esModule` property to the exports object
- Other: Better example in README for writing response to a file
- Other: More tests for Agent
## v2.1.2
- Fix: allow `Body` methods to work on `ArrayBuffer`-backed `Body` objects
- Fix: reject promise returned by `Body` methods when the accumulated `Buffer` exceeds the maximum size
- Fix: support custom `Host` headers with any casing
- Fix: support importing `fetch()` from TypeScript in `browser.js`
- Fix: handle the redirect response body properly
## v2.1.1
Fix packaging errors in v2.1.0.
## v2.1.0
- Enhance: allow using ArrayBuffer as the `body` of a `fetch()` or `Request`
- Fix: store HTTP headers of a `Headers` object internally with the given case, for compatibility with older servers that incorrectly treated header names in a case-sensitive manner
- Fix: silently ignore invalid HTTP headers
- Fix: handle HTTP redirect responses without a `Location` header just like non-redirect responses
- Fix: include bodies when following a redirection when appropriate
## v2.0.0
This is a major release. Check [our upgrade guide](https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md) for an overview on some key differences between v1 and v2.
### General changes
- Major: Node.js 0.10.x and 0.12.x support is dropped
- Major: `require('node-fetch/lib/response')` etc. is now unsupported; use `require('node-fetch').Response` or ES6 module imports
- Enhance: start testing on Node.js v4.x, v6.x, v8.x LTS, as well as v9.x stable
- Enhance: use Rollup to produce a distributed bundle (less memory overhead and faster startup)
- Enhance: make `Object.prototype.toString()` on Headers, Requests, and Responses return correct class strings
- Other: rewrite in ES2015 using Babel
- Other: use Codecov for code coverage tracking
- Other: update package.json script for npm 5
- Other: `encoding` module is now optional (alpha.7)
- Other: expose browser.js through package.json, avoid bundling mishaps (alpha.9)
- Other: allow TypeScript to `import` node-fetch by exposing default (alpha.9)
### HTTP requests
- Major: overwrite user's `Content-Length` if we can be sure our information is correct (per spec)
- Fix: errors in a response are caught before the body is accessed
- Fix: support WHATWG URL objects, created by `whatwg-url` package or `require('url').URL` in Node.js 7+
### Response and Request classes
- Major: `response.text()` no longer attempts to detect encoding, instead always opting for UTF-8 (per spec); use `response.textConverted()` for the v1 behavior
- Major: make `response.json()` throw error instead of returning an empty object on 204 no-content respose (per spec; reverts behavior changed in v1.6.2)
- Major: internal methods are no longer exposed
- Major: throw error when a `GET` or `HEAD` Request is constructed with a non-null body (per spec)
- Enhance: add `response.arrayBuffer()` (also applies to Requests)
- Enhance: add experimental `response.blob()` (also applies to Requests)
- Enhance: `URLSearchParams` is now accepted as a body
- Enhance: wrap `response.json()` json parsing error as `FetchError`
- Fix: fix Request and Response with `null` body
### Headers class
- Major: remove `headers.getAll()`; make `get()` return all headers delimited by commas (per spec)
- Enhance: make Headers iterable
- Enhance: make Headers constructor accept an array of tuples
- Enhance: make sure header names and values are valid in HTTP
- Fix: coerce Headers prototype function parameters to strings, where applicable
### Documentation
- Enhance: more comprehensive API docs
- Enhance: add a list of default headers in README
# 1.x release
## backport releases (v1.7.0 and beyond)
See [changelog on 1.x branch](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) for details.
## v1.6.3
- Enhance: error handling document to explain `FetchError` design
- Fix: support `form-data` 2.x releases (requires `form-data` >= 2.1.0)
## v1.6.2
- Enhance: minor document update
- Fix: response.json() returns empty object on 204 no-content response instead of throwing a syntax error
## v1.6.1
- Fix: if `res.body` is a non-stream non-formdata object, we will call `body.toString` and send it as a string
- Fix: `counter` value is incorrectly set to `follow` value when wrapping Request instance
- Fix: documentation update
## v1.6.0
- Enhance: added `res.buffer()` api for convenience, it returns body as a Node.js buffer
- Enhance: better old server support by handling raw deflate response
- Enhance: skip encoding detection for non-HTML/XML response
- Enhance: minor document update
- Fix: HEAD request doesn't need decompression, as body is empty
- Fix: `req.body` now accepts a Node.js buffer
## v1.5.3
- Fix: handle 204 and 304 responses when body is empty but content-encoding is gzip/deflate
- Fix: allow resolving response and cloned response in any order
- Fix: avoid setting `content-length` when `form-data` body use streams
- Fix: send DELETE request with content-length when body is present
- Fix: allow any url when calling new Request, but still reject non-http(s) url in fetch
## v1.5.2
- Fix: allow node.js core to handle keep-alive connection pool when passing a custom agent
## v1.5.1
- Fix: redirect mode `manual` should work even when there is no redirection or broken redirection
## v1.5.0
- Enhance: rejected promise now use custom `Error` (thx to @pekeler)
- Enhance: `FetchError` contains `err.type` and `err.code`, allows for better error handling (thx to @pekeler)
- Enhance: basic support for redirect mode `manual` and `error`, allows for location header extraction (thx to @jimmywarting for the initial PR)
## v1.4.1
- Fix: wrapping Request instance with FormData body again should preserve the body as-is
## v1.4.0
- Enhance: Request and Response now have `clone` method (thx to @kirill-konshin for the initial PR)
- Enhance: Request and Response now have proper string and buffer body support (thx to @kirill-konshin)
- Enhance: Body constructor has been refactored out (thx to @kirill-konshin)
- Enhance: Headers now has `forEach` method (thx to @tricoder42)
- Enhance: back to 100% code coverage
- Fix: better form-data support (thx to @item4)
- Fix: better character encoding detection under chunked encoding (thx to @dsuket for the initial PR)
## v1.3.3
- Fix: make sure `Content-Length` header is set when body is string for POST/PUT/PATCH requests
- Fix: handle body stream error, for cases such as incorrect `Content-Encoding` header
- Fix: when following certain redirects, use `GET` on subsequent request per Fetch Spec
- Fix: `Request` and `Response` constructors now parse headers input using `Headers`
## v1.3.2
- Enhance: allow auto detect of form-data input (no `FormData` spec on node.js, this is form-data specific feature)
## v1.3.1
- Enhance: allow custom host header to be set (server-side only feature, as it's a forbidden header on client-side)
## v1.3.0
- Enhance: now `fetch.Request` is exposed as well
## v1.2.1
- Enhance: `Headers` now normalized `Number` value to `String`, prevent common mistakes
## v1.2.0
- Enhance: now fetch.Headers and fetch.Response are exposed, making testing easier
## v1.1.2
- Fix: `Headers` should only support `String` and `Array` properties, and ignore others
## v1.1.1
- Enhance: now req.headers accept both plain object and `Headers` instance
## v1.1.0
- Enhance: timeout now also applies to response body (in case of slow response)
- Fix: timeout is now cleared properly when fetch is done/has failed
## v1.0.6
- Fix: less greedy content-type charset matching
## v1.0.5
- Fix: when `follow = 0`, fetch should not follow redirect
- Enhance: update tests for better coverage
- Enhance: code formatting
- Enhance: clean up doc
## v1.0.4
- Enhance: test iojs support
- Enhance: timeout attached to socket event only fire once per redirect
## v1.0.3
- Fix: response size limit should reject large chunk
- Enhance: added character encoding detection for xml, such as rss/atom feed (encoding in DTD)
## v1.0.2
- Fix: added res.ok per spec change
## v1.0.0
- Enhance: better test coverage and doc
# 0.x release
## v0.1
- Major: initial public release
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 David Frank
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,590 @@
node-fetch
==========
[![npm version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![coverage status][codecov-image]][codecov-url]
[![install size][install-size-image]][install-size-url]
[![Discord][discord-image]][discord-url]
A light-weight module that brings `window.fetch` to Node.js
(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567))
[![Backers][opencollective-image]][opencollective-url]
<!-- TOC -->
- [Motivation](#motivation)
- [Features](#features)
- [Difference from client-side fetch](#difference-from-client-side-fetch)
- [Installation](#installation)
- [Loading and configuring the module](#loading-and-configuring-the-module)
- [Common Usage](#common-usage)
- [Plain text or HTML](#plain-text-or-html)
- [JSON](#json)
- [Simple Post](#simple-post)
- [Post with JSON](#post-with-json)
- [Post with form parameters](#post-with-form-parameters)
- [Handling exceptions](#handling-exceptions)
- [Handling client and server errors](#handling-client-and-server-errors)
- [Advanced Usage](#advanced-usage)
- [Streams](#streams)
- [Buffer](#buffer)
- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)
- [Extract Set-Cookie Header](#extract-set-cookie-header)
- [Post data using a file stream](#post-data-using-a-file-stream)
- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)
- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
- [API](#api)
- [fetch(url[, options])](#fetchurl-options)
- [Options](#options)
- [Class: Request](#class-request)
- [Class: Response](#class-response)
- [Class: Headers](#class-headers)
- [Interface: Body](#interface-body)
- [Class: FetchError](#class-fetcherror)
- [License](#license)
- [Acknowledgement](#acknowledgement)
<!-- /TOC -->
## Motivation
Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.
See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).
## Features
- Stay consistent with `window.fetch` API.
- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.
- Use native promise but allow substituting it with [insert your favorite promise library].
- Use native Node streams for body on both request and response.
- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.
- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting.
## Difference from client-side fetch
- See [Known Differences](LIMITS.md) for details.
- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.
- Pull requests are welcomed too!
## Installation
Current stable release (`2.x`)
```sh
$ npm install node-fetch
```
## Loading and configuring the module
We suggest you load the module via `require` until the stabilization of ES modules in node:
```js
const fetch = require('node-fetch');
```
If you are using a Promise library other than native, set it through `fetch.Promise`:
```js
const Bluebird = require('bluebird');
fetch.Promise = Bluebird;
```
## Common Usage
NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences.
#### Plain text or HTML
```js
fetch('https://github.com/')
.then(res => res.text())
.then(body => console.log(body));
```
#### JSON
```js
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(json => console.log(json));
```
#### Simple Post
```js
fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
.then(res => res.json()) // expecting a json response
.then(json => console.log(json));
```
#### Post with JSON
```js
const body = { a: 1 };
fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
```
#### Post with form parameters
`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.
NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:
```js
const { URLSearchParams } = require('url');
const params = new URLSearchParams();
params.append('a', 1);
fetch('https://httpbin.org/post', { method: 'POST', body: params })
.then(res => res.json())
.then(json => console.log(json));
```
#### Handling exceptions
NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information.
Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details.
```js
fetch('https://domain.invalid/')
.catch(err => console.error(err));
```
#### Handling client and server errors
It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:
```js
function checkStatus(res) {
if (res.ok) { // res.status >= 200 && res.status < 300
return res;
} else {
throw MyCustomError(res.statusText);
}
}
fetch('https://httpbin.org/status/400')
.then(checkStatus)
.then(res => console.log('will not get here...'))
```
## Advanced Usage
#### Streams
The "Node.js way" is to use streams when possible:
```js
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => {
const dest = fs.createWriteStream('./octocat.png');
res.body.pipe(dest);
});
```
#### Buffer
If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API)
```js
const fileType = require('file-type');
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => res.buffer())
.then(buffer => fileType(buffer))
.then(type => { /* ... */ });
```
#### Accessing Headers and other Meta data
```js
fetch('https://github.com/')
.then(res => {
console.log(res.ok);
console.log(res.status);
console.log(res.statusText);
console.log(res.headers.raw());
console.log(res.headers.get('content-type'));
});
```
#### Extract Set-Cookie Header
Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.
```js
fetch(url).then(res => {
// returns an array of values, instead of a string of comma-separated values
console.log(res.headers.raw()['set-cookie']);
});
```
#### Post data using a file stream
```js
const { createReadStream } = require('fs');
const stream = createReadStream('input.txt');
fetch('https://httpbin.org/post', { method: 'POST', body: stream })
.then(res => res.json())
.then(json => console.log(json));
```
#### Post with form-data (detect multipart)
```js
const FormData = require('form-data');
const form = new FormData();
form.append('a', 1);
fetch('https://httpbin.org/post', { method: 'POST', body: form })
.then(res => res.json())
.then(json => console.log(json));
// OR, using custom headers
// NOTE: getHeaders() is non-standard API
const form = new FormData();
form.append('a', 1);
const options = {
method: 'POST',
body: form,
headers: form.getHeaders()
}
fetch('https://httpbin.org/post', options)
.then(res => res.json())
.then(json => console.log(json));
```
#### Request cancellation with AbortSignal
> NOTE: You may cancel streamed requests only on Node >= v8.0.0
You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).
An example of timing out a request after 150ms could be achieved as the following:
```js
import AbortController from 'abort-controller';
const controller = new AbortController();
const timeout = setTimeout(
() => { controller.abort(); },
150,
);
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(
data => {
useData(data)
},
err => {
if (err.name === 'AbortError') {
// request was aborted
}
},
)
.finally(() => {
clearTimeout(timeout);
});
```
See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples.
## API
### fetch(url[, options])
- `url` A string representing the URL for fetching
- `options` [Options](#fetch-options) for the HTTP(S) request
- Returns: <code>Promise&lt;[Response](#class-response)&gt;</code>
Perform an HTTP(S) fetch.
`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.
<a id="fetch-options"></a>
### Options
The default values are shown after each option key.
```js
{
// These properties are part of the Fetch Standard
method: 'GET',
headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)
body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream
redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect
signal: null, // pass an instance of AbortSignal to optionally abort requests
// The following properties are node-fetch extensions
follow: 20, // maximum redirect count. 0 to not follow redirect
timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.
compress: true, // support gzip/deflate content encoding. false to disable
size: 0, // maximum response body size in bytes. 0 to disable
agent: null // http(s).Agent instance or function that returns an instance (see below)
}
```
##### Default Headers
If no values are set, the following request headers will be sent automatically:
Header | Value
------------------- | --------------------------------------------------------
`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_
`Accept` | `*/*`
`Connection` | `close` _(when no `options.agent` is present)_
`Content-Length` | _(automatically calculated, if possible)_
`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_
`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)`
Note: when `body` is a `Stream`, `Content-Length` is not set automatically.
##### Custom Agent
The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:
- Support self-signed certificate
- Use only IPv4 or IPv6
- Custom DNS Lookup
See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.
In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.
```js
const httpAgent = new http.Agent({
keepAlive: true
});
const httpsAgent = new https.Agent({
keepAlive: true
});
const options = {
agent: function (_parsedURL) {
if (_parsedURL.protocol == 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
}
```
<a id="class-request"></a>
### Class: Request
An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.
Due to the nature of Node.js, the following properties are not implemented at this moment:
- `type`
- `destination`
- `referrer`
- `referrerPolicy`
- `mode`
- `credentials`
- `cache`
- `integrity`
- `keepalive`
The following node-fetch extension properties are provided:
- `follow`
- `compress`
- `counter`
- `agent`
See [options](#fetch-options) for exact meaning of these extensions.
#### new Request(input[, options])
<small>*(spec-compliant)*</small>
- `input` A string representing a URL, or another `Request` (which will be cloned)
- `options` [Options][#fetch-options] for the HTTP(S) request
Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).
In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.
<a id="class-response"></a>
### Class: Response
An HTTP(S) response. This class implements the [Body](#iface-body) interface.
The following properties are not implemented in node-fetch at this moment:
- `Response.error()`
- `Response.redirect()`
- `type`
- `trailer`
#### new Response([body[, options]])
<small>*(spec-compliant)*</small>
- `body` A `String` or [`Readable` stream][node-readable]
- `options` A [`ResponseInit`][response-init] options dictionary
Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).
Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.
#### response.ok
<small>*(spec-compliant)*</small>
Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.
#### response.redirected
<small>*(spec-compliant)*</small>
Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.
<a id="class-headers"></a>
### Class: Headers
This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.
#### new Headers([init])
<small>*(spec-compliant)*</small>
- `init` Optional argument to pre-fill the `Headers` object
Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.
```js
// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
const meta = {
'Content-Type': 'text/xml',
'Breaking-Bad': '<3'
};
const headers = new Headers(meta);
// The above is equivalent to
const meta = [
[ 'Content-Type', 'text/xml' ],
[ 'Breaking-Bad', '<3' ]
];
const headers = new Headers(meta);
// You can in fact use any iterable objects, like a Map or even another Headers
const meta = new Map();
meta.set('Content-Type', 'text/xml');
meta.set('Breaking-Bad', '<3');
const headers = new Headers(meta);
const copyOfHeaders = new Headers(headers);
```
<a id="iface-body"></a>
### Interface: Body
`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.
The following methods are not yet implemented in node-fetch at this moment:
- `formData()`
#### body.body
<small>*(deviation from spec)*</small>
* Node.js [`Readable` stream][node-readable]
Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].
#### body.bodyUsed
<small>*(spec-compliant)*</small>
* `Boolean`
A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.
#### body.arrayBuffer()
#### body.blob()
#### body.json()
#### body.text()
<small>*(spec-compliant)*</small>
* Returns: <code>Promise</code>
Consume the body and return a promise that will resolve to one of these formats.
#### body.buffer()
<small>*(node-fetch extension)*</small>
* Returns: <code>Promise&lt;Buffer&gt;</code>
Consume the body and return a promise that will resolve to a Buffer.
#### body.textConverted()
<small>*(node-fetch extension)*</small>
* Returns: <code>Promise&lt;String&gt;</code>
Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible.
(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.)
<a id="class-fetcherror"></a>
### Class: FetchError
<small>*(node-fetch extension)*</small>
An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.
<a id="class-aborterror"></a>
### Class: AbortError
<small>*(node-fetch extension)*</small>
An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.
## Acknowledgement
Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.
`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr).
## License
MIT
[npm-image]: https://flat.badgen.net/npm/v/node-fetch
[npm-url]: https://www.npmjs.com/package/node-fetch
[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch
[travis-url]: https://travis-ci.org/bitinn/node-fetch
[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master
[codecov-url]: https://codecov.io/gh/bitinn/node-fetch
[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch
[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch
[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square
[discord-url]: https://discord.gg/Zxbndcm
[opencollective-image]: https://opencollective.com/node-fetch/backers.svg
[opencollective-url]: https://opencollective.com/node-fetch
[whatwg-fetch]: https://fetch.spec.whatwg.org/
[response-init]: https://fetch.spec.whatwg.org/#responseinit
[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams
[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers
[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md
[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md
[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md
@@ -16,7 +16,9 @@ var global = getGlobal();
module.exports = exports = global.fetch;
// Needed for TypeScript and Webpack.
exports.default = global.fetch.bind(global);
if (global.fetch) {
exports.default = global.fetch.bind(global);
}
exports.Headers = global.Headers;
exports.Request = global.Request;
@@ -461,6 +461,12 @@ function convertBody(buffer, headers) {
// html4
if (!res && str) {
res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
if (!res) {
res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
if (res) {
res.pop(); // drop last quote
}
}
if (res) {
res = /charset=(.*)/i.exec(res.pop());
@@ -1468,7 +1474,7 @@ function fetch(url, opts) {
// HTTP fetch step 5.5
switch (request.redirect) {
case 'error':
reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
finalize();
return;
case 'manual':
@@ -1507,7 +1513,8 @@ function fetch(url, opts) {
method: request.method,
body: request.body,
signal: request.signal,
timeout: request.timeout
timeout: request.timeout,
size: request.size
};
// HTTP-redirect fetch step 9
@@ -465,6 +465,12 @@ function convertBody(buffer, headers) {
// html4
if (!res && str) {
res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
if (!res) {
res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
if (res) {
res.pop(); // drop last quote
}
}
if (res) {
res = /charset=(.*)/i.exec(res.pop());
@@ -1472,7 +1478,7 @@ function fetch(url, opts) {
// HTTP fetch step 5.5
switch (request.redirect) {
case 'error':
reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
finalize();
return;
case 'manual':
@@ -1511,7 +1517,8 @@ function fetch(url, opts) {
method: request.method,
body: request.body,
signal: request.signal,
timeout: request.timeout
timeout: request.timeout,
size: request.size
};
// HTTP-redirect fetch step 9
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,8 @@
{
"_from": "node-fetch@^2.2.0",
"_id": "node-fetch@2.6.0",
"_id": "node-fetch@2.6.1",
"_inBundle": false,
"_integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==",
"_integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==",
"_location": "/node-fetch",
"_phantomChildren": {},
"_requested": {
@@ -18,10 +18,10 @@
"_requiredBy": [
"/telegraf"
],
"_resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz",
"_shasum": "e633456386d4aa55863f676a7ab0daa8fdecb0fd",
"_resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
"_shasum": "045bd323631f76ed2e2b55573394416b639a0052",
"_spec": "node-fetch@^2.2.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\telegraf",
"_where": "c:\\Superalgos\\Projects\\Superalgos\\TS\\Bot-Modules\\Trading-Bot\\Announcements\\node_modules\\telegraf",
"author": {
"name": "David Frank"
},
@@ -89,5 +89,5 @@
"report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js",
"test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js"
},
"version": "2.6.0"
"version": "2.6.1"
}
@@ -0,0 +1,13 @@
# editorconfig.org
root = true
[*]
indent_size = 4
indent_style = space
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
@@ -0,0 +1,13 @@
Copyright 2013 Paul Connolley (connrs)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,58 @@
# SandwichStream
[![npm](https://img.shields.io/npm/v/sandwich-stream.svg?style=flat-square)](https://www.npmjs.com/package/sandwich-stream)
[![npm](https://img.shields.io/npm/dt/sandwich-stream.svg?style=flat-square)](https://www.npmjs.com/package/sandwich-stream)
[![Travis CI](https://img.shields.io/travis/connrs/node-sandwich-stream.svg?style=flat-square)](https://travis-ci.org/connrs/node-sandwich-stream)
[![codecov](https://img.shields.io/codecov/c/github/connrs/node-sandwich-stream.svg?style=flat-square)](https://codecov.io/gh/connrs/node-sandwich-stream)
[![Codacy Badge](https://img.shields.io/codacy/grade/6d64b00364bf413980280bd4e55d6115.svg?style=flat-square)](https://www.codacy.com/project/connrs/node-sandwich-stream/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=connrs/node-sandwich-stream&amp;utm_campaign=Badge_Grade_Dashboard)
[![Dependencies](https://david-dm.org/connrs/node-sandwich-stream.svg?style=flat-square)](https://codeclimate.com/github/connrs/node-sandwich-stream/master/package.json)
[![Known Vulnerabilities](https://snyk.io/test/github/connrs/node-sandwich-stream/badge.svg?style=flat-square&targetFile=package.json)](https://snyk.io/test/github/connrs/node-sandwich-stream?targetFile=package.json)
[![Maintainability](https://api.codeclimate.com/v1/badges/a6a00d50601938edfdad/maintainability)](https://codeclimate.com/github/connrs/node-sandwich-stream/maintainability)
## About
While I'm not overjoyed about how performant the internals will operate, I wanted a readable stream that was ACTUALLY A READABLE STREAM. Not a streams1 stream masquerading as streams2. As soon as somebody writes a better concat stream as a readable stream with a nice simple API, this baby is going to develop some serious abandonment issues.
## Installation
```bash
npm install sandwich-stream --save
```
**note**: this code was made using it [TypeScript](https://www.typescriptlang.org/), and its typings are linked in [package.json](./package.json), so there's no need of installing _@types/sandwich-stream_ or anything related.
## Usage
```typescript
import { SandwichStream } from 'sandwich-stream';
// OR EVEN:
// const SandwichStream = require('sandwich-stream');
const sandwich = SandwichStream({
head: 'Thing at the top\n',
tail: '\nThing at the bottom',
separator: '\n ---- \n'
});
sandwich.add(aStreamIPreparedEarlier)
.add(anotherStreamIPreparedEarlier)
.add(aFurtherStreamIPreparedEarlier)
.pipe(process.stdout);
// The thing at the top
// ----
// Stream1
// ----
// Stream2
// ----
// Stream3
// The thing at the bottom
```
## Configuration Options
* `head` option takes a string/buffer and pushes the string before all other content
* `foot` option takes a string/buffer and pushes the string after all other data has been pushed
* `separator` option pushes a string/buffer between each stream
* [Readable Options](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/be662c475da091788139b486a55708f02e2880b6/types/node/index.d.ts#L6485) can also be passed through.
## API
Too add a stream use the **.add** method: `sandwich.add(streamVariable);`
## More
Wanna known more about Node Streams? Read [this](https://medium.freecodecamp.org/node-js-streams-everything-you-need-to-know-c9141306be93).
@@ -0,0 +1,107 @@
/// <reference types="node" />
import { Readable, ReadableOptions } from 'stream';
/**
* Sandwich Options that will configure parsed data
*/
export interface SandwichOptions extends ReadableOptions {
readonly head?: string | Buffer;
readonly tail?: string | Buffer;
readonly separator?: string | Buffer;
}
/**
* Handles Readable streams requests as concatenation through data handling as
* well adding tags it each begin, end and between of the streams
*/
export declare class SandwichStream extends Readable {
private streamsActive;
private streams;
private newStreams;
private head;
private tail;
private separator;
private currentStream;
/**
* Initiates the SandwichStream, you can consider it also passing
* ReadableOptions to it
*
* @param head Pushes this content before all other content
* @param tail Pushes this content after all other data has been pushed
* @param separator Pushes this content between each stream
* @param remaining The other kind of options to be passed to Readable
* @example
* const ss = new SandwichStream({
* head: 'This at the top\n',
* tail: '\nThis at the bottom',
* separator: '\n --- \n'
* });
*/
constructor({ head, tail, separator, ...remaining }: SandwichOptions);
/**
* Add a new Readable stream in the queue
*
* @param newStream The Readable stream
* @example
* sandwichStream.add(streamOne);
* sandwichStream.add(streamTwo);
* sandwichStream.add(streamThree);
* @throws An Error in case that this request was not accepted
* @returns This instance of Sandwich Stream
*/
add(newStream: Readable): this;
/**
* Works in a similar way from the Readable read, only that this one checks
* for whether or not a stream is already being handled
* @returns This instance of Sandwich Stream
*/
_read(): void;
/**
* Binds an error thrown from one of the streams being handled
*
* @param err Error to be bind
* @returns This instance of Sandwich Stream
*/
private subStreamOnError;
/**
* Fetches the next stream to be handled
* @returns This instance of Sandwich Stream
*/
private streamNextStream;
/**
* Verifies whether or not the stream queue has ended
* @returns This instance of Sandwich Stream
*/
private nextStream;
/**
* Once the current stream starts to pass their data, this handles it in a
* less complicated way
* @returns This instance of Sandwich Stream
*/
private bindCurrentStreamEvents;
/**
* Handles the data from a current stream once they are being streamed
* @returns This instance of Sandwich Stream
*/
private currentStreamOnReadable;
/**
* Handles the tagging once a stream is finished
* @returns This instance of Sandwich Stream
*/
private currentStreamOnEnd;
/**
* Adds the head tag to the Sandwich Stream
* @returns This instance of Sandwich Stream
*/
private pushHead;
/**
* Adds the separator tag to the Sandwich Stream
* @returns This instance of Sandwich Stream
*/
private pushSeparator;
/**
* Adds the tail tag to the Sandwich Stream
* @returns This instance of Sandwich Stream
*/
private pushTail;
}
export default SandwichStream;
//# sourceMappingURL=sandwich-stream.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"sandwich-stream.d.ts","sourceRoot":"","sources":["src/sandwich-stream.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAEnD;;GAEG;AACH,MAAM,WAAW,eAAgB,SAAQ,eAAe;IACpD,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAChC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAChC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CACxC;AAED;;;GAGG;AACH,qBAAa,cAAe,SAAQ,QAAQ;IACxC,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,OAAO,CAAmB;IAClC,OAAO,CAAC,UAAU,CAAkB;IACpC,OAAO,CAAC,IAAI,CAAyB;IACrC,OAAO,CAAC,IAAI,CAAyB;IACrC,OAAO,CAAC,SAAS,CAAyB;IAC1C,OAAO,CAAC,aAAa,CAAyB;IAE9C;;;;;;;;;;;;;;OAcG;gBACS,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,SAAS,EAAE,EAAE,eAAe;IAQpE;;;;;;;;;;OAUG;IACI,GAAG,CAAC,SAAS,EAAE,QAAQ,GAAG,IAAI;IAWrC;;;;OAIG;IACI,KAAK,IAAI,IAAI;IAQpB;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IASxB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAOlB;;;;OAIG;IACH,OAAO,CAAC,uBAAuB;IAK/B;;;OAGG;IACH,OAAO,CAAC,uBAAuB;IAO/B;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAM1B;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAMhB;;;OAGG;IACH,OAAO,CAAC,aAAa;IAMrB;;;OAGG;IACH,OAAO,CAAC,QAAQ;CAKnB;AAED,eAAe,cAAc,CAAC"}
@@ -0,0 +1,181 @@
import { Readable } from 'stream';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
}
/**
* Handles Readable streams requests as concatenation through data handling as
* well adding tags it each begin, end and between of the streams
*/
class SandwichStream extends Readable {
/**
* Initiates the SandwichStream, you can consider it also passing
* ReadableOptions to it
*
* @param head Pushes this content before all other content
* @param tail Pushes this content after all other data has been pushed
* @param separator Pushes this content between each stream
* @param remaining The other kind of options to be passed to Readable
* @example
* const ss = new SandwichStream({
* head: 'This at the top\n',
* tail: '\nThis at the bottom',
* separator: '\n --- \n'
* });
*/
constructor(_a) {
var { head, tail, separator } = _a, remaining = __rest(_a, ["head", "tail", "separator"]);
super(remaining);
this.streamsActive = false;
this.streams = [];
this.newStreams = [];
this.currentStream = null;
this.head = (null !== head && undefined !== head) ? head : null;
this.tail = (null !== tail && undefined !== tail) ? tail : null;
this.separator = (null !== separator && undefined !== separator) ? separator : null;
}
/**
* Add a new Readable stream in the queue
*
* @param newStream The Readable stream
* @example
* sandwichStream.add(streamOne);
* sandwichStream.add(streamTwo);
* sandwichStream.add(streamThree);
* @throws An Error in case that this request was not accepted
* @returns This instance of Sandwich Stream
*/
add(newStream) {
if (false === this.streamsActive) {
this.streams.push(newStream);
newStream.on('error', this.subStreamOnError.bind(this));
}
else {
this.newStreams.push(newStream);
}
return this;
}
/**
* Works in a similar way from the Readable read, only that this one checks
* for whether or not a stream is already being handled
* @returns This instance of Sandwich Stream
*/
_read() {
if (false === this.streamsActive) {
this.streamsActive = true;
this.pushHead();
this.streamNextStream();
}
}
/**
* Binds an error thrown from one of the streams being handled
*
* @param err Error to be bind
* @returns This instance of Sandwich Stream
*/
subStreamOnError(err) {
this.emit('error', err);
}
/**
* Fetches the next stream to be handled
* @returns This instance of Sandwich Stream
*/
streamNextStream() {
if (true === this.nextStream()) {
this.bindCurrentStreamEvents();
}
else {
this.pushTail();
this.push(null);
}
}
/**
* Verifies whether or not the stream queue has ended
* @returns This instance of Sandwich Stream
*/
nextStream() {
const tmp = this.streams.shift();
this.currentStream = (undefined !== tmp) ? tmp : null;
return null !== this.currentStream;
}
/**
* Once the current stream starts to pass their data, this handles it in a
* less complicated way
* @returns This instance of Sandwich Stream
*/
bindCurrentStreamEvents() {
this.currentStream.on('readable', this.currentStreamOnReadable.bind(this));
this.currentStream.on('end', this.currentStreamOnEnd.bind(this));
}
/**
* Handles the data from a current stream once they are being streamed
* @returns This instance of Sandwich Stream
*/
currentStreamOnReadable() {
const tmp = this.currentStream.read();
const data = (undefined !== tmp && null !== tmp) ? tmp : '';
this.push(data);
}
/**
* Handles the tagging once a stream is finished
* @returns This instance of Sandwich Stream
*/
currentStreamOnEnd() {
this.pushSeparator();
this.streams.concat(this.newStreams);
this.newStreams = [];
this.streamNextStream();
}
/**
* Adds the head tag to the Sandwich Stream
* @returns This instance of Sandwich Stream
*/
pushHead() {
if (null !== this.head) {
this.push(this.head);
}
}
/**
* Adds the separator tag to the Sandwich Stream
* @returns This instance of Sandwich Stream
*/
pushSeparator() {
if (0 < this.streams.length && null !== this.separator) {
this.push(this.separator);
}
}
/**
* Adds the tail tag to the Sandwich Stream
* @returns This instance of Sandwich Stream
*/
pushTail() {
if (null !== this.tail) {
this.push(this.tail);
}
}
}
export default SandwichStream;
export { SandwichStream };
@@ -21,7 +21,7 @@
"_resolved": "https://registry.npmjs.org/sandwich-stream/-/sandwich-stream-2.0.2.tgz",
"_shasum": "6d1feb6cf7e9fe9fadb41513459a72c2e84000fa",
"_spec": "sandwich-stream@^2.0.1",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\telegraf",
"_where": "c:\\Superalgos\\Projects\\Superalgos\\TS\\Bot-Modules\\Trading-Bot\\Announcements\\node_modules\\telegraf",
"author": {
"name": "connrs",
"url": "https://connrs.uk/"
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016-2019 Vitaly Domnikov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,108 @@
#!/usr/bin/env node
const debug = require('debug')
const path = require('path')
const parse = require('minimist')
const { addAlias } = require('module-alias')
const Telegraf = require('../')
const log = debug('telegraf:cli')
const help = () => {
console.log(`Usage: telegraf [opts] <bot-file>
-t Bot token [$BOT_TOKEN]
-d Webhook domain
-H Webhook host [0.0.0.0]
-p Webhook port [$PORT or 3000]
-s Stop on error
-l Enable logs
-h Show this help message`)
}
const args = parse(process.argv, {
alias: {
t: 'token',
d: 'domain',
H: 'host',
h: 'help',
l: 'logs',
s: 'stop',
p: 'port'
},
boolean: ['h', 'l', 's'],
default: {
H: '0.0.0.0',
p: process.env.PORT || 3000
}
})
if (args.help) {
help()
process.exit(0)
}
const token = args.token || process.env.BOT_TOKEN
const domain = args.domain || process.env.BOT_DOMAIN
if (!token) {
console.error('Please supply Bot Token')
help()
process.exit(1)
}
let [, , file] = args._
if (!file) {
try {
const packageJson = require(path.resolve(process.cwd(), 'package.json'))
file = packageJson.main || 'index.js'
} catch (err) {
}
}
if (!file) {
console.error('Please supply a bot handler file.\n')
help()
process.exit(1)
}
if (file[0] !== '/') {
file = path.resolve(process.cwd(), file)
}
let botHandler
let httpHandler
let tlsOptions
try {
if (args.logs) {
debug.enable('telegraf:*')
}
addAlias('telegraf', path.join(__dirname, '../'))
const mod = require(file)
botHandler = mod.botHandler || mod
httpHandler = mod.httpHandler
tlsOptions = mod.tlsOptions
} catch (err) {
console.error(`Error importing ${file}`, err.stack)
process.exit(1)
}
const config = {}
if (domain) {
config.webhook = {
tlsOptions,
host: args.host,
port: args.port,
domain: domain,
cb: httpHandler
}
}
const bot = new Telegraf(token)
if (!args.stop) {
bot.catch(log)
}
bot.use(botHandler)
log(`Starting module ${file}`)
bot.launch(config)
@@ -1,33 +1,34 @@
{
"_from": "telegraf@^3.37.0",
"_from": "telegraf",
"_id": "telegraf@3.38.0",
"_inBundle": false,
"_integrity": "sha512-va4VlrKWp64JrowFoZX/NPzzA6q38kvaIukVXOWFO1V+jR1G8+hCfgJy4TX8Z3rwLJzwaBEet1QhikHDRZWl3A==",
"_location": "/telegraf",
"_phantomChildren": {},
"_requested": {
"type": "range",
"type": "tag",
"registry": true,
"raw": "telegraf@^3.37.0",
"raw": "telegraf",
"name": "telegraf",
"escapedName": "telegraf",
"rawSpec": "^3.37.0",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "^3.37.0"
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/telegraf/-/telegraf-3.38.0.tgz",
"_shasum": "745b447547a8e6cdb626055e4d616058aaae0759",
"_spec": "telegraf@^3.37.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer",
"_spec": "telegraf",
"_where": "c:\\Superalgos\\Projects\\Superalgos\\TS\\Bot-Modules\\Trading-Bot\\Announcements",
"author": {
"name": "Vitaly Domnikov",
"email": "oss@vitaly.codes"
},
"bin": {
"telegraf": "./bin/telegraf"
"telegraf": "bin/telegraf"
},
"bugs": {
"url": "https://github.com/telegraf/telegraf/issues"
@@ -0,0 +1,64 @@
![Telegraf](docs/header.png)
[![Bot API Version](https://img.shields.io/badge/Bot%20API-v4.8-f36caf.svg?style=flat-square)](https://core.telegram.org/bots/api)
[![NPM Version](https://img.shields.io/npm/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf)
[![node](https://img.shields.io/node/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf)
[![Build Status](https://img.shields.io/travis/telegraf/telegraf.svg?branch=master&style=flat-square)](https://travis-ci.org/telegraf/telegraf)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/)
[![Community Chat](https://img.shields.io/badge/Community-Chat-blueChat?style=flat-square&logo=telegram)](https://t.me/TelegrafJSChat)
## Introduction
Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically.
Users can interact with bots by sending them command messages in private or group chats.
These accounts serve as an interface for code running somewhere on your server.
### Features
- Full [Telegram Bot API 4.8](https://core.telegram.org/bots/api) support
- [Telegram Payment Platform](https://telegram.org/blog/payments)
- [HTML5 Games](https://core.telegram.org/bots/api#games)
- [Inline mode](https://core.telegram.org/bots/api#inline-mode)
- Incredibly fast
- [now](https://now.sh)/[Firebase](https://firebase.google.com/products/functions/)/[Glitch](https://dashing-light.glitch.me)/[Heroku](https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction)/[AWS **λ**](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html)/Whatever ready
- `http/https/fastify/Connect.js/express.js` compatible webhooks
- Easy to extend
- `TypeScript` typings
### Installation
```
$ npm install telegraf
```
or using `yarn`:
```
$ yarn add telegraf
```
### Documentation
[Telegraf developer docs](http://telegraf.js.org)
### Examples
```js
const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start((ctx) => ctx.reply('Welcome!'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on('sticker', (ctx) => ctx.reply('👍'))
bot.hears('hi', (ctx) => ctx.reply('Hey there'))
bot.launch()
```
```js
const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.command('oldschool', (ctx) => ctx.reply('Hello'))
bot.command('modern', ({ reply }) => reply('Yo'))
bot.command('hipster', Telegraf.reply('λ'))
bot.launch()
```
There's some cool [examples too](docs/examples/).
@@ -0,0 +1,205 @@
/** @format */
import * as tt from './telegram-types.d'
import { TelegrafContext } from './context'
type HearsTriggers<TContext> = string[] | string | RegExp | RegExp[] | ((value: string, ctx: TContext) => RegExpExecArray | null)
type BranchPredicate<TContext> = boolean | ((ctx: TContext) => boolean | Promise<boolean>)
export interface MiddlewareFn<TContext extends TelegrafContext> {
/*
next's parameter is in a contravariant position, and thus, trying to type it
prevents assigning `MiddlewareFn<ContextMessageUpdate>`
to `MiddlewareFn<CustomContext>`.
Middleware passing the parameter should be a separate type instead.
*/
(ctx: TContext, next: () => Promise<void>): void | Promise<unknown>
}
export interface MiddlewareObj<TContext extends TelegrafContext> {
middleware(): MiddlewareFn<TContext>
}
export type Middleware<TContext extends TelegrafContext> =
| MiddlewareFn<TContext>
| MiddlewareObj<TContext>
export declare class Composer<TContext extends TelegrafContext>
implements MiddlewareObj<TContext> {
/**
* Registers a middleware.
*/
use(...middlewares: ReadonlyArray<Middleware<TContext>>): this
/**
* Registers middleware for provided update type.
*/
on(
updateTypes:
| tt.UpdateType
| tt.UpdateType[]
| tt.MessageSubTypes
| tt.MessageSubTypes[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Return the middleware created by this Composer
*/
middleware(): MiddlewareFn<TContext>
/**
* Registers middleware for handling text messages.
*/
hears(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling callbackQuery data with regular expressions
*/
action(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling specified commands.
*/
command(
command: string | string[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling callback_data actions with game query.
*/
gameQuery(...middlewares: ReadonlyArray<Middleware<TContext>>): this
/**
* Registers middleware for handling /start command.
*/
start(...middlewares: ReadonlyArray<Middleware<TContext>>): this
/**
* Registers middleware for handling /help command.
*/
help(...middlewares: ReadonlyArray<Middleware<TContext>>): this
constructor(...middlewares: ReadonlyArray<Middleware<TContext>>)
static unwrap<TContext extends TelegrafContext>(
middleware: Middleware<TContext>
): MiddlewareFn<TContext>
/**
* Compose middlewares returning a fully valid middleware comprised of all those which are passed.
*/
static compose<TContext extends TelegrafContext>(
middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling provided update types.
*/
static mount<TContext extends TelegrafContext>(
updateTypes: tt.UpdateType | tt.UpdateType[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling matching text messages.
*/
static hears<TContext extends TelegrafContext>(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling matching callback queries.
*/
static action<TContext extends TelegrafContext>(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates pass thru middleware.
*/
static passThru(): MiddlewareFn<TelegrafContext>
/**
* Generates safe version of pass thru middleware.
*/
static safePassThru(): MiddlewareFn<TelegrafContext>
/**
* Generates optional middleware.
* @param middleware middleware to run if the predicate returns true
*/
static optional<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates filter middleware.
*/
static filter<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>
): MiddlewareFn<TContext>
/**
* Generates drop middleware.
*/
static drop<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>
): Middleware<TContext>
/**
* @param trueMiddleware middleware to run if the predicate returns true
* @param falseMiddleware middleware to run if the predicate returns false
*/
static branch<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>,
trueMiddleware: Middleware<TContext>,
falseMiddleware: Middleware<TContext>
): MiddlewareFn<TContext>
static reply(
text: string,
extra?: tt.ExtraReplyMessage
): MiddlewareFn<TelegrafContext>
/**
* Generates middleware that runs in the background.
*/
static fork<TContext extends TelegrafContext>(
middleware: Middleware<TContext>
): MiddlewareFn<TContext>
static log(logFn?: (s: string) => void): MiddlewareFn<TelegrafContext>
/**
* Generates middleware running only in given chat types.
*/
static chatType<TContext extends TelegrafContext>(
type: tt.ChatType | tt.ChatType[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware running only in private chats.
*/
static privateChat<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware running only in groups and supergroups.
*/
static groupChat<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
}
@@ -0,0 +1,524 @@
/** @format */
import * as tt from './telegram-types'
import { Telegram } from './telegram'
export declare class TelegrafContext {
updateType: tt.UpdateType
updateSubTypes: tt.MessageSubTypes[]
update: tt.Update
tg: Telegram
botInfo?: tt.User
telegram: Telegram
callbackQuery?: tt.CallbackQuery
channelPost?: tt.Message
chat?: tt.Chat
chosenInlineResult?: tt.ChosenInlineResult
editedChannelPost?: tt.Message
editedMessage?: tt.Message
from?: tt.User
inlineQuery?: tt.InlineQuery
match?: RegExpExecArray | null
me?: string
message?: tt.IncomingMessage
poll?: tt.Poll
pollAnswer?: tt.PollAnswer
preCheckoutQuery?: tt.PreCheckoutQuery
shippingQuery?: tt.ShippingQuery
constructor(
update: tt.Update,
telegram: Telegram,
options?: { username?: string }
)
/**
* Use this method to add a new sticker to a set created by the bot
* @param ownerId User identifier of sticker set owner
* @param name Sticker set name
* @param stickerData Sticker object
* @param isMasks https://github.com/telegraf/telegraf/blob/87882c42f6c2496576fdb57ca622690205c3e35e/lib/telegram.js#L304
* @returns Returns True on success.
*/
addStickerToSet(
ownerId: number,
name: string,
stickerData: tt.StickerData,
isMasks: boolean
): Promise<boolean>
/**
* Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set
* @param ownerId User identifier of created sticker set owner
* @param name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters.
* @param title Sticker set title, 1-64 characters
* @param stickerData Sticker object
* @returns Returns True on success.
*/
createNewStickerSet(
ownerId: number,
name: string,
title: string,
stickerData: tt.StickerData
): Promise<boolean>
/**
* Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* @returns True on success
*/
deleteChatPhoto(): Promise<boolean>
/**
* Use this method to delete a sticker from a set created by the bot.
* @param sticker File identifier of the sticker
* @returns Returns True on success
*/
deleteStickerFromSet(sticker: string): Promise<boolean>
/**
* Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* @returns exported invite link as String on success.
*/
exportChatInviteLink(): Promise<string>
/**
* Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.)
* @returns a Chat object on success.
*/
getChat(): Promise<tt.Chat>
/**
* Use this method to get a list of administrators in a chat.
* @returns On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
*/
getChatAdministrators(): Promise<Array<tt.ChatMember>>
/**
* Use this method to get information about a member of a chat.
* @param userId Unique identifier of the target user
* @returns a ChatMember object on success
*/
getChatMember(userId: number): Promise<tt.ChatMember>
/**
* Use this method to get the number of members in a chat
* @returns Number on success
*/
getChatMembersCount(): Promise<number>
/**
* Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success.
* @param user_id Unique identifier of the target user
* @param extra Additional params for restrict chat member
* @returns True on success
*/
restrictChatMember(
userId: number,
extra?: tt.ExtraRestrictChatMember
): Promise<boolean>
/**
* Use this method to get a sticker set
* @param setName Name of the sticker set
* @returns On success, a StickerSet object is returned.
*/
getStickerSet(setName: string): Promise<tt.StickerSet>
/**
* Use this method for your bot to leave a group, supergroup or channel
* @returns True on success
*/
leaveChat(): Promise<boolean>
/**
* Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param messageId Identifier of a message to pin
* @param extra Pass `{ disable_notification: true }`, if it is not necessary to send a notification to all group members about the new pinned message
* @returns True on success
*/
pinChatMessage(
messageId: number,
extra?: { disable_notification?: boolean }
): Promise<boolean>
/**
* Use this method to unpin a message in a group, a supergroup, or a channel.
* @returns True on success
*/
unpinChatMessage(): Promise<boolean>
/**
* Use this method to reply on messages in the same chat.
* @param text Text of the message to be sent
* @param extra SendMessage additional params
* @returns sent Message if Success
*/
reply(text: string, extra?: tt.ExtraReplyMessage): Promise<tt.Message>
/**
* Use this method to send audio files to the same chat, if you want Telegram clients to display them in the music player.
* Your audio must be in the .mp3 format.
* Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
* @param audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data
* @param extra Audio extra parameters
* @returns On success, the sent Message is returned.
*/
replyWithAudio(
audio: tt.InputFile,
extra?: tt.ExtraAudio
): Promise<tt.MessageAudio>
/**
* Use this method when you need to tell the user that something is happening on the bot's side.
* The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
* Choose one, depending on what the user is about to receive:
* - typing for text messages,
* - upload_photo for photos,
* - record_video or upload_video for videos,
* - record_audio or upload_audio for audio files,
* - upload_document for general files,
* - find_location for location data,
* - record_video_note or upload_video_note for video notes.
* @param action Type of action to broadcast.
* @returns True on success
*/
replyWithChatAction(action: tt.ChatAction): Promise<boolean>
/**
* Use this method to send general files. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
* @param document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params for send document
* @returns a Message on success
*/
replyWithDocument(
document: tt.InputFile,
extra?: tt.ExtraDocument
): Promise<tt.MessageDocument>
/**
* Use this method to send a game
* @param gameShortName Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather.
* @param extra Additional params for send game
* @returns a Message on success
*/
replyWithGame(
gameShortName: string,
extra?: tt.ExtraGame
): Promise<tt.MessageGame>
/**
* The Bot API supports basic formatting for messages
* @param html You can use bold and italic text, as well as inline links and pre-formatted code in your bots' messages.
* @param extra Additional params to send message
* @returns a Message on success
*/
replyWithHTML(html: string, extra?: tt.ExtraReplyMessage): Promise<tt.Message>
/**
* Use this method to send invoices
* @param invoice Object with new invoice params
* @param extra Additional params for send invoice
* @returns a Message on success
*/
replyWithInvoice(
invoice: tt.NewInvoiceParameters,
extra?: tt.ExtraInvoice
): Promise<tt.MessageInvoice>
/**
* Use this method to send point on the map
* @param latitude Latitude of location
* @param longitude Longitude of location
* @param extra Additional params for send location
* @returns a Message on success
*/
replyWithLocation(
latitude: number,
longitude: number,
extra?: tt.ExtraLocation
): Promise<tt.MessageLocation>
/**
* The Bot API supports basic formatting for messages
* @param markdown You can use bold and italic text, as well as inline links and pre-formatted code in your bots' messages.
* @param extra Additional params to send message
* @returns a Message on success
*/
replyWithMarkdown(
markdown: string,
extra?: tt.ExtraReplyMessage
): Promise<tt.Message>
/**
* Use this method to send photos
* @param photo Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data
* @param extra Additional params to send photo
* @returns a Message on success
*/
replyWithPhoto(
photo: tt.InputFile,
extra?: tt.ExtraPhoto
): Promise<tt.MessagePhoto>
/**
* Use this method to send a group of photos or videos as an album
* @param media A JSON-serialized array describing photos and videos to be sent, must include 2–10 items
* @param extra Additional params to send media group
* @returns On success, an array of the sent Messages is returned
*/
replyWithMediaGroup(
media: tt.MessageMedia[],
extra?: tt.ExtraMediaGroup
): Promise<Array<tt.Message>>
/**
* Use this method to send a native poll.
* @param question Poll question, 1-255 characters
* @param options A JSON-serialized list of answer options, 2-10 strings 1-100 characters each
* @param extra Additional params to send poll
* @returns On success, the sent Message is returned.
*/
replyWithPoll(
question: string,
options: string[],
extra: tt.ExtraPoll
): Promise<tt.MessagePoll>
/**
* Use this method to send a native quiz.
* @param question Poll question, 1-255 characters
* @param options A JSON-serialized list of answer options, 2-10 strings 1-100 characters each
* @param extra Additional params to send quiz
* @returns On success, the sent Message is returned.
*/
replyWithQuiz(
question: string,
options: string[],
extra: tt.ExtraPoll
): Promise<tt.MessagePoll>
/**
* Use this method to send a native quiz.
* @param messageId Identifier of the original message with the poll
* @param extra Additional params to stop poll
* @returns On success, the stopped Poll with the final results is returned.
*/
stopPoll(messageId: number, extra: tt.ExtraStopPoll): Promise<tt.Poll>
/**
* Use this method to send .webp stickers
* @param sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params to send sticker
* @returns a Message on success
*/
replyWithSticker(
sticker: tt.InputFile,
extra?: tt.ExtraSticker
): Promise<tt.MessageSticker>
/**
* Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document)
* Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
* @param video video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data
* @param extra Additional params to send video
* @returns a Message on success
*/
replyWithVideo(
video: tt.InputFile,
extra?: tt.ExtraVideo
): Promise<tt.MessageVideo>
/**
* Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
* @param voice Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params to send voice
* @returns a Message on success
*/
replyWithVoice(
voice: tt.InputFile,
extra?: tt.ExtraVoice
): Promise<tt.MessageVoice>
/**
* Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent Message is returned. (Yes, we're aware of the “proper” singular of die. But it's awkward, and we decided to help it change. One dice at a time!)
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param extra Additional params to send dice
* @returns a Message on success
*/
replyWithDice(extra?: tt.ExtraDice): Promise<tt.MessageDice>
// ------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------ //
answerCbQuery(
text?: string,
showAlert?: boolean,
extra?: object
): Promise<boolean>
/**
* Use this method to send answers to game query.
* @param url Notification text
*/
answerGameQuery(url: string): Promise<boolean>
/**
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
* @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
* @param shippingOptions Required if ok is True. A JSON-serialized array of available shipping options.
* @param errorMessage Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
*/
answerShippingQuery(
ok: boolean,
shippingOptions: tt.ShippingOption[],
errorMessage: string
): Promise<boolean>
/**
* Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
* @param ok Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
* @param errorMessage Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
*/
answerPreCheckoutQuery(ok: boolean, errorMessage?: string): Promise<boolean>
/**
* Use this method to send answers to an inline query.
* No more than 50 results per query are allowed.
* @returns On success, True is returned.
* @param results Array of results for the inline query
* @param extra Extra optional parameters
*/
answerInlineQuery(
results: tt.InlineQueryResult[],
extra?: tt.ExtraAnswerInlineQuery
): Promise<boolean>
/**
* Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
* @returns On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param text New text of the message
* @param extra Extra params
*/
editMessageText(
text: string,
extra?: tt.ExtraEditMessage
): Promise<tt.Message | boolean>
/**
* Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param caption New caption of the message
* @param markup Markup of inline keyboard
*/
editMessageCaption(
caption?: string,
markup?: tt.InlineKeyboardMarkup
): Promise<tt.Message | boolean>
/**
* Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
* @returns On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param markup Markup of inline keyboard
*/
editMessageReplyMarkup(
markup?: tt.InlineKeyboardMarkup
): Promise<tt.Message | boolean>
/**
* Use this method to edit animation, audio, document, photo, or video messages.
* @returns On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
* @param media New media of message
* @param markup Markup of inline keyboard
*/
editMessageMedia(
media: tt.MessageMedia,
extra?: tt.ExtraEditMessage
): Promise<tt.Message | boolean>
/**
* Use this method to edit live location messages.
* @returns On success, if the edited message was sent by the bot, the edited message is returned, otherwise True is returned.
* @param lat New latitude
* @param lon New longitude
*/
editMessageLiveLocation(
lat: number,
lon: number,
extra?: tt.ExtraLocation
): Promise<tt.MessageLocation | boolean>
/**
* Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param userId Unique identifier of the target user
* @param untilDate Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever
* @returns True on success
*/
kickChatMember(userId: number, untilDate?: number): Promise<boolean>
/**
* Use this method to unban a user from a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param userId Unique identifier of the target user
* @returns True on success
*/
unbanChatMember(userId: number): Promise<boolean>
/**
* Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param userId Unique identifier of the target user
* @returns True on success
*/
promoteChatMember(
userId: number,
extra: tt.ExtraPromoteChatMember
): Promise<boolean>
/**
* Use this method to stop updating a live location message before live_period expires.
* @returns On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned.
* @param extra Extra params
*/
stopMessageLiveLocation(
extra?: tt.ExtraLocation
): Promise<tt.MessageLocation | boolean>
/**
* Use this method to delete a message, including service messages, with the following limitations:
* - A message can only be deleted if it was sent less than 48 hours ago.
* - Bots can delete outgoing messages in groups and supergroups.
* - Bots granted can_post_messages permissions can delete outgoing messages in channels.
* - If the bot is an administrator of a group, it can delete any message there.
* - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
* @returns Returns True on success.
*/
deleteMessage(messageId?: number): Promise<boolean>
/**
* Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times)
* https://core.telegram.org/bots/api#sending-files
* @param ownerId User identifier of sticker file owner
* @param stickerFile Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.
* @returns Returns the uploaded File on success
*/
uploadStickerFile(
ownerId: number,
stickerFile: tt.InputFile
): Promise<tt.File>
/**
* Use this method to move a sticker in a set created by the bot to a specific position
* @param sticker File identifier of the sticker
* @param position New sticker position in the set, zero-based
* @returns Returns True on success.
*/
setStickerPositionInSet(sticker: string, position: number): Promise<boolean>
/**
* Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param title New chat title, 1-255 characters
* @returns True on success
*/
setChatTitle(title: string): Promise<boolean>
}
@@ -0,0 +1,39 @@
/** @format */
import * as tt from './telegram-types.d'
export declare class Extra {
constructor(opts: object)
load(opts: object): this
inReplyTo(messageId: string | number): this
notifications(value?: boolean): this
webPreview(value?: boolean): this
markup(markup: any): tt.ExtraEditMessage & this
HTML(value?: boolean): this
markdown(value?: boolean): this
caption(caption: string): this
static load(opts: object): Extra
static inReplyTo(messageId: string | number): Extra
static notifications(value?: boolean): Extra
static webPreview(value?: boolean): Extra
static markup(markup: any): tt.ExtraEditMessage
static HTML(value?: boolean): Extra
static markdown(value?: boolean): Extra
static caption(caption: string): Extra
}
@@ -0,0 +1,11 @@
/** @format */
export { BaseScene, Stage } from './stage'
export { Composer, Middleware } from './composer'
export { Extra } from './extra'
export { Markup } from './markup'
export { Router } from './router'
export { session } from './session'
export { Telegraf, Telegraf as default } from './telegraf'
export { TelegrafContext as Context } from './context'
export { Telegram } from './telegram'
@@ -0,0 +1,225 @@
/** @format */
import * as tt from './telegram-types.d'
export interface Button {
text: string
hide: boolean
}
export interface ContactRequestButton {
text: string
hide: boolean
request_contact: boolean
}
export interface LocationRequestButton {
text: string
hide: boolean
request_location: boolean
}
type PollType = 'poll' | 'quiz'
export interface PollRequestButton {
text: string
request_poll: { type?: PollType }
}
export type KeyboardButton =
| Button
| ContactRequestButton
| LocationRequestButton
| PollRequestButton
| string
export interface UrlButton {
url: string
text: string
hide?: boolean
}
export interface CallbackButton {
text: string
hide: boolean
callback_data: string
}
export interface SwitchToChatButton {
text: string
hide: boolean
switch_inline_query: string
}
export interface SwitchToCurrentChatButton {
text: string
hide: boolean
switch_inline_query_current_chat: string
}
export interface GameButton {
text: string
hide: boolean
callback_game: tt.CallbackGame
}
export interface PayButton {
pay: boolean
text: string
hide: boolean
}
export interface LoginUrl {
url: string
forward_text?: string
bot_username?: string
request_write_access?: boolean
}
export interface LoginButton {
text: string
login_url: LoginUrl
hide: boolean
}
export type InlineKeyboardButton =
| UrlButton
| CallbackButton
| SwitchToChatButton
| SwitchToCurrentChatButton
| GameButton
| PayButton
| LoginButton
export interface KeyboardOptions<TBtn> {
columns?: number
wrap?(btn: TBtn, index: number, currentRow: TBtn[]): boolean
}
export declare class Markup {
forceReply(value?: boolean): this
removeKeyboard(value?: boolean): this
selective(value?: boolean): this
extra(options?: tt.ExtraReplyMessage): tt.ExtraReplyMessage
keyboard(
buttons: KeyboardButton[] | KeyboardButton[][],
options?: KeyboardOptions<KeyboardButton>
): this & tt.ReplyKeyboardMarkup
resize(value?: boolean): this
oneTime(value?: boolean): this
inlineKeyboard(
buttons: InlineKeyboardButton[] | InlineKeyboardButton[][],
options: KeyboardOptions<InlineKeyboardButton>
): this & tt.InlineKeyboardMarkup
button(text: string, hide?: boolean): Button
contactRequestButton(text: string, hide?: boolean): ContactRequestButton
locationRequestButton(text: string, hide?: boolean): LocationRequestButton
urlButton(text: string, url: string, hide?: boolean): UrlButton
callbackButton(text: string, data: string, hide?: boolean): CallbackButton
switchToChatButton(
text: string,
value: string,
hide?: boolean
): SwitchToChatButton
switchToCurrentChatButton(
text: string,
value: string,
hide?: boolean
): SwitchToCurrentChatButton
gameButton(text: string, hide?: boolean): GameButton
payButton(text: string, hide?: boolean): PayButton
loginButton(
text: string,
url: string,
opts: Omit<LoginUrl, 'url'>,
hide?: boolean
): LoginButton
static removeKeyboard(value?: string): Markup
static forceReply(value?: string): Markup
static keyboard(
buttons: KeyboardButton[] | KeyboardButton[][],
options?: KeyboardOptions<KeyboardButton>
): Markup & tt.ReplyKeyboardMarkup
static inlineKeyboard(
buttons: InlineKeyboardButton[] | InlineKeyboardButton[][],
options?: KeyboardOptions<InlineKeyboardButton>
): Markup & tt.InlineKeyboardMarkup
static resize(value?: boolean): Markup
static selective(value?: boolean): Markup
static oneTime(value?: boolean): Markup
static button(text: string, hide?: boolean): Button
static contactRequestButton(
text: string,
hide?: boolean
): ContactRequestButton
static locationRequestButton(
text: string,
hide?: boolean
): LocationRequestButton
static pollRequestButton(
text: string,
type: PollType,
hide?: boolean
): PollRequestButton
static urlButton(text: string, url: string, hide?: boolean): UrlButton
static callbackButton(
text: string,
data: string,
hide?: boolean
): CallbackButton
static switchToChatButton(
text: string,
value: string,
hide?: boolean
): SwitchToChatButton
static switchToCurrentChatButton(
text: string,
value: string,
hide?: boolean
): SwitchToCurrentChatButton
static gameButton(text: string, hide?: boolean): GameButton
static payButton(text: string, hide?: boolean): PayButton
static loginButton(
text: string,
url: string,
opts: Omit<LoginUrl, 'url'>,
hide?: boolean
): LoginButton
static formatHTML(text: string, entities: Array<tt.MessageEntity>): string
}
@@ -0,0 +1,37 @@
/** @format */
import { MiddlewareObj, Middleware, MiddlewareFn } from './composer'
import { TelegrafContext } from './context'
type TRoute = string
type MaybePromise<T> = T | Promise<T>
export type RouteFn<TContext extends TelegrafContext> = (
ctx: TContext
) => MaybePromise<{
route?: TRoute
} | null>
type HandlersMap<TContext extends TelegrafContext> = Map<
TRoute,
Middleware<TContext>
>
declare class Router<TContext extends TelegrafContext>
implements MiddlewareObj<TContext> {
routeFn: RouteFn<TContext>
handlers: HandlersMap<TContext>
otherwiseHandler: Middleware<TContext>
constructor(routeFn: RouteFn<TContext>, handlers?: HandlersMap<TContext>)
on(
route: TRoute,
fn: Middleware<TContext>,
...fns: Middleware<TContext>[]
): this
otherwise(fn: Middleware<TContext>, ...fns: Middleware<TContext>[]): this
middleware(): MiddlewareFn<TContext>
}
@@ -0,0 +1,11 @@
/** @format */
import { TelegrafContext } from './context'
import { Middleware } from './composer'
export declare function session<TContext extends TelegrafContext>(opts?: {
property?: string
store?: Map<string, any>
getSessionKey?: (ctx: TContext) => string
ttl?: number
}): Middleware<TContext>
@@ -0,0 +1,100 @@
/** @format */
import { TelegrafContext } from './context'
import { Middleware, Composer, MiddlewareFn } from './composer'
export interface SceneContextOptions {
sessionName: string
default?: string
ttl?: number
}
export interface SceneContext<TContext extends SceneContextMessageUpdate> {
ctx: TContext
scenes: Map<string, Scene<TContext>>
options: SceneContextOptions
readonly session: {
state?: object
current?: string
expires?: number
}
state: object
readonly current: BaseScene<TContext> | null
reset: () => void
enter: (
sceneId: string,
initialState?: object,
silent?: boolean
) => Promise<any>
reenter: () => Promise<any>
leave: () => Promise<any>
}
export interface SceneContextMessageUpdate extends TelegrafContext {
scene: SceneContext<this>
}
export interface BaseSceneOptions<TContext extends SceneContextMessageUpdate> {
handlers: Middleware<TContext>[]
enterHandlers: Middleware<TContext>[]
leaveHandlers: Middleware<TContext>[]
ttl?: number
}
export class BaseScene<
TContext extends SceneContextMessageUpdate
> extends Composer<TContext> {
constructor(id: string, options?: Partial<BaseSceneOptions<TContext>>)
id: string
options: BaseSceneOptions<TContext>
enterHandler: Middleware<TContext>
leaveHandler: Middleware<TContext>
ttl?: number
enter: (...fns: Middleware<TContext>[]) => this
leave: (...fns: Middleware<TContext>[]) => this
enterMiddleware: () => Middleware<TContext>
leaveMiddleware: () => Middleware<TContext>
}
export type Scene<TContext extends SceneContextMessageUpdate> = BaseScene<
TContext
>
export type StageOptions = SceneContextOptions
export class Stage<TContext extends SceneContextMessageUpdate> extends Composer<
TContext
> {
constructor(scenes: Scene<TContext>[], options?: Partial<StageOptions>)
register: (...scenes: Scene<TContext>[]) => this
middleware: () => MiddlewareFn<TContext>
static enter: (
sceneId: string,
initialState?: object,
silent?: boolean
) => Middleware<SceneContextMessageUpdate>
static reenter: () => Middleware<SceneContextMessageUpdate>
static leave: () => Middleware<SceneContextMessageUpdate>
}
@@ -0,0 +1,217 @@
/** @format */
/// <reference types="node" />
import { IncomingMessage, ServerResponse } from 'http'
import * as https from 'https'
import * as http from 'http'
import { TlsOptions } from 'tls'
import * as tt from './telegram-types.d'
import { TelegrafContext } from './context'
import { Composer } from './composer'
import { Telegram, TelegramOptions } from './telegram'
export interface TelegrafOptions {
/**
* Telegram options
*/
telegram?: TelegramOptions
/**
* Bot username
*/
username?: string
}
export interface LaunchPollingOptions {
/**
* Poll timeout in seconds
*/
timeout?: number
/**
* Limits the number of updates to be retrieved
*/
limit?: number
/**
* List the types of updates you want your bot to receive
*/
allowedUpdates?: tt.UpdateType[] | tt.UpdateType | null
/**
* Polling stop callback
*/
stopCallback?: () => void | null
}
export interface LaunchWebhookOptions {
/**
* Public domain for webhook. If domain is not specified, hookPath should contain a domain name as well (not only path component).
*/
domain?: string
/**
* Webhook url path; will be automatically generated if not specified
*/
hookPath?: string
/**
* The port to listen on for Telegram calls. If port is omitted or is 0, the operating system will assign an arbitrary unused port.
*/
port?: number
/**
* The host to listen on for Telegram calls. If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.
*/
host?: string
/**
* TLS server options. Pass null (or omit) to use http.
*/
tlsOptions?: TlsOptions | null
/**
* A callback function suitable for the http[s].createServer() method to handle a request.
*/
cb?: (req: IncomingMessage, res: ServerResponse) => void
}
export declare class Telegraf<
TContext extends TelegrafContext
> extends Composer<TContext> {
/**
* Use this property to get/set bot token
*/
token: string
/**
* Use this property to control reply via webhook feature.
*/
webhookReply: boolean
/**
* Use this property to get telegram instance
*/
telegram: Telegram
/**
* Use this property to extend context and support your custom interface
*/
context: TContext
/**
* Telegraf options
*/
options: TOptions
/**
* Initialize new Telegraf app.
* @param token Bot token
* @param options options
* @example
* new Telegraf(token, options)
*/
constructor(token: string, options?: TelegrafOptions)
/**
* Launch bot in long-polling or webhook mode.
*
* @param options [See reference to get more]{@link https://telegraf.js.org/#/?id=launch}
*/
launch(options?: {
polling?: LaunchPollingOptions
webhook?: LaunchWebhookOptions
}): Promise<void>
/**
* Start poll updates.
* @param timeout Poll timeout in seconds
* @param limit Limits the number of updates to be retrieved
* @param allowedUpdates List the types of updates you want your bot to receive
* @param stopCallback Polling stop callback
*/
startPolling(
timeout?: number,
limit?: number,
allowedUpdates?: tt.UpdateType[] | tt.UpdateType | null,
stopCallback?: () => void | null
): Telegraf<TContext>
/**
* Start listening @ https://host:port/hookPath for Telegram calls.
* @param hookPath Webhook url path (see Telegraf.setWebhook)
* @param tlsOptions TLS server options. Pass null to use http
* @param port Port number
* @param host Hostname
* @param cb A callback function suitable for the http[s].createServer() method to handle a request.
*/
startWebhook(
hookPath: string,
tlsOptions?: TlsOptions | null,
port?: number,
host?: string,
cb?: (req: IncomingMessage, res: ServerResponse) => void
): Telegraf<TContext>
/**
* Stop Webhook and polling
*/
stop(cb?: () => void): Promise<void>
/**
* Return a callback function suitable for the http[s].createServer() method to handle a request.
* You may also use this callback function to mount your telegraf app in a Koa/Connect/Express app.
* @param hookPath Webhook url path (see Telegraf.setWebhook)
*/
webhookCallback(
hookPath: string
): (req: IncomingMessage, res: ServerResponse) => void
handleUpdates(updates: tt.Update[]): Promise<unknown[]>
/**
* Handle raw Telegram update. In case you use centralized webhook server, queue, etc.
*/
handleUpdate(
update: tt.Update,
webhookResponse?: ServerResponse
): Promise<unknown>
private fetchUpdates(): void
catch(logFn?: Function): void
}
export interface TOptions {
/**
* Telegram options
*/
telegram?: {
/**
* https.Agent or http.Agent instance, allows custom proxy, certificate, keep alive, etc.
*/
agent: https.Agent | http.Agent
/**
* Reply via webhook
*/
webhookReply: boolean
}
/**
* Bot username
*/
username?: string
/**
* Handle `channel_post` updates as messages
*/
channelMode?: boolean
retryAfter?: number
handlerTimeout?: number
}
@@ -0,0 +1,803 @@
import * as TT from "telegram-typings";
export * from "telegram-typings";
export type ParseMode = 'Markdown' | 'MarkdownV2' | 'HTML'
export type ChatAction =
'typing' |
'upload_photo' |
'record_video' |
'upload_video' |
'record_audio' |
'upload_audio' |
'upload_document' |
'find_location' |
'record_video_note' |
'upload_video_note'
export type ChatType =
'private' |
'group' |
'supergroup' |
'channel'
export type UpdateType =
'callback_query' |
'channel_post' |
'chosen_inline_result' |
'edited_channel_post' |
'edited_message' |
'inline_query' |
'message' |
'pre_checkout_query' |
'shipping_query' |
'poll' |
'poll_answer'
export type MessageSubTypes =
'voice' |
'video_note' |
'video' |
'venue' |
'text' |
'supergroup_chat_created' |
'successful_payment' |
'sticker' |
'pinned_message' |
'photo' |
'new_chat_title' |
'new_chat_photo' |
'new_chat_members' |
'migrate_to_chat_id' |
'migrate_from_chat_id' |
'location' |
'left_chat_member' |
'invoice' |
'group_chat_created' |
'game' |
'document' |
'delete_chat_photo' |
'contact' |
'channel_chat_created' |
'audio' |
'passport_data' |
'connected_website' |
'animation'
export type InlineQueryResult =
TT.InlineQueryResultCachedAudio |
TT.InlineQueryResultCachedDocument |
TT.InlineQueryResultCachedGif |
TT.InlineQueryResultCachedMpeg4Gif |
TT.InlineQueryResultCachedPhoto |
TT.InlineQueryResultCachedSticker |
TT.InlineQueryResultCachedVideo |
TT.InlineQueryResultCachedVoice |
TT.InlineQueryResultArticle |
TT.InlineQueryResultAudio |
TT.InlineQueryResultContact |
TT.InlineQueryResultGame |
TT.InlineQueryResultDocument |
TT.InlineQueryResultGif |
TT.InlineQueryResultLocation |
TT.InlineQueryResultMpeg4Gif |
TT.InlineQueryResultPhoto |
TT.InlineQueryResultVenue |
TT.InlineQueryResultVideo |
TT.InlineQueryResultVoice
export type MessageMedia =
InputMediaPhoto |
InputMediaVideo |
InputMediaAnimation |
InputMediaAudio |
InputMediaDocument
export interface InputMediaPhoto {
type: string
media: InputFile
caption?: string
parse_mode?: string
}
export interface InputMediaVideo {
type: string
media: InputFile
thumb?: string | InputFile
caption?: string
parse_mode?: string
width?: number
height?: number
duration?: number
supports_streaming?: boolean
}
export interface InputMediaAnimation {
type: string
media: InputFile
thumb?: string | InputFile
caption?: string
parse_mode?: string
width?: number
height?: number
duration?: number
supports_streaming?: boolean
}
export interface InputMediaAudio {
type: string
media: InputFile
thumb?: string | InputFile
caption?: string
parse_mode?: string
performer?: string
title?: string
duration?: number
supports_streaming?: boolean
}
export interface InputMediaDocument {
type: string
media: InputFile
thumb?: string | InputFile
caption?: string
parse_mode?: string
}
export interface StickerData {
png_sticker: string | Buffer
emojis: string
mask_position: TT.MaskPosition
}
type FileId = string
export interface InputFileByPath {
source: string
}
export interface InputFileByReadableStream {
source: NodeJS.ReadableStream
}
export interface InputFileByBuffer {
source: Buffer
}
export interface InputFileByURL {
url: string
filename: string
}
export type InputFile =
FileId |
InputFileByPath |
InputFileByReadableStream |
InputFileByBuffer |
InputFileByURL
/**
* Sending video notes by a URL is currently unsupported
*/
export type InputFileVideoNote = Exclude<InputFile, InputFileByURL>
export interface ChatPermissions {
/** True, if the user is allowed to send text messages, contacts, locations and venues */
can_send_messages?: boolean
/** True, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages */
can_send_media_messages?: boolean
/** True, if the user is allowed to send polls, implies can_send_messages */
can_send_polls?: boolean
/** True, if the user is allowed to send animations, games, stickers and use inline bots, implies can_send_media_messages */
can_send_other_messages?: boolean
/** True, if the user is allowed to add web page previews to their messages, implies can_send_media_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
}
export interface ExtraRestrictChatMember {
/** New user permissions */
permissions: ChatPermissions
/** Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever */
until_date?: number
}
export interface ExtraPromoteChatMember {
/** Pass True, if the administrator can change chat title, photo and other settings */
can_change_info?: boolean
/** Pass True, if the administrator can create channel posts, channels only */
can_post_messages?: boolean
/** Pass True, if the administrator can edit messages of other users and can pin messages, channels only */
can_edit_messages?: boolean
/** Pass True, if the administrator can delete messages of other users */
can_delete_messages?: boolean
/** Pass True, if the administrator can invite new users to the chat */
can_invite_users?: boolean
/** Pass True, if the administrator can restrict, ban or unban chat members */
can_restrict_members?: boolean
/** Pass True, if the administrator can pin messages, supergroups only */
can_pin_messages?: boolean
/** Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him) */
can_promote_members?: boolean
}
export interface ExtraReplyMessage {
/**
* Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
*/
parse_mode?: ParseMode
/**
* Disables link previews for links in this message
*/
disable_web_page_preview?: boolean
/**
* Sends the message silently. Users will receive a notification with no sound.
*/
disable_notification?: boolean
/**
* If the message is a reply, ID of the original message
*/
reply_to_message_id?: number
/**
* Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
*/
reply_markup?: TT.InlineKeyboardMarkup | TT.ReplyKeyboardMarkup | TT.ReplyKeyboardRemove | TT.ForceReply
}
export interface ExtraEditMessage extends ExtraReplyMessage {
// no specified properties
}
export interface ExtraAudio extends ExtraReplyMessage {
/**
* Audio caption, 0-1024 characters
*/
caption?: string
/**
* Duration of the audio in seconds
*/
duration?: number
/**
* Performer
*/
performer?: string
/**
* Track name
*/
title?: string
/**
* Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side.
* The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 320.
* Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file,
* so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>.
*/
thumb?: InputFile
/**
* Does not exist, see https://core.telegram.org/bots/api#sendaudio
*/
disable_web_page_preview?: never
}
export interface ExtraDocument extends ExtraReplyMessage {
/**
* Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side.
* The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 320.
* Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file,
* so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>.
*/
thumb?: InputFile
/**
* Document caption (may also be used when resending documents by file_id), 0-1024 characters
*/
caption?: string
/**
* Does not exist, see https://core.telegram.org/bots/api#senddocument
*/
disable_web_page_preview?: never
}
export interface ExtraGame extends ExtraReplyMessage {
/**
* Inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game.
*/
reply_markup?: TT.InlineKeyboardMarkup
/**
* Does not exist, see https://core.telegram.org/bots/api#sendgame
*/
disable_web_page_preview?: never
/**
* Does not exist, see https://core.telegram.org/bots/api#sendgame
*/
parse_mode?: never
}
export interface ExtraInvoice extends ExtraReplyMessage {
/**
* Inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
*/
reply_markup?: TT.InlineKeyboardMarkup
/**
* Does not exist, see https://core.telegram.org/bots/api#sendinvoice
*/
disable_web_page_preview?: never
/**
* Does not exist, see https://core.telegram.org/bots/api#sendinvoice
*/
parse_mode?: never
}
export interface ExtraLocation extends ExtraReplyMessage {
/**
* Period in seconds for which the location will be updated (should be between 60 and 86400)
*/
live_period?: number
/**
* Does not exist, see https://core.telegram.org/bots/api#sendlocation
*/
disable_web_page_preview?: never
/**
* Does not exist, see https://core.telegram.org/bots/api#sendlocation
*/
parse_mode?: never
}
export interface ExtraPhoto extends ExtraReplyMessage {
/**
* Photo caption (may also be used when resending photos by file_id), 0-1024 characters
*/
caption?: string
/**
* Does not exist, see https://core.telegram.org/bots/api#sendphoto
*/
disable_web_page_preview?: never
}
export interface ExtraMediaGroup extends ExtraReplyMessage {
/**
* Does not exist, see https://core.telegram.org/bots/api#sendmediagroup
*/
disable_web_page_preview?: never
/**
* Does not exist, see https://core.telegram.org/bots/api#sendmediagroup
*/
parse_mode?: never
/**
* Does not exist, see https://core.telegram.org/bots/api#sendmediagroup
*/
reply_markup?: never
}
export interface ExtraAnimation extends ExtraReplyMessage {
/**
* Animation caption (may also be used when resending animation by file_id), 0-200 characters
*/
caption?: string
}
export interface ExtraSticker extends ExtraReplyMessage {
/**
* Does not exist, see https://core.telegram.org/bots/api#sendsticker
*/
disable_web_page_preview?: never
/**
* Does not exist, see https://core.telegram.org/bots/api#sendsticker
*/
parse_mode?: never
}
export interface ExtraVideo extends ExtraReplyMessage {
/**
* Duration of sent video in seconds
*/
duration?: number
/**
* Video width
*/
width?: number
/**
* Video height
*/
height?: number
/**
* Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side.
* The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 320.
* Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file,
* so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>.
*/
thumb?: InputFile
/**
* Video caption (may also be used when resending videos by file_id), 0-1024 characters
*/
caption?: string
/**
* Pass True, if the uploaded video is suitable for streaming
*/
supports_streaming?: boolean
/**
* Does not exist, see https://core.telegram.org/bots/api#sendvideo
*/
disable_web_page_preview?: never
}
export interface ExtraVideoNote extends ExtraReplyMessage {
/**
* Duration of sent video in seconds
*/
duration?: number
/**
* Video width and height, i.e. diameter of the video message
*/
length?: number
/**
* Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side.
* The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 320.
* Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file,
* so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>.
*/
thumb?: InputFile
}
export interface ExtraVoice extends ExtraReplyMessage {
/**
* Voice message caption, 0-1024 characters
*/
caption?: string
/**
* Duration of the voice message in seconds
*/
duration?: number
/**
* Does not exist, see https://core.telegram.org/bots/api#sendvoice
*/
disable_web_page_preview?: never
}
export interface ExtraDice extends ExtraReplyMessage {
/**
* Does not exist, see https://core.telegram.org/bots/api#senddice
*/
parse_mode?: never
/**
* Does not exist, see https://core.telegram.org/bots/api#senddice
*/
disable_web_page_preview?: never
}
export interface ExtraPoll {
/** True, if the poll needs to be anonymous, defaults to True */
is_anonymous?: boolean
/** True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False */
allows_multiple_answers?: boolean
/** 0-based identifier of the correct answer option, required for polls in quiz mode */
correct_option_id?: number
/** Pass True, if the poll needs to be immediately closed. This can be useful for poll preview. */
is_closed?: boolean
/** Sends the message silently. Users will receive a notification with no sound. */
disable_notification?: boolean
/** If the message is a reply, ID of the original message */
reply_to_message_id?: number
/** Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. */
reply_markup?:
| TT.InlineKeyboardMarkup
| TT.ReplyKeyboardMarkup
| TT.ReplyKeyboardRemove
| TT.ForceReply
}
export interface ExtraStopPoll {
/** A JSON-serialized object for a new message inline keyboard. */
reply_markup?: TT.InlineKeyboardMarkup
}
export interface IncomingMessage extends TT.Message {
audio?: TT.Audio
entities?: TT.MessageEntity[]
caption?: string
document?: TT.Document
game?: TT.Game
photo?: TT.PhotoSize[]
animation?: TT.Animation
sticker?: TT.Sticker
video?: TT.Video
video_note?: TT.VideoNote
contact?: TT.Contact
location?: TT.Location
venue?: TT.Venue
pinned_message?: TT.Message
invoice?: TT.Invoice
successful_payment?: TT.SuccessfulPayment
dice?: Dice
}
export interface MessageAudio extends TT.Message {
audio: TT.Audio
}
export interface MessageDocument extends TT.Message {
document: TT.Document
}
export interface MessageGame extends TT.Message {
game: TT.Game
}
export interface MessageInvoice extends TT.Message {
invoice: TT.Invoice
}
export interface MessageLocation extends TT.Message {
location: TT.Location
}
export interface MessagePhoto extends TT.Message {
photo: TT.PhotoSize[]
}
export interface MessageAnimation extends TT.Message {
animation: TT.Animation
}
export interface MessageSticker extends TT.Message {
sticker: TT.Sticker
}
export interface MessageVideo extends TT.Message {
video: TT.Video
}
export interface MessageVideoNote extends TT.Message {
video_note: TT.VideoNote
}
export interface MessageVoice extends TT.Message {
voice: TT.Voice
}
export interface MessageDice extends TT.Message {
dice: Dice
}
export interface MessagePoll extends TT.Message {
poll: Poll
}
export interface NewInvoiceParameters {
/**
* 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
/**
* Payments provider token, obtained via Botfather
*/
provider_token: string
/**
* Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter
*/
start_parameter: 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: TT.LabeledPrice[]
/**
* URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
*/
photo_url?: string
/**
* Photo size
*/
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?: true
/**
* Pass True, if you require the user's phone number to complete the order
*/
need_phone_number?: true
/**
* Pass True, if you require the user's email to complete the order
*/
need_email?: true
/**
* Pass True, if you require the user's shipping address to complete the order
*/
need_shipping_address?: true
/**
* Pass True, if the final price depends on the shipping method
*/
is_flexible?: true
}
export interface ExtraAnswerInlineQuery {
/**
* The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.
*/
cache_time?: number
/**
* Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query
*/
is_personal?: boolean
/**
* Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes.
*/
next_offset?: string
/**
* If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter
*/
switch_pm_text?: string
/**
* Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.
*/
switch_pm_parameter?: 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, 3-256 characters.
*/
description: string
}
/**
* This object represents a dice with random value from 1 to 6. (Yes, we're aware of the “proper” singular of die. But it's awkward, and we decided to help it change. One dice at a time!)
*/
export interface Dice {
/**
* Value of the dice, 1-6
*/
value: number
}
export interface PollOption {
/** Option text, 1-100 characters */
text: string
/** Number of users that voted for this option */
voter_count: number
}
export interface PollAnswer {
/** Unique poll identifier */
poll_id: string
/** The user, who changed the answer to the poll */
user: TT.User
/** 0-based identifiers of answer options, chosen by the user. May be empty if the user retracted their vote. */
option_ids: number[]
}
export interface Poll {
/** Unique poll identifier */
id: string
/** Poll question, 1-255 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
}
@@ -0,0 +1,686 @@
/** @format */
import * as tt from './telegram-types.d'
import * as https from 'https'
import * as http from 'http'
export interface TelegramOptions {
/**
* https.Agent or http.Agent instance, allows custom proxy, certificate, keep alive, etc.
*/
agent?: https.Agent | http.Agent
/**
* Reply via webhook
*/
webhookReply?: boolean
/**
* Path to API. default: https://api.telegram.org
*/
apiRoot?: string
}
declare class ApiClient {
protected constructor(token: string, options: object, webhookResponse: any)
callApi(method: string, data: object): Promise<unknown>
}
export declare class Telegram extends ApiClient {
/**
* Initialize new Telegram app.
* @param token Bot token
* @param options Telegram options
*/
constructor(token: string, options?: TelegramOptions)
/**
* Use this property to control reply via webhook feature.
*/
webhookReply: boolean
/**
* Use this method to send answers to game query.
* @param callbackQueryId Query id
* @param url Notification text
*/
answerGameQuery(callbackQueryId: string, url: string): Promise<boolean>
/**
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified,
* the Bot API will send an Update with a shipping_query field to the bot.
* Use this method to reply to shipping queries.
* On success, True is returned.
* @param shippingQueryId Unique identifier for the query to be answered
* @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
* @param shippingOptions Required if ok is True. A JSON-serialized array of available shipping options.
* @param errorMessage Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
*/
answerShippingQuery(
shippingQueryId: string,
ok: boolean,
shippingOptions: Array<tt.ShippingOption>,
errorMessage: string
): Promise<boolean>
/**
* Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query.
* Use this method to respond to such pre-checkout queries. On success, True is returned.
* Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
* @param preCheckoutQueryId Unique identifier for the query to be answered
* @param ok Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
* @param errorMessage Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
*/
answerPreCheckoutQuery(
preCheckoutQueryId: string,
ok: boolean,
errorMessage?: string
): Promise<boolean>
/**
* Use this method to send answers to an inline query. On success, True is returned.
* No more than 50 results per query are allowed.
* @param inlineQueryId Unique identifier for the answered query
* @param results Array of results for the inline query
* @param extra Extra optional parameters
*/
answerInlineQuery(
inlineQueryId: string,
results: Array<tt.InlineQueryResult>,
extra?: tt.ExtraAnswerInlineQuery
): Promise<boolean>
/**
* Use this method to forward exists message.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param fromChatId Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)
* @param messageId Message identifier in the chat specified in from_chat_id
* @param extra Pass `{ disable_notification: true }`, if it is not necessary to send a notification for forwarded message
* @returns On success, the sent Message is returned.
*/
forwardMessage(
chatId: number | string,
fromChatId: number | string,
messageId: string | number,
extra?: { disable_notification?: boolean }
): Promise<tt.Message>
/**
* Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param chatId Required if inlineMessageId is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param messageId Required if inlineMessageId is not specified. Identifier of the sent message
* @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message
* @param text New text of the message
* @param extra Extra params
*/
editMessageText(
chatId: number | string | void,
messageId: number | void,
inlineMessageId: string | void,
text: string,
extra?: tt.ExtraEditMessage
): Promise<tt.Message | boolean>
/**
* Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param chatId Required if inlineMessageId is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param messageId Required if inlineMessageId is not specified. Identifier of the sent message
* @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message
* @param caption New caption of the message
* @param markup A JSON-serialized object for an inline keyboard.
*/
editMessageCaption(
chatId?: number | string,
messageId?: number,
inlineMessageId?: string,
caption?: string,
markup?: string
): Promise<tt.Message | boolean>
/**
* Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param chatId Required if inlineMessageId is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param messageId Required if inlineMessageId is not specified. Identifier of the sent message
* @param inlineMessageId Required if chatId and messageId are not specified. Identifier of the inline message
* @param markup A JSON-serialized object for an inline keyboard.
*/
editMessageReplyMarkup(
chatId?: number | string,
messageId?: number,
inlineMessageId?: string,
markup?: string
): Promise<tt.Message | boolean>
/**
* Use this method to delete a message, including service messages, with the following limitations:
* - A message can only be deleted if it was sent less than 48 hours ago.
* - Bots can delete outgoing messages in groups and supergroups.
* - Bots granted can_post_messages permissions can delete outgoing messages in channels.
* - If the bot is an administrator of a group, it can delete any message there.
* - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param messageId Identifier of the message to delete
* @returns Returns True on success.
*/
deleteMessage(chatId: number | string, messageId: number): Promise<boolean>
/**
* Use this method to get a sticker set
* @param setName Name of the sticker set
* @returns On success, a StickerSet object is returned.
*/
getStickerSet(setName: string): Promise<tt.StickerSet>
/**
* Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times)
* https://core.telegram.org/bots/api#sending-files
* @param ownerId User identifier of sticker file owner
* @param stickerFile Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.
* @returns Returns the uploaded File on success
*/
uploadStickerFile(
ownerId: number,
stickerFile: tt.InputFile
): Promise<tt.File>
/**
* Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set
* @param ownerId User identifier of created sticker set owner
* @param name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters.
* @param title Sticker set title, 1-64 characters
* @param stickerData Sticker object
* @returns Returns True on success.
*/
createNewStickerSet(
ownerId: number,
name: string,
title: string,
stickerData: tt.StickerData
): Promise<boolean>
/**
* Use this method to add a new sticker to a set created by the bot
* @param ownerId User identifier of sticker set owner
* @param name Sticker set name
* @param stickerData Sticker object
* @param isMasks https://github.com/telegraf/telegraf/blob/87882c42f6c2496576fdb57ca622690205c3e35e/lib/telegram.js#L304
* @returns Returns True on success.
*/
addStickerToSet(
ownerId: number,
name: string,
stickerData: tt.StickerData,
isMasks: boolean
): Promise<boolean>
/**
* Use this method to move a sticker in a set created by the bot to a specific position
* @param sticker File identifier of the sticker
* @param position New sticker position in the set, zero-based
* @returns Returns True on success.
*/
setStickerPositionInSet(sticker: string, position: number): Promise<boolean>
/**
* Use this method to delete a sticker from a set created by the bot.
* @param sticker File identifier of the sticker
* @returns Returns True on success
*/
deleteStickerFromSet(sticker: string): Promise<boolean>
/**
* Use this method to send copy of exists message.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param message Received message object
* @param extra Specified params for message
* @returns On success, the sent Message is returned.
*/
sendCopy(
chatId: number | string,
message?: tt.Message,
extra?: object
): Promise<tt.Message>
/**
* Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @returns True on success
*/
deleteChatPhoto(chatId: number | string): Promise<boolean>
/**
* Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @returns exported invite link as String on success.
*/
exportChatInviteLink(chatId: number | string): Promise<string>
/**
* Use this method to get basic information about the bot
* @returns a User object on success.
*/
getMe(): Promise<tt.User>
/**
* Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.)
* @param chatId Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
* @returns a Chat object on success.
*/
getChat(chatId: number | string): Promise<tt.Chat>
/**
* Use this method to get a list of administrators in a chat.
* @param chatId Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
* @returns On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
*/
getChatAdministrators(chatId: number | string): Promise<Array<tt.ChatMember>>
/**
* Use this method to get information about a member of a chat.
* @param chatId Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
* @param userId Unique identifier of the target user
* @returns a ChatMember object on success
*/
getChatMember(chatId: string | number, userId: number): Promise<tt.ChatMember>
/**
* Use this method to get the number of members in a chat
* @param chatId Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
* @returns Number on success
*/
getChatMembersCount(chatId: string | number): Promise<number>
/**
* Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success.
* @param chatId Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
* @param user_id Unique identifier of the target user
* @param extra Additional params for restrict chat member
* @returns True on success
*/
restrictChatMember(
chatId: string | number,
userId: number,
extra?: tt.ExtraRestrictChatMember
): Promise<boolean>
/**
* Use this method for your bot to leave a group, supergroup or channel
* @param chatId Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
* @returns True on success
*/
leaveChat(chatId: number | string): Promise<boolean>
/**
* Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param chatId Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
* @param messageId Identifier of a message to pin
* @param extra Pass `{ disable_notification: true }`, if it is not necessary to send a notification to all group members about the new pinned message
* @returns True on success
*/
pinChatMessage(
chatId: number | string,
messageId: number,
extra?: { disable_notification?: boolean }
): Promise<boolean>
/**
* Use this method to unpin a message in a group, a supergroup, or a channel.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @returns True on success
*/
unpinChatMessage(chatId: number | string): Promise<boolean>
/**
* Use this method to send text messages
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param text Text of the message to be sent
* @param extra SendMessage additional params
* @returns sent Message if Success
*/
sendMessage(
chatId: number | string,
text: string,
extra?: tt.ExtraEditMessage
): Promise<tt.Message>
/**
* Use this method to send audio files, if you want Telegram clients to display them in the music player.
* Your audio must be in the .mp3 format.
* Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data
* @param extra Audio extra parameters
* @returns On success, the sent Message is returned.
*/
sendAudio(
chatId: number | string,
audio: tt.InputFile,
extra?: tt.ExtraAudio
): Promise<tt.MessageAudio>
/**
* Use this method when you need to tell the user that something is happening on the bot's side.
* The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
* Choose one, depending on what the user is about to receive:
* - typing for text messages,
* - upload_photo for photos,
* - record_video or upload_video for videos,
* - record_audio or upload_audio for audio files,
* - upload_document for general files,
* - find_location for location data,
* - record_video_note or upload_video_note for video notes.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param action Type of action to broadcast.
* @returns True on success
*/
sendChatAction(
chatId: number | string,
action: tt.ChatAction
): Promise<boolean>
/**
* Use this method to send general files. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params for send document
* @returns a Message on success
*/
sendDocument(
chatId: number | string,
document: tt.InputFile,
extra?: tt.ExtraDocument
): Promise<tt.MessageDocument>
/**
* Use this method to send a game
* @param chatId Unique identifier for the target chat
* @param gameShortName Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather.
* @param extra Additional params for send game
* @returns a Message on success
*/
sendGame(
chatId: number | string,
gameShortName: string,
extra?: tt.ExtraGame
): Promise<tt.MessageGame>
/**
* Use this method to send invoices
* @param chatId Unique identifier for the target private chat
* @param invoice Object with new invoice params
* @param extra Additional params for send invoice
* @returns a Message on success
*/
sendInvoice(
chatId: number,
invoice: tt.NewInvoiceParameters,
extra?: tt.ExtraInvoice
): Promise<tt.MessageInvoice>
/**
* Use this method to send point on the map
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param latitude Latitude of location
* @param longitude Longitude of location
* @param extra Additional params for send location
* @returns a Message on success
*/
sendLocation(
chatId: number | string,
latitude: number,
longitude: number,
extra?: tt.ExtraLocation
): Promise<tt.MessageLocation>
/**
* Use this method to send photos
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param photo Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data
* @param extra Additional params to send photo
* @returns a Message on success
*/
sendPhoto(
chatId: number | string,
photo: tt.InputFile,
extra?: tt.ExtraPhoto
): Promise<tt.MessagePhoto>
/**
* Use this method to send a group of photos or videos as an album
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param media A JSON-serialized array describing photos and videos to be sent, must include 2–10 items
* @param extra Additional params to send media group
* @returns On success, an array of the sent Messages is returned
*/
sendMediaGroup(
chatId: number | string,
media: tt.MessageMedia[],
extra?: tt.ExtraMediaGroup
): Promise<Array<tt.Message>>
/**
* Use this method to send a native poll.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param question Poll question, 1-255 characters
* @param options A JSON-serialized list of answer options, 2-10 strings 1-100 characters each
* @param extra Additional params to send poll
* @returns On success, the sent Message is returned.
*/
sendPoll(
chatId: number | string,
question: string,
options: string[],
extra: tt.ExtraPoll
): Promise<tt.MessagePoll>
/**
* Use this method to send a native quiz.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param question Poll question, 1-255 characters
* @param options A JSON-serialized list of answer options, 2-10 strings 1-100 characters each
* @param extra Additional params to send quiz
* @returns On success, the sent Message is returned.
*/
sendQuiz(
chatId: number | string,
question: string,
options: string[],
extra: tt.ExtraPoll
): Promise<tt.MessagePoll>
/**
* Use this method to send a native quiz.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param messageId Identifier of the original message with the poll
* @param extra Additional params to stop poll
* @returns On success, the stopped Poll with the final results is returned.
*/
stopPoll(
chatId: number | string,
messageId: number,
extra: tt.ExtraStopPoll
): Promise<tt.Poll>
/**
* Use this method to send .gif animations
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param animation Animation to send. Pass a file_id as String to send a GIF that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a GIF from the Internet, or upload a new GIF using multipart/form-data
* @param extra Additional params to send GIF
* @returns a Message on success
*/
sendAnimation(
chatId: number | string,
animation: tt.InputFile,
extra?: tt.ExtraAnimation
): Promise<tt.MessageAnimation>
/**
* Use this method to send .webp stickers
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params to send sticker
* @returns a Message on success
*/
sendSticker(
chatId: number | string,
sticker: tt.InputFile,
extra?: tt.ExtraSticker
): Promise<tt.MessageSticker>
/**
* Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document)
* Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param video video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data
* @param extra Additional params to send video
* @returns a Message on success
*/
sendVideo(
chatId: number | string,
video: tt.InputFile,
extra?: tt.ExtraVideo
): Promise<tt.MessageVideo>
/**
* Use this method to send video messages
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param videoNote video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. Sending video notes by a URL is currently unsupported
* @param extra Additional params to send video note
* @returns a Message on success
*/
sendVideoNote(
chatId: number | string,
videoNote: tt.InputFileVideoNote,
extra?: tt.ExtraVideoNote
): Promise<tt.MessageVideoNote>
/**
* Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param voice Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params to send voice
* @returns a Message on success
*/
sendVoice(
chatId: number | string,
voice: tt.InputFile,
extra?: tt.ExtraVoice
): Promise<tt.MessageVoice>
/**
* Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent Message is returned. (Yes, we're aware of the “proper” singular of die. But it's awkward, and we decided to help it change. One dice at a time!)
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param extra Additional params to send dice
* @returns a Message on success
*/
sendDice(
chatId: number | string,
extra?: tt.ExtraDice
): Promise<tt.MessageDice>
/**
* Use this method to specify a url and receive incoming updates via an outgoing webhook
* @param url HTTPS url to send updates to. Use an empty string to remove webhook integration
* @param cert Upload your public key certificate so that the root certificate in use can be checked
* @param maxConnections Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100
* @param allowedUpdates List the types of updates you want your bot to receive
* @returns True on success
*/
setWebhook(
url: string,
cert?: tt.InputFile,
maxConnections?: number,
allowedUpdates?: string[]
): Promise<boolean>
/**
* Use this method to delete webhook
* @returns True on success
*/
deleteWebhook(): Promise<boolean>
/**
* Use this method to get information about set webhook
* @returns a WebhookInfo on success
*/
getWebhookInfo(): Promise<tt.WebhookInfo>
/**
* Use this method to get basic info about a file and prepare it for downloading
* @param fileId Id of file to get link to
* @returns a File object on success
*/
getFile(fileId: string): Promise<tt.File>
/**
* Use this method to get link to a file by file id
* @param fileId Id of file to get link to
* @returns a String with an url to the file
*/
getFileLink(fileId: string): Promise<string>
/**
* Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param chatId Unique identifier for the target group or username of the target supergroup or channel (in the format `@channelusername`)
* @param userId Unique identifier of the target user
* @param untilDate Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever
* @returns True on success
*/
kickChatMember(
chatId: number | string,
userId: number,
untilDate?: number
): Promise<boolean>
/**
* Use this method to unban a user from a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param chatId Unique identifier for the target group or username of the target supergroup or channel (in the format @username)
* @param userId Unique identifier of the target user
* @returns True on success
*/
unbanChatMember(chatId: number | string, userId: number): Promise<boolean>
/**
* Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param userId Unique identifier of the target user
* @returns True on success
*/
promoteChatMember(
chatId: number | string,
userId: number,
extra: tt.ExtraPromoteChatMember
): Promise<boolean>
/**
* Use this method to get updates from Telegram server. Bot should be in `polling` mode
* @returns Array of updates
*/
getUpdates(): Promise<any[]>
/**
* Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param chatId Unique identifier for the target group or username of the target supergroup or channel (in the format `@channelusername`)
* @param title New chat title, 1-255 characters
* @returns True on success
*/
setChatTitle(chatId: number | string, title: string): Promise<boolean>
/**
* Use this method to get the current list of the bot's commands. Requires no parameters.
* @returns Array of BotCommand on success.
*/
getMyCommands(): Promise<tt.BotCommand[]>
/**
* Use this method to change the list of the bot's commands.
* @param commands A list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.
* @returns True on success
*/
setMyCommands(commands: tt.BotCommand[]): Promise<boolean>
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -21,7 +21,7 @@
"_resolved": "https://registry.npmjs.org/telegram-typings/-/telegram-typings-3.6.1.tgz",
"_shasum": "1288d547f8694b61f1c01c2993e295f3114d9e25",
"_spec": "telegram-typings@^3.6.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\telegraf",
"_where": "c:\\Superalgos\\Projects\\Superalgos\\TS\\Bot-Modules\\Trading-Bot\\Announcements\\node_modules\\telegraf",
"author": {
"name": "Sergey Sova",
"email": "mail@sergeysova.com",
@@ -0,0 +1,32 @@
# telegram-typings
Full types parsed from core.telegram.org/bots/api for TypeScript and Flowtype
## Installation
Just install it as your dependency and use
```bash
npm install --save telegram-typings
```
```ts
// typescript
import { User, Chat, Voice } from 'telegram-typings'
```
### Flow
```bash
# Search in flow-typed
flow-typed search telegram-typings
# if not found, copy content of ./javascript/index.js.flow to your flow-typed
wget https://raw.githubusercontent.com/sergeysova/telegram-typings/master/javascript/index.js.flow -O ./flow-typed/npm/telegram-typings_vx.x.x.js
# next use as normal module
```
```js
// flow
import type { User, Chat, Voice } from 'telegram-typings'
```
@@ -0,0 +1,57 @@
{
"requires": true,
"lockfileVersion": 1,
"dependencies": {
"debug": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz",
"integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==",
"requires": {
"ms": "2.1.2"
}
},
"minimist": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
},
"module-alias": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/module-alias/-/module-alias-2.2.2.tgz",
"integrity": "sha512-A/78XjoX2EmNvppVWEhM2oGk3x4lLxnkEA4jTbaK97QKSDjkIoOsKQlfylt/d3kKKi596Qy3NP5XrXJ6fZIC9Q=="
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node-fetch": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
"integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw=="
},
"sandwich-stream": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/sandwich-stream/-/sandwich-stream-2.0.2.tgz",
"integrity": "sha512-jLYV0DORrzY3xaz/S9ydJL6Iz7essZeAfnAavsJ+zsJGZ1MOnsS52yRjU3uF3pJa/lla7+wisp//fxOwOH8SKQ=="
},
"telegraf": {
"version": "3.38.0",
"resolved": "https://registry.npmjs.org/telegraf/-/telegraf-3.38.0.tgz",
"integrity": "sha512-va4VlrKWp64JrowFoZX/NPzzA6q38kvaIukVXOWFO1V+jR1G8+hCfgJy4TX8Z3rwLJzwaBEet1QhikHDRZWl3A==",
"requires": {
"debug": "^4.0.1",
"minimist": "^1.2.0",
"module-alias": "^2.2.2",
"node-fetch": "^2.2.0",
"sandwich-stream": "^2.0.1",
"telegram-typings": "^3.6.0"
}
},
"telegram-typings": {
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/telegram-typings/-/telegram-typings-3.6.1.tgz",
"integrity": "sha512-njVv1EAhIZnmQVLocZEADYUyqA1WIXuVcDYlsp+mXua/XB0pxx+PKtMSPeZ/EE4wPWTw9h/hA9ASTT6yQelkiw=="
}
}
}
@@ -1,4 +1,4 @@
exports.newTradingProcess = function (processIndex) {
exports.newSuperalgosBotModulesTradingProcess = function (processIndex) {
/*
This Module will load all the process data dependencies from files and send them downstream.
After execution, will save the time range and status report of the process.
@@ -1,7 +1,6 @@
exports.newSuperalgosBotModulesSingleMarketTradingBot = function (processIndex) {
const MODULE_NAME = "Trading Bot";
const TRADING_PROCESS_MODULE = require(TS.projects.superalgos.globals.nodeJSConstants.REQUIRE_ROOT_DIR + '/LowFrequencyTrading/TradingProcess.js');
let session = TS.projects.superalgos.botModules.tradingSession.newSuperalgosBotModulesTradingSession(processIndex)
let nextLoopTimeoutHandle;
@@ -261,7 +260,7 @@
TS.projects.superalgos.globals.loggerVariables.VARIABLES_BY_PROCESS_INDEX_MAP.get(processIndex).BOT_MAIN_LOOP_LOGGER_MODULE.write(MODULE_NAME, "[INFO] run -> loop -> initializeDataDependencies -> onInizialized -> Execution finished well.")
switch (processConfig.framework.name) {
case 'Low-Frequency-Trading-Process': {
processFramework = TRADING_PROCESS_MODULE.newTradingProcess(processIndex);
processFramework = TS.projects.superalgos.botModules.tradingProcess.newSuperalgosBotModulesTradingProcess(processIndex);
intitializeProcessFramework();
break;
}
-912
View File
@@ -1,912 +0,0 @@
"use strict";
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
(function (f) {
if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === "object" && typeof module !== "undefined") {
module.exports = f();
} else if (typeof define === "function" && define.amd) {
define([], f);
} else {
var g;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
} else {
g = this;
}
g.debug = f();
}
})(function () {
var define, module, exports;
return function () {
function r(e, n, t) {
function o(i, f) {
if (!n[i]) {
if (!e[i]) {
var c = "function" == typeof require && require;
if (!f && c) return c(i, !0);
if (u) return u(i, !0);
var a = new Error("Cannot find module '" + i + "'");
throw a.code = "MODULE_NOT_FOUND", a;
}
var p = n[i] = {
exports: {}
};
e[i][0].call(p.exports, function (r) {
var n = e[i][1][r];
return o(n || r);
}, p, p.exports, r, e, n, t);
}
return n[i].exports;
}
for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) {
o(t[i]);
}
return o;
}
return r;
}()({
1: [function (require, module, exports) {
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = _typeof(val);
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
}, {}],
2: [function (require, module, exports) {
// shim for using process in browser
var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
} // if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
} // if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
}; // v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) {
return [];
};
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () {
return '/';
};
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function () {
return 0;
};
}, {}],
3: [function (require, module, exports) {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
Object.keys(env).forEach(function (key) {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
var hash = 0;
for (var i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime;
function debug() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Disabled?
if (!debug.enabled) {
return;
}
var self = debug; // Set `diff` timestamp
var curr = Number(new Date());
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
} // Apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
}
index++;
var formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
var val = args[index];
match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
}); // Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend; // Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
// env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
var index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.names = [];
createDebug.skips = [];
var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
var instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) {
return '-' + namespace;
}))).join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i;
var len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
}, {
"ms": 1
}],
4: [function (require, module, exports) {
(function (process) {
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
/**
* Colors.
*/
exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
} // Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
} // Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function (match) {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
var _console;
// This hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.getItem('debug');
} catch (error) {} // Swallow
// XXX (@Qix-) should we be logging these?
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
var formatters = module.exports.formatters;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
}).call(this, require('_process'));
}, {
"./common": 3,
"_process": 2
}]
}, {}, [4])(4);
});
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more