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

-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);
});
-102
View File
@@ -1,102 +0,0 @@
{
"_from": "debug@^4.0.1",
"_id": "debug@4.1.1",
"_inBundle": false,
"_integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
"_location": "/debug",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "debug@^4.0.1",
"name": "debug",
"escapedName": "debug",
"rawSpec": "^4.0.1",
"saveSpec": null,
"fetchSpec": "^4.0.1"
},
"_requiredBy": [
"/telegraf"
],
"_resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
"_shasum": "3b72260255109c6b589cee050f1d516139664791",
"_spec": "debug@^4.0.1",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\telegraf",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"browser": "./src/browser.js",
"bugs": {
"url": "https://github.com/visionmedia/debug/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://n8.io"
},
{
"name": "Andrew Rhyne",
"email": "rhyneandrew@gmail.com"
}
],
"dependencies": {
"ms": "^2.1.1"
},
"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",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.0.0",
"karma-chai": "^0.1.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"
},
"files": [
"src",
"dist/debug.js",
"LICENSE",
"README.md"
],
"homepage": "https://github.com/visionmedia/debug#readme",
"keywords": [
"debug",
"log",
"debugger"
],
"license": "MIT",
"main": "./src/index.js",
"name": "debug",
"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: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"
}
-264
View File
@@ -1,264 +0,0 @@
/* 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;
}
const 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
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, 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(...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);
}
/**
* 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() {
let 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);
const {formatters} = module.exports;
/**
* 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;
}
};
-266
View File
@@ -1,266 +0,0 @@
/**
* 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(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) {
let hash = 0;
for (let 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) {
let prevTime;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const 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
let index = 0;
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;
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const 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);
const 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() {
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;
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 = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const 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++) {
const instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + 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;
}
let i;
let 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;
-10
View File
@@ -1,10 +0,0 @@
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}
-257
View File
@@ -1,257 +0,0 @@
/**
* Module dependencies.
*/
const tty = require('tty');
const util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.format()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.format(...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.replace(/\s*\n\s*/g, ' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
-2
View File
@@ -1,2 +0,0 @@
var argv = require('../')(process.argv.slice(2));
console.log(argv);
-245
View File
@@ -1,245 +0,0 @@
module.exports = function (args, opts) {
if (!opts) opts = {};
var flags = { bools : {}, strings : {}, unknownFn: null };
if (typeof opts['unknown'] === 'function') {
flags.unknownFn = opts['unknown'];
}
if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
flags.allBools = true;
} else {
[].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
flags.bools[key] = true;
});
}
var aliases = {};
Object.keys(opts.alias || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key]);
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y;
}));
});
});
[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true;
if (aliases[key]) {
flags.strings[aliases[key]] = true;
}
});
var defaults = opts['default'] || {};
var argv = { _ : [] };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] === undefined ? false : defaults[key]);
});
var notFlags = [];
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--')+1);
args = args.slice(0, args.indexOf('--'));
}
function argDefined(key, arg) {
return (flags.allBools && /^--[^=]+$/.test(arg)) ||
flags.strings[key] || flags.bools[key] || aliases[key];
}
function setArg (key, val, arg) {
if (arg && flags.unknownFn && !argDefined(key, arg)) {
if (flags.unknownFn(arg) === false) return;
}
var value = !flags.strings[key] && isNumber(val)
? Number(val) : val
;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), value);
});
}
function setKey (obj, keys, value) {
var o = obj;
for (var i = 0; i < keys.length-1; i++) {
var key = keys[i];
if (key === '__proto__') return;
if (o[key] === undefined) o[key] = {};
if (o[key] === Object.prototype || o[key] === Number.prototype
|| o[key] === String.prototype) o[key] = {};
if (o[key] === Array.prototype) o[key] = [];
o = o[key];
}
var key = keys[keys.length - 1];
if (key === '__proto__') return;
if (o === Object.prototype || o === Number.prototype
|| o === String.prototype) o = {};
if (o === Array.prototype) o = [];
if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [ o[key], value ];
}
}
function aliasIsBoolean(key) {
return aliases[key].some(function (x) {
return flags.bools[x];
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (/^--.+=/.test(arg)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
var key = m[1];
var value = m[2];
if (flags.bools[key]) {
value = value !== 'false';
}
setArg(key, value, arg);
}
else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false, arg);
}
else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !/^-/.test(next)
&& !flags.bools[key]
&& !flags.allBools
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, next, arg);
i++;
}
else if (/^(true|false)$/.test(next)) {
setArg(key, next === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1,-1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
var next = arg.slice(j+2);
if (next === '-') {
setArg(letters[j], next, arg)
continue;
}
if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
setArg(letters[j], next.split('=')[1], arg);
broken = true;
break;
}
if (/[A-Za-z]/.test(letters[j])
&& /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next, arg);
broken = true;
break;
}
if (letters[j+1] && letters[j+1].match(/\W/)) {
setArg(letters[j], arg.slice(j+2), arg);
broken = true;
break;
}
else {
setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== '-') {
if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
&& !flags.bools[key]
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, args[i+1], arg);
i++;
}
else if (args[i+1] && /^(true|false)$/.test(args[i+1])) {
setArg(key, args[i+1] === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
}
else {
if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
argv._.push(
flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
);
}
if (opts.stopEarly) {
argv._.push.apply(argv._, args.slice(i + 1));
break;
}
}
}
Object.keys(defaults).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) {
setKey(argv, key.split('.'), defaults[key]);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), defaults[key]);
});
}
});
if (opts['--']) {
argv['--'] = new Array();
notFlags.forEach(function(key) {
argv['--'].push(key);
});
}
else {
notFlags.forEach(function(key) {
argv._.push(key);
});
}
return argv;
};
function hasKey (obj, keys) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
o = (o[key] || {});
});
var key = keys[keys.length - 1];
return key in o;
}
function isNumber (x) {
if (typeof x === 'number') return true;
if (/^0x[0-9a-f]+$/i.test(x)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
-73
View File
@@ -1,73 +0,0 @@
{
"_from": "minimist@^1.2.0",
"_id": "minimist@1.2.5",
"_inBundle": false,
"_integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
"_location": "/minimist",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "minimist@^1.2.0",
"name": "minimist",
"escapedName": "minimist",
"rawSpec": "^1.2.0",
"saveSpec": null,
"fetchSpec": "^1.2.0"
},
"_requiredBy": [
"/telegraf"
],
"_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",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/minimist/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "parse argument options",
"devDependencies": {
"covert": "^1.0.0",
"tap": "~0.4.0",
"tape": "^3.5.0"
},
"homepage": "https://github.com/substack/minimist",
"keywords": [
"argv",
"getopt",
"parser",
"optimist"
],
"license": "MIT",
"main": "index.js",
"name": "minimist",
"repository": {
"type": "git",
"url": "git://github.com/substack/minimist.git"
},
"scripts": {
"coverage": "covert test/*.js",
"test": "tap test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/6..latest",
"ff/5",
"firefox/latest",
"chrome/10",
"chrome/latest",
"safari/5.1",
"safari/latest",
"opera/12"
]
},
"version": "1.2.5"
}
-32
View File
@@ -1,32 +0,0 @@
var parse = require('../');
var test = require('tape');
test('flag boolean true (default all --args to boolean)', function (t) {
var argv = parse(['moo', '--honk', 'cow'], {
boolean: true
});
t.deepEqual(argv, {
honk: true,
_: ['moo', 'cow']
});
t.deepEqual(typeof argv.honk, 'boolean');
t.end();
});
test('flag boolean true only affects double hyphen arguments without equals signs', function (t) {
var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], {
boolean: true
});
t.deepEqual(argv, {
honk: true,
tacos: 'good',
p: 55,
_: ['moo', 'cow']
});
t.deepEqual(typeof argv.honk, 'boolean');
t.end();
});
-178
View File
@@ -1,178 +0,0 @@
var parse = require('../');
var test = require('tape');
test('flag boolean default false', function (t) {
var argv = parse(['moo'], {
boolean: ['t', 'verbose'],
default: { verbose: false, t: false }
});
t.deepEqual(argv, {
verbose: false,
t: false,
_: ['moo']
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('boolean groups', function (t) {
var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], {
boolean: ['x','y','z']
});
t.deepEqual(argv, {
x : true,
y : false,
z : true,
_ : [ 'one', 'two', 'three' ]
});
t.deepEqual(typeof argv.x, 'boolean');
t.deepEqual(typeof argv.y, 'boolean');
t.deepEqual(typeof argv.z, 'boolean');
t.end();
});
test('boolean and alias with chainable api', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var opts = {
herp: { alias: 'h', boolean: true }
};
var aliasedArgv = parse(aliased, {
boolean: 'herp',
alias: { h: 'herp' }
});
var propertyArgv = parse(regular, {
boolean: 'herp',
alias: { h: 'herp' }
});
var expected = {
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias with options hash', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var opts = {
alias: { 'h': 'herp' },
boolean: 'herp'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias array with options hash', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var alt = [ '--harp', 'derp' ];
var opts = {
alias: { 'h': ['herp', 'harp'] },
boolean: 'h'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var altPropertyArgv = parse(alt, opts);
var expected = {
harp: true,
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.same(altPropertyArgv, expected);
t.end();
});
test('boolean and alias using explicit true', function (t) {
var aliased = [ '-h', 'true' ];
var regular = [ '--herp', 'true' ];
var opts = {
alias: { h: 'herp' },
boolean: 'h'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
'_': [ ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
// regression, see https://github.com/substack/node-optimist/issues/71
test('boolean and --x=true', function(t) {
var parsed = parse(['--boool', '--other=true'], {
boolean: 'boool'
});
t.same(parsed.boool, true);
t.same(parsed.other, 'true');
parsed = parse(['--boool', '--other=false'], {
boolean: 'boool'
});
t.same(parsed.boool, true);
t.same(parsed.other, 'false');
t.end();
});
test('boolean --boool=true', function (t) {
var parsed = parse(['--boool=true'], {
default: {
boool: false
},
boolean: ['boool']
});
t.same(parsed.boool, true);
t.end();
});
test('boolean --boool=false', function (t) {
var parsed = parse(['--boool=false'], {
default: {
boool: true
},
boolean: ['boool']
});
t.same(parsed.boool, false);
t.end();
});
test('boolean using something similar to true', function (t) {
var opts = { boolean: 'h' };
var result = parse(['-h', 'true.txt'], opts);
var expected = {
h: true,
'_': ['true.txt']
};
t.same(result, expected);
t.end();
});
-31
View File
@@ -1,31 +0,0 @@
var parse = require('../');
var test = require('tape');
test('-', function (t) {
t.plan(5);
t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] });
t.deepEqual(parse([ '-' ]), { _: [ '-' ] });
t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] });
t.deepEqual(
parse([ '-b', '-' ], { boolean: 'b' }),
{ b: true, _: [ '-' ] }
);
t.deepEqual(
parse([ '-s', '-' ], { string: 's' }),
{ s: '-', _: [] }
);
});
test('-a -- b', function (t) {
t.plan(3);
t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
});
test('move arguments after the -- into their own `--` array', function(t) {
t.plan(1);
t.deepEqual(
parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }),
{ name: 'John', _: [ 'before' ], '--': [ 'after' ] });
});
-35
View File
@@ -1,35 +0,0 @@
var test = require('tape');
var parse = require('../');
test('boolean default true', function (t) {
var argv = parse([], {
boolean: 'sometrue',
default: { sometrue: true }
});
t.equal(argv.sometrue, true);
t.end();
});
test('boolean default false', function (t) {
var argv = parse([], {
boolean: 'somefalse',
default: { somefalse: false }
});
t.equal(argv.somefalse, false);
t.end();
});
test('boolean default to null', function (t) {
var argv = parse([], {
boolean: 'maybe',
default: { maybe: null }
});
t.equal(argv.maybe, null);
var argv = parse(['--maybe'], {
boolean: 'maybe',
default: { maybe: null }
});
t.equal(argv.maybe, true);
t.end();
})
-22
View File
@@ -1,22 +0,0 @@
var parse = require('../');
var test = require('tape');
test('dotted alias', function (t) {
var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
t.equal(argv.a.b, 22);
t.equal(argv.aa.bb, 22);
t.end();
});
test('dotted default', function (t) {
var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
t.equal(argv.a.b, 11);
t.equal(argv.aa.bb, 11);
t.end();
});
test('dotted default with no alias', function (t) {
var argv = parse('', {default: {'a.b': 11}});
t.equal(argv.a.b, 11);
t.end();
});
-16
View File
@@ -1,16 +0,0 @@
var parse = require('../');
var test = require('tape');
test('short -k=v' , function (t) {
t.plan(1);
var argv = parse([ '-b=123' ]);
t.deepEqual(argv, { b: 123, _: [] });
});
test('multi short -k=v' , function (t) {
t.plan(1);
var argv = parse([ '-a=whatever', '-b=robots' ]);
t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] });
});
-31
View File
@@ -1,31 +0,0 @@
var test = require('tape');
var parse = require('../');
test('long opts', function (t) {
t.deepEqual(
parse([ '--bool' ]),
{ bool : true, _ : [] },
'long boolean'
);
t.deepEqual(
parse([ '--pow', 'xixxle' ]),
{ pow : 'xixxle', _ : [] },
'long capture sp'
);
t.deepEqual(
parse([ '--pow=xixxle' ]),
{ pow : 'xixxle', _ : [] },
'long capture eq'
);
t.deepEqual(
parse([ '--host', 'localhost', '--port', '555' ]),
{ host : 'localhost', port : 555, _ : [] },
'long captures sp'
);
t.deepEqual(
parse([ '--host=localhost', '--port=555' ]),
{ host : 'localhost', port : 555, _ : [] },
'long captures eq'
);
t.end();
});
-36
View File
@@ -1,36 +0,0 @@
var parse = require('../');
var test = require('tape');
test('nums', function (t) {
var argv = parse([
'-x', '1234',
'-y', '5.67',
'-z', '1e7',
'-w', '10f',
'--hex', '0xdeadbeef',
'789'
]);
t.deepEqual(argv, {
x : 1234,
y : 5.67,
z : 1e7,
w : '10f',
hex : 0xdeadbeef,
_ : [ 789 ]
});
t.deepEqual(typeof argv.x, 'number');
t.deepEqual(typeof argv.y, 'number');
t.deepEqual(typeof argv.z, 'number');
t.deepEqual(typeof argv.w, 'string');
t.deepEqual(typeof argv.hex, 'number');
t.deepEqual(typeof argv._[0], 'number');
t.end();
});
test('already a number', function (t) {
var argv = parse([ '-x', 1234, 789 ]);
t.deepEqual(argv, { x : 1234, _ : [ 789 ] });
t.deepEqual(typeof argv.x, 'number');
t.deepEqual(typeof argv._[0], 'number');
t.end();
});
-197
View File
@@ -1,197 +0,0 @@
var parse = require('../');
var test = require('tape');
test('parse args', function (t) {
t.deepEqual(
parse([ '--no-moo' ]),
{ moo : false, _ : [] },
'no'
);
t.deepEqual(
parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
{ v : ['a','b','c'], _ : [] },
'multi'
);
t.end();
});
test('comprehensive', function (t) {
t.deepEqual(
parse([
'--name=meowmers', 'bare', '-cats', 'woo',
'-h', 'awesome', '--multi=quux',
'--key', 'value',
'-b', '--bool', '--no-meep', '--multi=baz',
'--', '--not-a-flag', 'eek'
]),
{
c : true,
a : true,
t : true,
s : 'woo',
h : 'awesome',
b : true,
bool : true,
key : 'value',
multi : [ 'quux', 'baz' ],
meep : false,
name : 'meowmers',
_ : [ 'bare', '--not-a-flag', 'eek' ]
}
);
t.end();
});
test('flag boolean', function (t) {
var argv = parse([ '-t', 'moo' ], { boolean: 't' });
t.deepEqual(argv, { t : true, _ : [ 'moo' ] });
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('flag boolean value', function (t) {
var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], {
boolean: [ 't', 'verbose' ],
default: { verbose: true }
});
t.deepEqual(argv, {
verbose: false,
t: true,
_: ['moo']
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('newlines in params' , function (t) {
var args = parse([ '-s', "X\nX" ])
t.deepEqual(args, { _ : [], s : "X\nX" });
// reproduce in bash:
// VALUE="new
// line"
// node program.js --s="$VALUE"
args = parse([ "--s=X\nX" ])
t.deepEqual(args, { _ : [], s : "X\nX" });
t.end();
});
test('strings' , function (t) {
var s = parse([ '-s', '0001234' ], { string: 's' }).s;
t.equal(s, '0001234');
t.equal(typeof s, 'string');
var x = parse([ '-x', '56' ], { string: 'x' }).x;
t.equal(x, '56');
t.equal(typeof x, 'string');
t.end();
});
test('stringArgs', function (t) {
var s = parse([ ' ', ' ' ], { string: '_' })._;
t.same(s.length, 2);
t.same(typeof s[0], 'string');
t.same(s[0], ' ');
t.same(typeof s[1], 'string');
t.same(s[1], ' ');
t.end();
});
test('empty strings', function(t) {
var s = parse([ '-s' ], { string: 's' }).s;
t.equal(s, '');
t.equal(typeof s, 'string');
var str = parse([ '--str' ], { string: 'str' }).str;
t.equal(str, '');
t.equal(typeof str, 'string');
var letters = parse([ '-art' ], {
string: [ 'a', 't' ]
});
t.equal(letters.a, '');
t.equal(letters.r, true);
t.equal(letters.t, '');
t.end();
});
test('string and alias', function(t) {
var x = parse([ '--str', '000123' ], {
string: 's',
alias: { s: 'str' }
});
t.equal(x.str, '000123');
t.equal(typeof x.str, 'string');
t.equal(x.s, '000123');
t.equal(typeof x.s, 'string');
var y = parse([ '-s', '000123' ], {
string: 'str',
alias: { str: 's' }
});
t.equal(y.str, '000123');
t.equal(typeof y.str, 'string');
t.equal(y.s, '000123');
t.equal(typeof y.s, 'string');
t.end();
});
test('slashBreak', function (t) {
t.same(
parse([ '-I/foo/bar/baz' ]),
{ I : '/foo/bar/baz', _ : [] }
);
t.same(
parse([ '-xyz/foo/bar/baz' ]),
{ x : true, y : true, z : '/foo/bar/baz', _ : [] }
);
t.end();
});
test('alias', function (t) {
var argv = parse([ '-f', '11', '--zoom', '55' ], {
alias: { z: 'zoom' }
});
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.f, 11);
t.end();
});
test('multiAlias', function (t) {
var argv = parse([ '-f', '11', '--zoom', '55' ], {
alias: { z: [ 'zm', 'zoom' ] }
});
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.z, argv.zm);
t.equal(argv.f, 11);
t.end();
});
test('nested dotted objects', function (t) {
var argv = parse([
'--foo.bar', '3', '--foo.baz', '4',
'--foo.quux.quibble', '5', '--foo.quux.o_O',
'--beep.boop'
]);
t.same(argv.foo, {
bar : 3,
baz : 4,
quux : {
quibble : 5,
o_O : true
}
});
t.same(argv.beep, { boop : true });
t.end();
});
-9
View File
@@ -1,9 +0,0 @@
var parse = require('../');
var test = require('tape');
test('parse with modifier functions' , function (t) {
t.plan(1);
var argv = parse([ '-b', '123' ], { boolean: 'b' });
t.deepEqual(argv, { b: true, _: [123] });
});
-44
View File
@@ -1,44 +0,0 @@
var parse = require('../');
var test = require('tape');
test('proto pollution', function (t) {
var argv = parse(['--__proto__.x','123']);
t.equal({}.x, undefined);
t.equal(argv.__proto__.x, undefined);
t.equal(argv.x, undefined);
t.end();
});
test('proto pollution (array)', function (t) {
var argv = parse(['--x','4','--x','5','--x.__proto__.z','789']);
t.equal({}.z, undefined);
t.deepEqual(argv.x, [4,5]);
t.equal(argv.x.z, undefined);
t.equal(argv.x.__proto__.z, undefined);
t.end();
});
test('proto pollution (number)', function (t) {
var argv = parse(['--x','5','--x.__proto__.z','100']);
t.equal({}.z, undefined);
t.equal((4).z, undefined);
t.equal(argv.x, 5);
t.equal(argv.x.z, undefined);
t.end();
});
test('proto pollution (string)', function (t) {
var argv = parse(['--x','abc','--x.__proto__.z','def']);
t.equal({}.z, undefined);
t.equal('...'.z, undefined);
t.equal(argv.x, 'abc');
t.equal(argv.x.z, undefined);
t.end();
});
test('proto pollution (constructor)', function (t) {
var argv = parse(['--constructor.prototype.y','123']);
t.equal({}.y, undefined);
t.equal(argv.y, undefined);
t.end();
});
-67
View File
@@ -1,67 +0,0 @@
var parse = require('../');
var test = require('tape');
test('numeric short args', function (t) {
t.plan(2);
t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] });
t.deepEqual(
parse([ '-123', '456' ]),
{ 1: true, 2: true, 3: 456, _: [] }
);
});
test('short', function (t) {
t.deepEqual(
parse([ '-b' ]),
{ b : true, _ : [] },
'short boolean'
);
t.deepEqual(
parse([ 'foo', 'bar', 'baz' ]),
{ _ : [ 'foo', 'bar', 'baz' ] },
'bare'
);
t.deepEqual(
parse([ '-cats' ]),
{ c : true, a : true, t : true, s : true, _ : [] },
'group'
);
t.deepEqual(
parse([ '-cats', 'meow' ]),
{ c : true, a : true, t : true, s : 'meow', _ : [] },
'short group next'
);
t.deepEqual(
parse([ '-h', 'localhost' ]),
{ h : 'localhost', _ : [] },
'short capture'
);
t.deepEqual(
parse([ '-h', 'localhost', '-p', '555' ]),
{ h : 'localhost', p : 555, _ : [] },
'short captures'
);
t.end();
});
test('mixed short bool and capture', function (t) {
t.same(
parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ]
}
);
t.end();
});
test('short and long', function (t) {
t.deepEqual(
parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ]
}
);
t.end();
});
-15
View File
@@ -1,15 +0,0 @@
var parse = require('../');
var test = require('tape');
test('stops parsing on the first non-option when stopEarly is set', function (t) {
var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], {
stopEarly: true
});
t.deepEqual(argv, {
aaa: 'bbb',
_: ['ccc', '--ddd']
});
t.end();
});
-102
View File
@@ -1,102 +0,0 @@
var parse = require('../');
var test = require('tape');
test('boolean and alias is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var aliased = [ '-h', 'true', '--derp', 'true' ];
var regular = [ '--herp', 'true', '-d', 'true' ];
var opts = {
alias: { h: 'herp' },
boolean: 'h',
unknown: unknownFn
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
t.same(unknown, ['--derp', '-d']);
t.end();
});
test('flag boolean true any double hyphen argument is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], {
boolean: true,
unknown: unknownFn
});
t.same(unknown, ['--tacos=good', 'cow', '-p']);
t.same(argv, {
honk: true,
_: []
});
t.end();
});
test('string and alias is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var aliased = [ '-h', 'hello', '--derp', 'goodbye' ];
var regular = [ '--herp', 'hello', '-d', 'moon' ];
var opts = {
alias: { h: 'herp' },
string: 'h',
unknown: unknownFn
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
t.same(unknown, ['--derp', '-d']);
t.end();
});
test('default and alias is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var aliased = [ '-h', 'hello' ];
var regular = [ '--herp', 'hello' ];
var opts = {
default: { 'h': 'bar' },
alias: { 'h': 'herp' },
unknown: unknownFn
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
t.same(unknown, []);
t.end();
unknownFn(); // exercise fn for 100% coverage
});
test('value following -- is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var aliased = [ '--bad', '--', 'good', 'arg' ];
var opts = {
'--': true,
unknown: unknownFn
};
var argv = parse(aliased, opts);
t.same(unknown, ['--bad']);
t.same(argv, {
'--': ['good', 'arg'],
'_': []
})
t.end();
});
-8
View File
@@ -1,8 +0,0 @@
var parse = require('../');
var test = require('tape');
test('whitespace should be whitespace' , function (t) {
t.plan(1);
var x = parse([ '-x', '\t' ]).x;
t.equal(x, '\t');
});
-224
View File
@@ -1,224 +0,0 @@
'use strict'
var BuiltinModule = require('module')
// Guard against poorly mocked module constructors
var Module = module.constructor.length > 1
? module.constructor
: BuiltinModule
var nodePath = require('path')
var modulePaths = []
var moduleAliases = {}
var moduleAliasNames = []
var oldNodeModulePaths = Module._nodeModulePaths
Module._nodeModulePaths = function (from) {
var paths = oldNodeModulePaths.call(this, from)
// Only include the module path for top-level modules
// that were not installed:
if (from.indexOf('node_modules') === -1) {
paths = modulePaths.concat(paths)
}
return paths
}
var oldResolveFilename = Module._resolveFilename
Module._resolveFilename = function (request, parentModule, isMain, options) {
for (var i = moduleAliasNames.length; i-- > 0;) {
var alias = moduleAliasNames[i]
if (isPathMatchesAlias(request, alias)) {
var aliasTarget = moduleAliases[alias]
// Custom function handler
if (typeof moduleAliases[alias] === 'function') {
var fromPath = parentModule.filename
aliasTarget = moduleAliases[alias](fromPath, request, alias)
if (!aliasTarget || typeof aliasTarget !== 'string') {
throw new Error('[module-alias] Expecting custom handler function to return path.')
}
}
request = nodePath.join(aliasTarget, request.substr(alias.length))
// Only use the first match
break
}
}
return oldResolveFilename.call(this, request, parentModule, isMain, options)
}
function isPathMatchesAlias (path, alias) {
// Matching /^alias(\/|$)/
if (path.indexOf(alias) === 0) {
if (path.length === alias.length) return true
if (path[alias.length] === '/') return true
}
return false
}
function addPathHelper (path, targetArray) {
path = nodePath.normalize(path)
if (targetArray && targetArray.indexOf(path) === -1) {
targetArray.unshift(path)
}
}
function removePathHelper (path, targetArray) {
if (targetArray) {
var index = targetArray.indexOf(path)
if (index !== -1) {
targetArray.splice(index, 1)
}
}
}
function addPath (path) {
var parent
path = nodePath.normalize(path)
if (modulePaths.indexOf(path) === -1) {
modulePaths.push(path)
// Enable the search path for the current top-level module
var mainModule = getMainModule()
if (mainModule) {
addPathHelper(path, mainModule.paths)
}
parent = module.parent
// Also modify the paths of the module that was used to load the
// app-module-paths module and all of it's parents
while (parent && parent !== mainModule) {
addPathHelper(path, parent.paths)
parent = parent.parent
}
}
}
function addAliases (aliases) {
for (var alias in aliases) {
addAlias(alias, aliases[alias])
}
}
function addAlias (alias, target) {
moduleAliases[alias] = target
// Cost of sorting is lower here than during resolution
moduleAliasNames = Object.keys(moduleAliases)
moduleAliasNames.sort()
}
/**
* Reset any changes maded (resets all registered aliases
* and custom module directories)
* The function is undocumented and for testing purposes only
*/
function reset () {
var mainModule = getMainModule()
// Reset all changes in paths caused by addPath function
modulePaths.forEach(function (path) {
if (mainModule) {
removePathHelper(path, mainModule.paths)
}
// Delete from require.cache if the module has been required before.
// This is required for node >= 11
Object.getOwnPropertyNames(require.cache).forEach(function (name) {
if (name.indexOf(path) !== -1) {
delete require.cache[name]
}
})
var parent = module.parent
while (parent && parent !== mainModule) {
removePathHelper(path, parent.paths)
parent = parent.parent
}
})
modulePaths = []
moduleAliases = {}
moduleAliasNames = []
}
/**
* Import aliases from package.json
* @param {object} options
*/
function init (options) {
if (typeof options === 'string') {
options = { base: options }
}
options = options || {}
var candidatePackagePaths
if (options.base) {
candidatePackagePaths = [nodePath.resolve(options.base.replace(/\/package\.json$/, ''))]
} else {
// There is probably 99% chance that the project root directory in located
// above the node_modules directory,
// Or that package.json is in the node process' current working directory (when
// running a package manager script, e.g. `yarn start` / `npm run start`)
candidatePackagePaths = [nodePath.join(__dirname, '../..'), process.cwd()]
}
var npmPackage
var base
for (var i in candidatePackagePaths) {
try {
base = candidatePackagePaths[i]
npmPackage = require(nodePath.join(base, 'package.json'))
break
} catch (e) {
// noop
}
}
if (typeof npmPackage !== 'object') {
var pathString = candidatePackagePaths.join(',\n')
throw new Error('Unable to find package.json in any of:\n[' + pathString + ']')
}
//
// Import aliases
//
var aliases = npmPackage._moduleAliases || {}
for (var alias in aliases) {
if (aliases[alias][0] !== '/') {
aliases[alias] = nodePath.join(base, aliases[alias])
}
}
addAliases(aliases)
//
// Register custom module directories (like node_modules)
//
if (npmPackage._moduleDirectories instanceof Array) {
npmPackage._moduleDirectories.forEach(function (dir) {
if (dir === 'node_modules') return
var modulePath = nodePath.join(base, dir)
addPath(modulePath)
})
}
}
function getMainModule () {
return require.main._simulateRepl ? undefined : require.main
}
module.exports = init
module.exports.addPath = addPath
module.exports.addAlias = addAlias
module.exports.addAliases = addAliases
module.exports.isPathMatchesAlias = isPathMatchesAlias
module.exports.reset = reset
-76
View File
@@ -1,76 +0,0 @@
{
"_from": "module-alias@^2.2.2",
"_id": "module-alias@2.2.2",
"_inBundle": false,
"_integrity": "sha512-A/78XjoX2EmNvppVWEhM2oGk3x4lLxnkEA4jTbaK97QKSDjkIoOsKQlfylt/d3kKKi596Qy3NP5XrXJ6fZIC9Q==",
"_location": "/module-alias",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "module-alias@^2.2.2",
"name": "module-alias",
"escapedName": "module-alias",
"rawSpec": "^2.2.2",
"saveSpec": null,
"fetchSpec": "^2.2.2"
},
"_requiredBy": [
"/telegraf"
],
"_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",
"author": {
"name": "Nick Gavrilov",
"email": "artnikpro@gmail.com"
},
"bugs": {
"url": "https://github.com/ilearnio/module-alias/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Create aliases of directories and register custom module paths",
"devDependencies": {
"chai": "^3.5.0",
"hello-world-classic": "github:ilearnio/hello-world-classic",
"husky": "^3.0.2",
"mocha": "^2.4.5",
"semver": "^6.1.1",
"standard": "^12.0.1"
},
"files": [
"index.js",
"register.js",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/ilearnio/module-alias",
"husky": {
"hooks": {
"pre-push": "npm run test"
}
},
"keywords": [
"extend",
"modules",
"node",
"path",
"resolve"
],
"license": "MIT",
"main": "index.js",
"name": "module-alias",
"repository": {
"type": "git",
"url": "git+https://github.com/ilearnio/module-alias.git"
},
"scripts": {
"lint": "standard",
"test": "npm run lint && npm run testonly",
"testonly": "NODE_ENV=test mocha test/specs.js",
"testonly-watch": "NODE_ENV=test mocha -w test/specs.js"
},
"version": "2.2.2"
}
-1
View File
@@ -1 +0,0 @@
require('.')()
-162
View File
@@ -1,162 +0,0 @@
/**
* 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' && isFinite(val)) {
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+) *(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' : '');
}
-69
View File
@@ -1,69 +0,0 @@
{
"_from": "ms@^2.1.1",
"_id": "ms@2.1.2",
"_inBundle": false,
"_integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
"_location": "/ms",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ms@^2.1.1",
"name": "ms",
"escapedName": "ms",
"rawSpec": "^2.1.1",
"saveSpec": null,
"fetchSpec": "^2.1.1"
},
"_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",
"bugs": {
"url": "https://github.com/zeit/ms/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Tiny millisecond conversion utility",
"devDependencies": {
"eslint": "4.12.1",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"files": [
"index.js"
],
"homepage": "https://github.com/zeit/ms#readme",
"license": "MIT",
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"main": "./index",
"name": "ms",
"repository": {
"type": "git",
"url": "git+https://github.com/zeit/ms.git"
},
"scripts": {
"lint": "eslint lib/* bin/*",
"precommit": "lint-staged",
"test": "mocha tests.js"
},
"version": "2.1.2"
}
-23
View File
@@ -1,23 +0,0 @@
"use strict";
// ref: https://github.com/tc39/proposal-global
var getGlobal = function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
}
var global = getGlobal();
module.exports = exports = global.fetch;
// Needed for TypeScript and Webpack.
exports.default = global.fetch.bind(global);
exports.Headers = global.Headers;
exports.Request = global.Request;
exports.Response = global.Response;
File diff suppressed because it is too large. Load diff
-1642
View File
File diff suppressed because it is too large. Load diff
-93
View File
@@ -1,93 +0,0 @@
{
"_from": "node-fetch@^2.2.0",
"_id": "node-fetch@2.6.0",
"_inBundle": false,
"_integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==",
"_location": "/node-fetch",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "node-fetch@^2.2.0",
"name": "node-fetch",
"escapedName": "node-fetch",
"rawSpec": "^2.2.0",
"saveSpec": null,
"fetchSpec": "^2.2.0"
},
"_requiredBy": [
"/telegraf"
],
"_resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz",
"_shasum": "e633456386d4aa55863f676a7ab0daa8fdecb0fd",
"_spec": "node-fetch@^2.2.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\TaskServer\\node_modules\\telegraf",
"author": {
"name": "David Frank"
},
"browser": "./browser.js",
"bugs": {
"url": "https://github.com/bitinn/node-fetch/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "A light-weight module that brings window.fetch to node.js",
"devDependencies": {
"@ungap/url-search-params": "^0.1.2",
"abort-controller": "^1.1.0",
"abortcontroller-polyfill": "^1.3.0",
"babel-core": "^6.26.3",
"babel-plugin-istanbul": "^4.1.6",
"babel-preset-env": "^1.6.1",
"babel-register": "^6.16.3",
"chai": "^3.5.0",
"chai-as-promised": "^7.1.1",
"chai-iterator": "^1.1.1",
"chai-string": "~1.3.0",
"codecov": "^3.3.0",
"cross-env": "^5.2.0",
"form-data": "^2.3.3",
"is-builtin-module": "^1.0.0",
"mocha": "^5.0.0",
"nyc": "11.9.0",
"parted": "^0.1.1",
"promise": "^8.0.3",
"resumer": "0.0.0",
"rollup": "^0.63.4",
"rollup-plugin-babel": "^3.0.7",
"string-to-arraybuffer": "^1.0.2",
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"files": [
"lib/index.js",
"lib/index.mjs",
"lib/index.es.js",
"browser.js"
],
"homepage": "https://github.com/bitinn/node-fetch",
"keywords": [
"fetch",
"http",
"promise"
],
"license": "MIT",
"main": "lib/index",
"module": "lib/index.mjs",
"name": "node-fetch",
"repository": {
"type": "git",
"url": "git+https://github.com/bitinn/node-fetch.git"
},
"scripts": {
"build": "cross-env BABEL_ENV=rollup rollup -c",
"coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json",
"prepare": "npm run build",
"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"
}
-185
View File
@@ -1,185 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var stream = require('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 stream.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);
}
}
}
exports.SandwichStream = SandwichStream;
exports.default = SandwichStream;
-101
View File
@@ -1,101 +0,0 @@
{
"_from": "sandwich-stream@^2.0.1",
"_id": "sandwich-stream@2.0.2",
"_inBundle": false,
"_integrity": "sha512-jLYV0DORrzY3xaz/S9ydJL6Iz7essZeAfnAavsJ+zsJGZ1MOnsS52yRjU3uF3pJa/lla7+wisp//fxOwOH8SKQ==",
"_location": "/sandwich-stream",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "sandwich-stream@^2.0.1",
"name": "sandwich-stream",
"escapedName": "sandwich-stream",
"rawSpec": "^2.0.1",
"saveSpec": null,
"fetchSpec": "^2.0.1"
},
"_requiredBy": [
"/telegraf"
],
"_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",
"author": {
"name": "connrs",
"url": "https://connrs.uk/"
},
"bugs": {
"url": "https://github.com/connrs/node-sandwich-stream/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Fazendaaa",
"email": "lucas.carotta@outlook.com",
"url": "http://fazendaaa.me/"
}
],
"dependencies": {},
"deprecated": false,
"description": "A readable stream that concatenates multiple streams with optional head, tail & join buffers",
"devDependencies": {
"@types/jest": "^23.3.5",
"@types/node": "^10.12.0",
"codecov": "^3.1.0",
"husky": "^1.1.2",
"jest": "^23.6.0",
"rollup": "^0.66.6",
"rollup-plugin-typescript2": "^0.17.2",
"snyk": "^1.104.1",
"ts-jest": "^23.10.4",
"ts-node": "^7.0.1",
"tslint": "^5.11.0",
"tslint-microsoft-contrib": "^5.2.1",
"typedoc": "^0.13.0",
"typescript": "^3.1.4"
},
"engines": {
"node": ">= 0.10"
},
"homepage": "https://github.com/connrs/node-sandwich-stream#readme",
"husky": {
"hooks": {
"pre-push": "npm run build && npm test",
"pre-commit": "npm run lint && npm run docs"
}
},
"keywords": [
"stream",
"sandwich",
"readable",
"typescript",
"concatenation"
],
"license": "Apache-2.0",
"licenses": [
{
"type": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.txt"
}
],
"main": "dist/sandwich-stream",
"module": "dist/sandwich-stream.mjs",
"name": "sandwich-stream",
"repository": {
"type": "git",
"url": "git+https://github.com/connrs/node-sandwich-stream.git"
},
"scripts": {
"build": "npm run rollup:build",
"docs": "typedoc --out ./docs/ ./src/",
"jest": "jest --config jest.config.json --ci --runInBand --detectOpenHandles --forceExit --no-cache",
"lint": "tslint --config tslint.json --project .",
"rollup:build": "rollup -c",
"rollup:watch": "npm run rollup:build -- --watch",
"test": "snyk test && npm run jest"
},
"types": "dist/sandwich-stream.d.ts",
"version": "2.0.2"
}
-40
View File
@@ -1,40 +0,0 @@
import typescript from 'rollup-plugin-typescript2';
import nodeOs from 'os';
import nodePath from 'path';
import pkg from './package.json';
export default [
{
input: 'src/sandwich-stream.ts',
external: [
'stream'
],
plugins: [
typescript({
cacheRoot: nodePath.join(
nodeOs.tmpdir(),
String(Date.now),
'.rpt2_cache'
),
tsconfigOverride: {
compilerOptions: {
composite: false
}
}
})
],
output: [
{
file: `${pkg.main}.js`,
format: 'cjs',
exports: 'named'
},
{
file: `${pkg.main}.mjs`,
format: 'esm'
}
]
}
];
-408
View File
@@ -1,408 +0,0 @@
const Context = require('./context')
class Composer {
constructor (...fns) {
this.handler = Composer.compose(fns)
}
use (...fns) {
this.handler = Composer.compose([this.handler, ...fns])
return this
}
on (updateTypes, ...fns) {
return this.use(Composer.mount(updateTypes, ...fns))
}
hears (triggers, ...fns) {
return this.use(Composer.hears(triggers, ...fns))
}
command (commands, ...fns) {
return this.use(Composer.command(commands, ...fns))
}
action (triggers, ...fns) {
return this.use(Composer.action(triggers, ...fns))
}
inlineQuery (triggers, ...fns) {
return this.use(Composer.inlineQuery(triggers, ...fns))
}
gameQuery (...fns) {
return this.use(Composer.gameQuery(...fns))
}
drop (predicate) {
return this.use(Composer.drop(predicate))
}
filter (predicate) {
return this.use(Composer.filter(predicate))
}
entity (...args) {
return this.use(Composer.entity(...args))
}
email (...args) {
return this.use(Composer.email(...args))
}
url (...args) {
return this.use(Composer.url(...args))
}
textLink (...args) {
return this.use(Composer.textLink(...args))
}
textMention (...args) {
return this.use(Composer.textMention(...args))
}
mention (...args) {
return this.use(Composer.mention(...args))
}
phone (...args) {
return this.use(Composer.phone(...args))
}
hashtag (...args) {
return this.use(Composer.hashtag(...args))
}
cashtag (...args) {
return this.use(Composer.cashtag(...args))
}
start (...fns) {
return this.command('start', Composer.tap((ctx) => {
ctx.startPayload = ctx.message.text.substring(7)
}), ...fns)
}
help (...fns) {
return this.command('help', ...fns)
}
settings (...fns) {
return this.command('settings', ...fns)
}
middleware () {
return this.handler
}
static reply (...args) {
return (ctx) => ctx.reply(...args)
}
static catchAll (...fns) {
return Composer.catch((err) => {
console.error()
console.error((err.stack || err.toString()).replace(/^/gm, ' '))
console.error()
}, ...fns)
}
static catch (errorHandler, ...fns) {
const handler = Composer.compose(fns)
return (ctx, next) => Promise.resolve(handler(ctx, next))
.catch((err) => errorHandler(err, ctx))
}
static fork (middleware) {
const handler = Composer.unwrap(middleware)
return (ctx, next) => {
setImmediate(handler, ctx, Composer.safePassThru())
return next(ctx)
}
}
static tap (middleware) {
const handler = Composer.unwrap(middleware)
return (ctx, next) => Promise.resolve(handler(ctx, Composer.safePassThru())).then(() => next(ctx))
}
static passThru () {
return (ctx, next) => next(ctx)
}
static safePassThru () {
return (ctx, next) => typeof next === 'function' ? next(ctx) : Promise.resolve()
}
static lazy (factoryFn) {
if (typeof factoryFn !== 'function') {
throw new Error('Argument must be a function')
}
return (ctx, next) => Promise.resolve(factoryFn(ctx))
.then((middleware) => Composer.unwrap(middleware)(ctx, next))
}
static log (logFn = console.log) {
return Composer.fork((ctx) => logFn(JSON.stringify(ctx.update, null, 2)))
}
static branch (predicate, trueMiddleware, falseMiddleware) {
if (typeof predicate !== 'function') {
return predicate ? trueMiddleware : falseMiddleware
}
return Composer.lazy((ctx) => Promise.resolve(predicate(ctx))
.then((value) => value ? trueMiddleware : falseMiddleware))
}
static optional (predicate, ...fns) {
return Composer.branch(predicate, Composer.compose(fns), Composer.safePassThru())
}
static filter (predicate) {
return Composer.branch(predicate, Composer.safePassThru(), () => { })
}
static drop (predicate) {
return Composer.branch(predicate, () => { }, Composer.safePassThru())
}
static dispatch (routeFn, handlers) {
return typeof routeFn === 'function'
? Composer.lazy((ctx) => Promise.resolve(routeFn(ctx)).then((value) => handlers[value]))
: handlers[routeFn]
}
static mount (updateType, ...fns) {
const updateTypes = normalizeTextArguments(updateType)
const predicate = (ctx) => updateTypes.includes(ctx.updateType) || updateTypes.some((type) => ctx.updateSubTypes.includes(type))
return Composer.optional(predicate, ...fns)
}
static entity (predicate, ...fns) {
if (typeof predicate !== 'function') {
const entityTypes = normalizeTextArguments(predicate)
return Composer.entity(({ type }) => entityTypes.includes(type), ...fns)
}
return Composer.optional((ctx) => {
const message = ctx.message || ctx.channelPost
const entities = message && (message.entities || message.caption_entities)
const text = message && (message.text || message.caption)
return entities && entities.some((entity) =>
predicate(entity, text.substring(entity.offset, entity.offset + entity.length), ctx)
)
}, ...fns)
}
static entityText (entityType, predicate, ...fns) {
if (fns.length === 0) {
return Array.isArray(predicate)
? Composer.entity(entityType, ...predicate)
: Composer.entity(entityType, predicate)
}
const triggers = normalizeTriggers(predicate)
return Composer.entity(({ type }, value, ctx) => {
if (type !== entityType) {
return false
}
for (const trigger of triggers) {
ctx.match = trigger(value, ctx)
if (ctx.match) {
return true
}
}
}, ...fns)
}
static email (email, ...fns) {
return Composer.entityText('email', email, ...fns)
}
static phone (number, ...fns) {
return Composer.entityText('phone_number', number, ...fns)
}
static url (url, ...fns) {
return Composer.entityText('url', url, ...fns)
}
static textLink (link, ...fns) {
return Composer.entityText('text_link', link, ...fns)
}
static textMention (mention, ...fns) {
return Composer.entityText('text_mention', mention, ...fns)
}
static mention (mention, ...fns) {
return Composer.entityText('mention', normalizeTextArguments(mention, '@'), ...fns)
}
static hashtag (hashtag, ...fns) {
return Composer.entityText('hashtag', normalizeTextArguments(hashtag, '#'), ...fns)
}
static cashtag (cashtag, ...fns) {
return Composer.entityText('cashtag', normalizeTextArguments(cashtag, '$'), ...fns)
}
static match (triggers, ...fns) {
return Composer.optional((ctx) => {
const text = (
(ctx.message && (ctx.message.caption || ctx.message.text)) ||
(ctx.callbackQuery && ctx.callbackQuery.data) ||
(ctx.inlineQuery && ctx.inlineQuery.query)
)
for (const trigger of triggers) {
ctx.match = trigger(text, ctx)
if (ctx.match) {
return true
}
}
}, ...fns)
}
static hears (triggers, ...fns) {
return Composer.mount('text', Composer.match(normalizeTriggers(triggers), ...fns))
}
static command (command, ...fns) {
if (fns.length === 0) {
return Composer.entity(['bot_command'], command)
}
const commands = normalizeTextArguments(command, '/')
return Composer.mount('text', Composer.lazy((ctx) => {
const groupCommands = ctx.me && (ctx.chat.type === 'group' || ctx.chat.type === 'supergroup')
? commands.map((command) => `${command}@${ctx.me}`)
: []
return Composer.entity(({ offset, type }, value) =>
offset === 0 &&
type === 'bot_command' &&
(commands.includes(value) || groupCommands.includes(value))
, ...fns)
}))
}
static action (triggers, ...fns) {
return Composer.mount('callback_query', Composer.match(normalizeTriggers(triggers), ...fns))
}
static inlineQuery (triggers, ...fns) {
return Composer.mount('inline_query', Composer.match(normalizeTriggers(triggers), ...fns))
}
static acl (userId, ...fns) {
if (typeof userId === 'function') {
return Composer.optional(userId, ...fns)
}
const allowed = Array.isArray(userId) ? userId : [userId]
return Composer.optional((ctx) => !ctx.from || allowed.includes(ctx.from.id), ...fns)
}
static memberStatus (status, ...fns) {
const statuses = Array.isArray(status) ? status : [status]
return Composer.optional((ctx) => ctx.message && ctx.getChatMember(ctx.message.from.id)
.then(member => member && statuses.includes(member.status))
, ...fns)
}
static admin (...fns) {
return Composer.memberStatus(['administrator', 'creator'], ...fns)
}
static creator (...fns) {
return Composer.memberStatus('creator', ...fns)
}
static chatType (type, ...fns) {
const types = Array.isArray(type) ? type : [type]
return Composer.optional((ctx) => ctx.chat && types.includes(ctx.chat.type), ...fns)
}
static privateChat (...fns) {
return Composer.chatType('private', ...fns)
}
static groupChat (...fns) {
return Composer.chatType(['group', 'supergroup'], ...fns)
}
static gameQuery (...fns) {
return Composer.mount('callback_query', Composer.optional((ctx) => ctx.callbackQuery.game_short_name, ...fns))
}
static unwrap (handler) {
if (!handler) {
throw new Error('Handler is undefined')
}
return typeof handler.middleware === 'function'
? handler.middleware()
: handler
}
static compose (middlewares) {
if (!Array.isArray(middlewares)) {
throw new Error('Middlewares must be an array')
}
if (middlewares.length === 0) {
return Composer.safePassThru()
}
if (middlewares.length === 1) {
return Composer.unwrap(middlewares[0])
}
return (ctx, next) => {
let index = -1
return execute(0, ctx)
function execute (i, context) {
if (!(context instanceof Context)) {
return Promise.reject(new Error('next(ctx) called with invalid context'))
}
if (i <= index) {
return Promise.reject(new Error('next() called multiple times'))
}
index = i
const handler = middlewares[i] ? Composer.unwrap(middlewares[i]) : next
if (!handler) {
return Promise.resolve()
}
try {
return Promise.resolve(
handler(context, (ctx = context) => execute(i + 1, ctx))
)
} catch (err) {
return Promise.reject(err)
}
}
}
}
}
function normalizeTriggers (triggers) {
if (!Array.isArray(triggers)) {
triggers = [triggers]
}
return triggers.map((trigger) => {
if (!trigger) {
throw new Error('Invalid trigger')
}
if (typeof trigger === 'function') {
return trigger
}
if (trigger instanceof RegExp) {
return (value) => {
trigger.lastIndex = 0
return trigger.exec(value || '')
}
}
return (value) => trigger === value ? value : null
})
}
function normalizeTextArguments (argument, prefix) {
const args = Array.isArray(argument) ? argument : [argument]
return args
.filter(Boolean)
.map((arg) => prefix && typeof arg === 'string' && !arg.startsWith(prefix) ? `${prefix}${arg}` : arg)
}
module.exports = Composer
-595
View File
@@ -1,595 +0,0 @@
const UpdateTypes = [
'callback_query',
'channel_post',
'chosen_inline_result',
'edited_channel_post',
'edited_message',
'inline_query',
'shipping_query',
'pre_checkout_query',
'message',
'poll',
'poll_answer'
]
const MessageSubTypes = [
'voice',
'video_note',
'video',
'animation',
'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',
'dice',
'document',
'delete_chat_photo',
'contact',
'channel_chat_created',
'audio',
'connected_website',
'passport_data',
'poll',
'forward_date'
]
const MessageSubTypesMapping = {
forward_date: 'forward'
}
class TelegrafContext {
constructor (update, telegram, options) {
this.tg = telegram
this.update = update
this.options = options
this.updateType = UpdateTypes.find((key) => key in this.update)
if (this.updateType === 'message' || (this.options.channelMode && this.updateType === 'channel_post')) {
this.updateSubTypes = MessageSubTypes
.filter((key) => key in this.update[this.updateType])
.map((type) => MessageSubTypesMapping[type] || type)
} else {
this.updateSubTypes = []
}
Object.getOwnPropertyNames(TelegrafContext.prototype)
.filter((key) => key !== 'constructor' && typeof this[key] === 'function')
.forEach((key) => (this[key] = this[key].bind(this)))
}
get me () {
return this.options && this.options.username
}
get telegram () {
return this.tg
}
get message () {
return this.update.message
}
get editedMessage () {
return this.update.edited_message
}
get inlineQuery () {
return this.update.inline_query
}
get shippingQuery () {
return this.update.shipping_query
}
get preCheckoutQuery () {
return this.update.pre_checkout_query
}
get chosenInlineResult () {
return this.update.chosen_inline_result
}
get channelPost () {
return this.update.channel_post
}
get editedChannelPost () {
return this.update.edited_channel_post
}
get callbackQuery () {
return this.update.callback_query
}
get poll () {
return this.update.poll
}
get pollAnswer () {
return this.update.poll_answer
}
get chat () {
return (this.message && this.message.chat) ||
(this.editedMessage && this.editedMessage.chat) ||
(this.callbackQuery && this.callbackQuery.message && this.callbackQuery.message.chat) ||
(this.channelPost && this.channelPost.chat) ||
(this.editedChannelPost && this.editedChannelPost.chat)
}
get from () {
return (this.message && this.message.from) ||
(this.editedMessage && this.editedMessage.from) ||
(this.callbackQuery && this.callbackQuery.from) ||
(this.inlineQuery && this.inlineQuery.from) ||
(this.channelPost && this.channelPost.from) ||
(this.editedChannelPost && this.editedChannelPost.from) ||
(this.shippingQuery && this.shippingQuery.from) ||
(this.preCheckoutQuery && this.preCheckoutQuery.from) ||
(this.chosenInlineResult && this.chosenInlineResult.from)
}
get inlineMessageId () {
return (this.callbackQuery && this.callbackQuery.inline_message_id) || (this.chosenInlineResult && this.chosenInlineResult.inline_message_id)
}
get passportData () {
return this.message && this.message.passport_data
}
get state () {
if (!this.contextState) {
this.contextState = {}
}
return this.contextState
}
set state (value) {
this.contextState = { ...value }
}
get webhookReply () {
return this.tg.webhookReply
}
set webhookReply (enable) {
this.tg.webhookReply = enable
}
assert (value, method) {
if (!value) {
throw new Error(`Telegraf: "${method}" isn't available for "${this.updateType}::${this.updateSubTypes}"`)
}
}
answerInlineQuery (...args) {
this.assert(this.inlineQuery, 'answerInlineQuery')
return this.telegram.answerInlineQuery(this.inlineQuery.id, ...args)
}
answerCbQuery (...args) {
this.assert(this.callbackQuery, 'answerCbQuery')
return this.telegram.answerCbQuery(this.callbackQuery.id, ...args)
}
answerGameQuery (...args) {
this.assert(this.callbackQuery, 'answerGameQuery')
return this.telegram.answerGameQuery(this.callbackQuery.id, ...args)
}
answerShippingQuery (...args) {
this.assert(this.shippingQuery, 'answerShippingQuery')
return this.telegram.answerShippingQuery(this.shippingQuery.id, ...args)
}
answerPreCheckoutQuery (...args) {
this.assert(this.preCheckoutQuery, 'answerPreCheckoutQuery')
return this.telegram.answerPreCheckoutQuery(this.preCheckoutQuery.id, ...args)
}
editMessageText (text, extra) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageText')
return this.inlineMessageId
? this.telegram.editMessageText(
undefined,
undefined,
this.inlineMessageId,
text,
extra
)
: this.telegram.editMessageText(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
text,
extra
)
}
editMessageCaption (caption, extra) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageCaption')
return this.inlineMessageId
? this.telegram.editMessageCaption(
undefined,
undefined,
this.inlineMessageId,
caption,
extra
)
: this.telegram.editMessageCaption(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
caption,
extra
)
}
editMessageMedia (media, extra) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageMedia')
return this.inlineMessageId
? this.telegram.editMessageMedia(
undefined,
undefined,
this.inlineMessageId,
media,
extra
)
: this.telegram.editMessageMedia(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
media,
extra
)
}
editMessageReplyMarkup (markup) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageReplyMarkup')
return this.inlineMessageId
? this.telegram.editMessageReplyMarkup(
undefined,
undefined,
this.inlineMessageId,
markup
)
: this.telegram.editMessageReplyMarkup(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
markup
)
}
editMessageLiveLocation (latitude, longitude, markup) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageLiveLocation')
return this.inlineMessageId
? this.telegram.editMessageLiveLocation(
latitude,
longitude,
undefined,
undefined,
this.inlineMessageId,
markup
)
: this.telegram.editMessageLiveLocation(
latitude,
longitude,
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
markup
)
}
stopMessageLiveLocation (markup) {
this.assert(this.callbackQuery || this.inlineMessageId, 'stopMessageLiveLocation')
return this.inlineMessageId
? this.telegram.stopMessageLiveLocation(
undefined,
undefined,
this.inlineMessageId,
markup
)
: this.telegram.stopMessageLiveLocation(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
markup
)
}
reply (...args) {
this.assert(this.chat, 'reply')
return this.telegram.sendMessage(this.chat.id, ...args)
}
getChat (...args) {
this.assert(this.chat, 'getChat')
return this.telegram.getChat(this.chat.id, ...args)
}
exportChatInviteLink (...args) {
this.assert(this.chat, 'exportChatInviteLink')
return this.telegram.exportChatInviteLink(this.chat.id, ...args)
}
kickChatMember (...args) {
this.assert(this.chat, 'kickChatMember')
return this.telegram.kickChatMember(this.chat.id, ...args)
}
unbanChatMember (...args) {
this.assert(this.chat, 'unbanChatMember')
return this.telegram.unbanChatMember(this.chat.id, ...args)
}
restrictChatMember (...args) {
this.assert(this.chat, 'restrictChatMember')
return this.telegram.restrictChatMember(this.chat.id, ...args)
}
promoteChatMember (...args) {
this.assert(this.chat, 'promoteChatMember')
return this.telegram.promoteChatMember(this.chat.id, ...args)
}
setChatAdministratorCustomTitle (...args) {
this.assert(this.chat, 'setChatAdministratorCustomTitle')
return this.telegram.setChatAdministratorCustomTitle(this.chat.id, ...args)
}
setChatPhoto (...args) {
this.assert(this.chat, 'setChatPhoto')
return this.telegram.setChatPhoto(this.chat.id, ...args)
}
deleteChatPhoto (...args) {
this.assert(this.chat, 'deleteChatPhoto')
return this.telegram.deleteChatPhoto(this.chat.id, ...args)
}
setChatTitle (...args) {
this.assert(this.chat, 'setChatTitle')
return this.telegram.setChatTitle(this.chat.id, ...args)
}
setChatDescription (...args) {
this.assert(this.chat, 'setChatDescription')
return this.telegram.setChatDescription(this.chat.id, ...args)
}
pinChatMessage (...args) {
this.assert(this.chat, 'pinChatMessage')
return this.telegram.pinChatMessage(this.chat.id, ...args)
}
unpinChatMessage (...args) {
this.assert(this.chat, 'unpinChatMessage')
return this.telegram.unpinChatMessage(this.chat.id, ...args)
}
leaveChat (...args) {
this.assert(this.chat, 'leaveChat')
return this.telegram.leaveChat(this.chat.id, ...args)
}
setChatPermissions (...args) {
this.assert(this.chat, 'setChatPermissions')
return this.telegram.setChatPermissions(this.chat.id, ...args)
}
getChatAdministrators (...args) {
this.assert(this.chat, 'getChatAdministrators')
return this.telegram.getChatAdministrators(this.chat.id, ...args)
}
getChatMember (...args) {
this.assert(this.chat, 'getChatMember')
return this.telegram.getChatMember(this.chat.id, ...args)
}
getChatMembersCount (...args) {
this.assert(this.chat, 'getChatMembersCount')
return this.telegram.getChatMembersCount(this.chat.id, ...args)
}
setPassportDataErrors (errors) {
this.assert(this.chat, 'setPassportDataErrors')
return this.telegram.setPassportDataErrors(this.from.id, errors)
}
replyWithPhoto (...args) {
this.assert(this.chat, 'replyWithPhoto')
return this.telegram.sendPhoto(this.chat.id, ...args)
}
replyWithMediaGroup (...args) {
this.assert(this.chat, 'replyWithMediaGroup')
return this.telegram.sendMediaGroup(this.chat.id, ...args)
}
replyWithAudio (...args) {
this.assert(this.chat, 'replyWithAudio')
return this.telegram.sendAudio(this.chat.id, ...args)
}
replyWithDice (...args) {
this.assert(this.chat, 'replyWithDice')
return this.telegram.sendDice(this.chat.id, ...args)
}
replyWithDocument (...args) {
this.assert(this.chat, 'replyWithDocument')
return this.telegram.sendDocument(this.chat.id, ...args)
}
replyWithSticker (...args) {
this.assert(this.chat, 'replyWithSticker')
return this.telegram.sendSticker(this.chat.id, ...args)
}
replyWithVideo (...args) {
this.assert(this.chat, 'replyWithVideo')
return this.telegram.sendVideo(this.chat.id, ...args)
}
replyWithAnimation (...args) {
this.assert(this.chat, 'replyWithAnimation')
return this.telegram.sendAnimation(this.chat.id, ...args)
}
replyWithVideoNote (...args) {
this.assert(this.chat, 'replyWithVideoNote')
return this.telegram.sendVideoNote(this.chat.id, ...args)
}
replyWithInvoice (...args) {
this.assert(this.chat, 'replyWithInvoice')
return this.telegram.sendInvoice(this.chat.id, ...args)
}
replyWithGame (...args) {
this.assert(this.chat, 'replyWithGame')
return this.telegram.sendGame(this.chat.id, ...args)
}
replyWithVoice (...args) {
this.assert(this.chat, 'replyWithVoice')
return this.telegram.sendVoice(this.chat.id, ...args)
}
replyWithPoll (...args) {
this.assert(this.chat, 'replyWithPoll')
return this.telegram.sendPoll(this.chat.id, ...args)
}
replyWithQuiz (...args) {
this.assert(this.chat, 'replyWithQuiz')
return this.telegram.sendQuiz(this.chat.id, ...args)
}
stopPoll (...args) {
this.assert(this.chat, 'stopPoll')
return this.telegram.stopPoll(this.chat.id, ...args)
}
replyWithChatAction (...args) {
this.assert(this.chat, 'replyWithChatAction')
return this.telegram.sendChatAction(this.chat.id, ...args)
}
replyWithLocation (...args) {
this.assert(this.chat, 'replyWithLocation')
return this.telegram.sendLocation(this.chat.id, ...args)
}
replyWithVenue (...args) {
this.assert(this.chat, 'replyWithVenue')
return this.telegram.sendVenue(this.chat.id, ...args)
}
replyWithContact (...args) {
this.assert(this.from, 'replyWithContact')
return this.telegram.sendContact(this.chat.id, ...args)
}
getStickerSet (setName) {
return this.telegram.getStickerSet(setName)
}
setChatStickerSet (setName) {
this.assert(this.chat, 'setChatStickerSet')
return this.telegram.setChatStickerSet(this.chat.id, setName)
}
deleteChatStickerSet () {
this.assert(this.chat, 'deleteChatStickerSet')
return this.telegram.deleteChatStickerSet(this.chat.id)
}
setStickerPositionInSet (sticker, position) {
return this.telegram.setStickerPositionInSet(sticker, position)
}
setStickerSetThumb (...args) {
return this.telegram.setStickerSetThumb(...args)
}
deleteStickerFromSet (sticker) {
return this.telegram.deleteStickerFromSet(sticker)
}
uploadStickerFile (...args) {
this.assert(this.from, 'uploadStickerFile')
return this.telegram.uploadStickerFile(this.from.id, ...args)
}
createNewStickerSet (...args) {
this.assert(this.from, 'createNewStickerSet')
return this.telegram.createNewStickerSet(this.from.id, ...args)
}
addStickerToSet (...args) {
this.assert(this.from, 'addStickerToSet')
return this.telegram.addStickerToSet(this.from.id, ...args)
}
getMyCommands () {
return this.telegram.getMyCommands()
}
setMyCommands (...args) {
return this.telegram.setMyCommands(...args)
}
replyWithMarkdown (markdown, extra) {
return this.reply(markdown, { parse_mode: 'Markdown', ...extra })
}
replyWithMarkdownV2 (markdown, extra) {
return this.reply(markdown, { parse_mode: 'MarkdownV2', ...extra })
}
replyWithHTML (html, extra) {
return this.reply(html, { parse_mode: 'HTML', ...extra })
}
deleteMessage (messageId) {
this.assert(this.chat, 'deleteMessage')
if (typeof messageId !== 'undefined') {
return this.telegram.deleteMessage(this.chat.id, messageId)
}
const message = this.message ||
this.editedMessage ||
this.channelPost ||
this.editedChannelPost ||
(this.callbackQuery && this.callbackQuery.message)
this.assert(message, 'deleteMessage')
return this.telegram.deleteMessage(this.chat.id, message.message_id)
}
forwardMessage (chatId, extra) {
this.assert(this.chat, 'forwardMessage')
const message = this.message ||
this.editedMessage ||
this.channelPost ||
this.editedChannelPost ||
(this.callbackQuery && this.callbackQuery.message)
this.assert(message, 'forwardMessage')
return this.telegram.forwardMessage(chatId, this.chat.id, message.message_id, extra)
}
}
module.exports = TelegrafContext
-288
View File
@@ -1,288 +0,0 @@
const debug = require('debug')('telegraf:client')
const crypto = require('crypto')
const fetch = require('node-fetch').default
const fs = require('fs')
const https = require('https')
const path = require('path')
const TelegramError = require('./error')
const MultipartStream = require('./multipart-stream')
const { isStream } = MultipartStream
const WEBHOOK_BLACKLIST = [
'getChat',
'getChatAdministrators',
'getChatMember',
'getChatMembersCount',
'getFile',
'getFileLink',
'getGameHighScores',
'getMe',
'getUserProfilePhotos',
'getWebhookInfo',
'exportChatInviteLink'
]
const DEFAULT_EXTENSIONS = {
audio: 'mp3',
photo: 'jpg',
sticker: 'webp',
video: 'mp4',
animation: 'mp4',
video_note: 'mp4',
voice: 'ogg'
}
const DEFAULT_OPTIONS = {
apiRoot: 'https://api.telegram.org',
webhookReply: true,
agent: new https.Agent({
keepAlive: true,
keepAliveMsecs: 10000
})
}
const WEBHOOK_REPLY_STUB = {
webhook: true,
details: 'https://core.telegram.org/bots/api#making-requests-when-getting-updates'
}
function safeJSONParse (text) {
try {
return JSON.parse(text)
} catch (err) {
debug('JSON parse failed', err)
}
}
function includesMedia (payload) {
return Object.keys(payload).some(
(key) => {
const value = payload[key]
if (Array.isArray(value)) {
return value.some(({ media }) => media && typeof media === 'object' && (media.source || media.url))
}
return (typeof value === 'object') && (
value.source ||
value.url ||
(typeof value.media === 'object' && (value.media.source || value.media.url))
)
}
)
}
function buildJSONConfig (payload) {
return Promise.resolve({
method: 'POST',
compress: true,
headers: { 'content-type': 'application/json', connection: 'keep-alive' },
body: JSON.stringify(payload)
})
}
const FORM_DATA_JSON_FIELDS = [
'results',
'reply_markup',
'mask_position',
'shipping_options',
'errors'
]
function buildFormDataConfig (payload, agent) {
for (const field of FORM_DATA_JSON_FIELDS) {
if (field in payload && typeof payload[field] !== 'string') {
payload[field] = JSON.stringify(payload[field])
}
}
const boundary = crypto.randomBytes(32).toString('hex')
const formData = new MultipartStream(boundary)
const tasks = Object.keys(payload).map((key) => attachFormValue(formData, key, payload[key], agent))
return Promise.all(tasks).then(() => {
return {
method: 'POST',
compress: true,
headers: { 'content-type': `multipart/form-data; boundary=${boundary}`, connection: 'keep-alive' },
body: formData
}
})
}
function attachFormValue (form, id, value, agent) {
if (!value) {
return Promise.resolve()
}
const valueType = typeof value
if (valueType === 'string' || valueType === 'boolean' || valueType === 'number') {
form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"` },
body: `${value}`
})
return Promise.resolve()
}
if (id === 'thumb') {
const attachmentId = crypto.randomBytes(16).toString('hex')
return attachFormMedia(form, value, attachmentId, agent)
.then(() => form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"` },
body: `attach://${attachmentId}`
}))
}
if (Array.isArray(value)) {
return Promise.all(
value.map((item) => {
if (typeof item.media !== 'object') {
return Promise.resolve(item)
}
const attachmentId = crypto.randomBytes(16).toString('hex')
return attachFormMedia(form, item.media, attachmentId, agent)
.then(() => ({ ...item, media: `attach://${attachmentId}` }))
})
).then((items) => form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"` },
body: JSON.stringify(items)
}))
}
if (typeof value.media !== 'undefined' && typeof value.type !== 'undefined') {
const attachmentId = crypto.randomBytes(16).toString('hex')
return attachFormMedia(form, value.media, attachmentId, agent)
.then(() => form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"` },
body: JSON.stringify({
...value,
media: `attach://${attachmentId}`
})
}))
}
return attachFormMedia(form, value, id, agent)
}
function attachFormMedia (form, media, id, agent) {
let fileName = media.filename || `${id}.${DEFAULT_EXTENSIONS[id] || 'dat'}`
if (media.url) {
return fetch(media.url, { agent }).then((res) =>
form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"; filename="${fileName}"` },
body: res.body
})
)
}
if (media.source) {
if (fs.existsSync(media.source)) {
fileName = media.filename || path.basename(media.source)
media.source = fs.createReadStream(media.source)
}
if (isStream(media.source) || Buffer.isBuffer(media.source)) {
form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"; filename="${fileName}"` },
body: media.source
})
}
}
return Promise.resolve()
}
function isKoaResponse (response) {
return typeof response.set === 'function' && typeof response.header === 'object'
}
function answerToWebhook (response, payload = {}, options) {
if (!includesMedia(payload)) {
if (isKoaResponse(response)) {
response.body = payload
return Promise.resolve(WEBHOOK_REPLY_STUB)
}
if (!response.headersSent) {
response.setHeader('content-type', 'application/json')
}
return new Promise((resolve) => {
if (response.end.length === 2) {
response.end(JSON.stringify(payload), 'utf-8')
return resolve(WEBHOOK_REPLY_STUB)
}
response.end(JSON.stringify(payload), 'utf-8', () => resolve(WEBHOOK_REPLY_STUB))
})
}
return buildFormDataConfig(payload, options.agent)
.then(({ headers, body }) => {
if (isKoaResponse(response)) {
Object.keys(headers).forEach(key => response.set(key, headers[key]))
response.body = body
return Promise.resolve(WEBHOOK_REPLY_STUB)
}
if (!response.headersSent) {
Object.keys(headers).forEach(key => response.setHeader(key, headers[key]))
}
return new Promise((resolve) => {
response.on('finish', () => resolve(WEBHOOK_REPLY_STUB))
body.pipe(response)
})
})
}
class ApiClient {
constructor (token, options, webhookResponse) {
this.token = token
this.options = {
...DEFAULT_OPTIONS,
...options
}
if (this.options.apiRoot.startsWith('http://')) {
this.options.agent = null
}
this.response = webhookResponse
}
set webhookReply (enable) {
this.options.webhookReply = enable
}
get webhookReply () {
return this.options.webhookReply
}
callApi (method, data = {}) {
const { token, options, response, responseEnd } = this
const payload = Object.keys(data)
.filter((key) => typeof data[key] !== 'undefined' && data[key] !== null)
.reduce((acc, key) => ({ ...acc, [key]: data[key] }), {})
if (options.webhookReply && response && !responseEnd && !WEBHOOK_BLACKLIST.includes(method)) {
debug('Call via webhook', method, payload)
this.responseEnd = true
return answerToWebhook(response, { method, ...payload }, options)
}
if (!token) {
throw new TelegramError({ error_code: 401, description: 'Bot Token is required' })
}
debug('HTTP call', method, payload)
const buildConfig = includesMedia(payload)
? buildFormDataConfig({ method, ...payload }, options.agent)
: buildJSONConfig(payload)
return buildConfig
.then((config) => {
const apiUrl = `${options.apiRoot}/bot${token}/${method}`
config.agent = options.agent
return fetch(apiUrl, config)
})
.then((res) => res.text())
.then((text) => {
return safeJSONParse(text) || {
error_code: 500,
description: 'Unsupported http response from Telegram',
response: text
}
})
.then((data) => {
if (!data.ok) {
debug('API call failed', data)
throw new TelegramError(data, { method, payload })
}
return data.result
})
}
}
module.exports = ApiClient
-12
View File
@@ -1,12 +0,0 @@
class TelegramError extends Error {
constructor (payload = {}, on) {
super(`${payload.error_code}: ${payload.description}`)
this.code = payload.error_code
this.response = payload
this.description = payload.description
this.parameters = payload.parameters || {}
this.on = on || {}
}
}
module.exports = TelegramError
-37
View File
@@ -1,37 +0,0 @@
const stream = require('stream')
const { SandwichStream } = require('sandwich-stream')
const CRNL = '\r\n'
class MultipartStream extends SandwichStream {
constructor (boundary) {
super({
head: `--${boundary}${CRNL}`,
tail: `${CRNL}--${boundary}--`,
separator: `${CRNL}--${boundary}${CRNL}`
})
}
addPart (part) {
part = part || {}
const partStream = new stream.PassThrough()
if (part.headers) {
for (const key in part.headers) {
const header = part.headers[key]
partStream.write(`${key}:${header}${CRNL}`)
}
}
partStream.write(CRNL)
if (MultipartStream.isStream(part.body)) {
part.body.pipe(partStream)
} else {
partStream.end(part.body)
}
this.add(partStream)
}
static isStream (stream) {
return stream && typeof stream === 'object' && typeof stream.pipe === 'function'
}
}
module.exports = MultipartStream
-39
View File
@@ -1,39 +0,0 @@
const debug = require('debug')('telegraf:webhook')
module.exports = function (hookPath, updateHandler, errorHandler) {
return (req, res, next) => {
debug('Incoming request', req.method, req.url)
if (req.method !== 'POST' || req.url !== hookPath) {
if (typeof next === 'function') {
return next()
}
res.statusCode = 403
return res.end()
}
let body = ''
req.on('data', (chunk) => {
body += chunk.toString()
})
req.on('end', () => {
let update = {}
try {
update = JSON.parse(body)
} catch (error) {
res.writeHead(415)
res.end()
return errorHandler(error)
}
updateHandler(update, res)
.then(() => {
if (!res.finished) {
res.end()
}
})
.catch((err) => {
debug('Webhook error', err)
res.writeHead(500)
res.end()
})
})
}
}
-140
View File
@@ -1,140 +0,0 @@
const { formatHTML } = require('../markup')
module.exports = {
copyMethods: {
audio: 'sendAudio',
contact: 'sendContact',
document: 'sendDocument',
location: 'sendLocation',
photo: 'sendPhoto',
sticker: 'sendSticker',
text: 'sendMessage',
venue: 'sendVenue',
video: 'sendVideo',
video_note: 'sendVideoNote',
animation: 'sendAnimation',
voice: 'sendVoice',
poll: 'sendPoll'
},
text: (message) => {
const entities = message.entities || []
return {
reply_markup: message.reply_markup,
parse_mode: entities.length > 0 ? 'HTML' : '',
text: formatHTML(message.text, entities)
}
},
contact: (message) => {
return {
reply_markup: message.reply_markup,
phone_number: message.contact.phone_number,
first_name: message.contact.first_name,
last_name: message.contact.last_name
}
},
location: (message) => {
return {
reply_markup: message.reply_markup,
latitude: message.location.latitude,
longitude: message.location.longitude
}
},
venue: (message) => {
return {
reply_markup: message.reply_markup,
latitude: message.venue.location.latitude,
longitude: message.venue.location.longitude,
title: message.venue.title,
address: message.venue.address,
foursquare_id: message.venue.foursquare_id
}
},
voice: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
voice: message.voice.file_id,
duration: message.voice.duration,
caption: formatHTML(message.caption, entities),
parse_mode: entities.length > 0 ? 'HTML' : ''
}
},
audio: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
audio: message.audio.file_id,
thumb: message.audio.thumb,
duration: message.audio.duration,
performer: message.audio.performer,
title: message.audio.title,
caption: formatHTML(message.caption, entities),
parse_mode: entities.length > 0 ? 'HTML' : ''
}
},
video: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
video: message.video.file_id,
thumb: message.video.thumb,
caption: formatHTML(message.caption, entities),
parse_mode: entities.length > 0 ? 'HTML' : '',
duration: message.video.duration,
width: message.video.width,
height: message.video.height,
supports_streaming: !!message.video.supports_streaming
}
},
document: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
document: message.document.file_id,
caption: formatHTML(message.caption, entities),
parse_mode: entities.length > 0 ? 'HTML' : ''
}
},
sticker: (message) => {
return {
reply_markup: message.reply_markup,
sticker: message.sticker.file_id
}
},
photo: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
photo: message.photo[message.photo.length - 1].file_id,
parse_mode: entities.length > 0 ? 'HTML' : '',
caption: formatHTML(message.caption, entities)
}
},
video_note: (message) => {
return {
reply_markup: message.reply_markup,
video_note: message.video_note.file_id,
thumb: message.video_note.thumb,
length: message.video_note.length,
duration: message.video_note.duration
}
},
animation: (message) => {
return {
reply_markup: message.reply_markup,
animation: message.animation.file_id,
thumb: message.animation.thumb,
duration: message.animation.duration
}
},
poll: (message) => {
return {
question: message.poll.question,
type: message.poll.type,
is_anonymous: message.poll.is_anonymous,
allows_multiple_answers: message.poll.allows_multiple_answers,
correct_option_id: message.poll.correct_option_id,
options: message.poll.options.map(({ text }) => text)
}
}
}
-85
View File
@@ -1,85 +0,0 @@
const Markup = require('./markup')
class Extra {
constructor (opts) {
this.load(opts)
}
load (opts = {}) {
return Object.assign(this, opts)
}
inReplyTo (messageId) {
this.reply_to_message_id = messageId
return this
}
notifications (value = true) {
this.disable_notification = !value
return this
}
webPreview (value = true) {
this.disable_web_page_preview = !value
return this
}
markup (markup) {
if (typeof markup === 'function') {
markup = markup(new Markup())
}
this.reply_markup = { ...markup }
return this
}
HTML (value = true) {
this.parse_mode = value ? 'HTML' : undefined
return this
}
markdown (value = true) {
this.parse_mode = value ? 'Markdown' : undefined
return this
}
caption (caption = '') {
this.caption = caption
return this
}
static inReplyTo (messageId) {
return new Extra().inReplyTo(messageId)
}
static notifications (value) {
return new Extra().notifications(value)
}
static webPreview (value) {
return new Extra().webPreview(value)
}
static load (opts) {
return new Extra(opts)
}
static markup (markup) {
return new Extra().markup(markup)
}
static HTML (value) {
return new Extra().HTML(value)
}
static markdown (value) {
return new Extra().markdown(value)
}
static caption (caption) {
return new Extra().caption(caption)
}
}
Extra.Markup = Markup
module.exports = Extra
-282
View File
@@ -1,282 +0,0 @@
class Markup {
forceReply (value = true) {
this.force_reply = value
return this
}
removeKeyboard (value = true) {
this.remove_keyboard = value
return this
}
selective (value = true) {
this.selective = value
return this
}
extra (options) {
return {
reply_markup: { ...this },
...options
}
}
keyboard (buttons, options) {
const keyboard = buildKeyboard(buttons, { columns: 1, ...options })
if (keyboard && keyboard.length > 0) {
this.keyboard = keyboard
}
return this
}
resize (value = true) {
this.resize_keyboard = value
return this
}
oneTime (value = true) {
this.one_time_keyboard = value
return this
}
inlineKeyboard (buttons, options) {
const keyboard = buildKeyboard(buttons, { columns: buttons.length, ...options })
if (keyboard && keyboard.length > 0) {
this.inline_keyboard = keyboard
}
return this
}
button (text, hide) {
return Markup.button(text, hide)
}
contactRequestButton (text, hide) {
return Markup.contactRequestButton(text, hide)
}
locationRequestButton (text, hide) {
return Markup.locationRequestButton(text, hide)
}
urlButton (text, url, hide) {
return Markup.urlButton(text, url, hide)
}
callbackButton (text, data, hide) {
return Markup.callbackButton(text, data, hide)
}
switchToChatButton (text, value, hide) {
return Markup.switchToChatButton(text, value, hide)
}
switchToCurrentChatButton (text, value, hide) {
return Markup.switchToCurrentChatButton(text, value, hide)
}
gameButton (text, hide) {
return Markup.gameButton(text, hide)
}
payButton (text, hide) {
return Markup.payButton(text, hide)
}
loginButton (text, url, opts, hide) {
return Markup.loginButton(text, url, opts, hide)
}
static removeKeyboard (value) {
return new Markup().removeKeyboard(value)
}
static forceReply (value) {
return new Markup().forceReply(value)
}
static keyboard (buttons, options) {
return new Markup().keyboard(buttons, options)
}
static inlineKeyboard (buttons, options) {
return new Markup().inlineKeyboard(buttons, options)
}
static resize (value = true) {
return new Markup().resize(value)
}
static selective (value = true) {
return new Markup().selective(value)
}
static oneTime (value = true) {
return new Markup().oneTime(value)
}
static button (text, hide = false) {
return { text: text, hide: hide }
}
static contactRequestButton (text, hide = false) {
return { text: text, request_contact: true, hide: hide }
}
static locationRequestButton (text, hide = false) {
return { text: text, request_location: true, hide: hide }
}
static pollRequestButton (text, type, hide = false) {
return { text: text, request_poll: { type }, hide: hide }
}
static urlButton (text, url, hide = false) {
return { text: text, url: url, hide: hide }
}
static callbackButton (text, data, hide = false) {
return { text: text, callback_data: data, hide: hide }
}
static switchToChatButton (text, value, hide = false) {
return { text: text, switch_inline_query: value, hide: hide }
}
static switchToCurrentChatButton (text, value, hide = false) {
return { text: text, switch_inline_query_current_chat: value, hide: hide }
}
static gameButton (text, hide = false) {
return { text: text, callback_game: {}, hide: hide }
}
static payButton (text, hide = false) {
return { text: text, pay: true, hide: hide }
}
static loginButton (text, url, opts = {}, hide = false) {
return {
text: text,
login_url: { ...opts, url: url },
hide: hide
}
}
static formatHTML (text = '', entities = []) {
const chars = [...text]
const available = [...entities]
const opened = []
const result = []
for (let offset = 0; offset < chars.length; offset++) {
while (true) {
const index = available.findIndex((entity) => entity.offset === offset)
if (index === -1) {
break
}
const entity = available[index]
switch (entity.type) {
case 'bold':
result.push('<b>')
break
case 'italic':
result.push('<i>')
break
case 'code':
result.push('<code>')
break
case 'pre':
if (entity.language) {
result.push(`<pre><code class="language-${entity.language}">`)
} else {
result.push('<pre>')
}
break
case 'strikethrough':
result.push('<s>')
break
case 'underline':
result.push('<u>')
break
case 'text_mention':
result.push(`<a href="tg://user?id=${entity.user.id}">`)
break
case 'text_link':
result.push(`<a href="${entity.url}">`)
break
}
opened.unshift(entity)
available.splice(index, 1)
}
result.push(chars[offset])
while (true) {
const index = opened.findIndex((entity) => entity.offset + entity.length - 1 === offset)
if (index === -1) {
break
}
const entity = opened[index]
switch (entity.type) {
case 'bold':
result.push('</b>')
break
case 'italic':
result.push('</i>')
break
case 'code':
result.push('</code>')
break
case 'pre':
if (entity.language) {
result.push('</code></pre>')
} else {
result.push('</pre>')
}
break
case 'strikethrough':
result.push('</s>')
break
case 'underline':
result.push('</u>')
break
case 'text_mention':
case 'text_link':
result.push('</a>')
break
}
opened.splice(index, 1)
}
}
return result.join('')
}
}
function buildKeyboard (buttons, options) {
const result = []
if (!Array.isArray(buttons)) {
return result
}
if (buttons.find(Array.isArray)) {
return buttons.map(row => row.filter((button) => !button.hide))
}
const wrapFn = options.wrap
? options.wrap
: (btn, index, currentRow) => currentRow.length >= options.columns
let currentRow = []
let index = 0
for (const btn of buttons.filter((button) => !button.hide)) {
if (wrapFn(btn, index, currentRow) && currentRow.length > 0) {
result.push(currentRow)
currentRow = []
}
currentRow.push(btn)
index++
}
if (currentRow.length > 0) {
result.push(currentRow)
}
return result
}
module.exports = Markup
-95
View File
@@ -1,95 +0,0 @@
{
"_from": "telegraf@^3.37.0",
"_id": "telegraf@3.38.0",
"_inBundle": false,
"_integrity": "sha512-va4VlrKWp64JrowFoZX/NPzzA6q38kvaIukVXOWFO1V+jR1G8+hCfgJy4TX8Z3rwLJzwaBEet1QhikHDRZWl3A==",
"_location": "/telegraf",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "telegraf@^3.37.0",
"name": "telegraf",
"escapedName": "telegraf",
"rawSpec": "^3.37.0",
"saveSpec": null,
"fetchSpec": "^3.37.0"
},
"_requiredBy": [
"/"
],
"_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",
"author": {
"name": "Vitaly Domnikov",
"email": "oss@vitaly.codes"
},
"bin": {
"telegraf": "./bin/telegraf"
},
"bugs": {
"url": "https://github.com/telegraf/telegraf/issues"
},
"bundleDependencies": false,
"dependencies": {
"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"
},
"deprecated": false,
"description": "Modern Telegram Bot Framework",
"devDependencies": {
"@types/node": "^13.1.0",
"ava": "^3.0.0",
"eslint": "^6.2.2",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-ava": "^10.0.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-promise": "^4.0.0",
"eslint-plugin-standard": "^4.0.0",
"husky": "^4.2.0",
"prettier": "^2.0.5",
"typescript": "^3.0.1"
},
"engines": {
"node": ">=8"
},
"files": [
"bin/*",
"core/**/*.js",
"scenes/**/*.js",
"typings/*.d.ts",
"*.js"
],
"homepage": "https://github.com/telegraf/telegraf#readme",
"keywords": [
"telegraf",
"telegram",
"telegram bot api",
"bot",
"botapi",
"bot framework"
],
"license": "MIT",
"main": "telegraf.js",
"name": "telegraf",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/telegraf/telegraf.git"
},
"scripts": {
"lint": "eslint .",
"precommit": "npm run lint && npm run typecheck && npm test",
"test": "ava test/*",
"typecheck": "tsc"
},
"type": "commonjs",
"types": "./typings/index.d.ts",
"version": "3.38.0"
}
-43
View File
@@ -1,43 +0,0 @@
const { compose, lazy, passThru } = require('./composer')
class Router {
constructor (routeFn, handlers = new Map()) {
if (!routeFn) {
throw new Error('Missing routing function')
}
this.routeFn = routeFn
this.handlers = handlers
this.otherwiseHandler = passThru()
}
on (route, ...fns) {
if (fns.length === 0) {
throw new TypeError('At least one handler must be provided')
}
this.handlers.set(route, compose(fns))
return this
}
otherwise (...fns) {
if (fns.length === 0) {
throw new TypeError('At least one otherwise handler must be provided')
}
this.otherwiseHandler = compose(fns)
return this
}
middleware () {
return lazy((ctx) => {
return Promise.resolve(this.routeFn(ctx)).then((result) => {
if (!result || !result.route || !this.handlers.has(result.route)) {
return this.otherwiseHandler
}
Object.assign(ctx, result.context)
Object.assign(ctx.state, result.state)
return this.handlers.get(result.route)
})
})
}
}
module.exports = Router
-46
View File
@@ -1,46 +0,0 @@
const Composer = require('../composer')
const { compose } = Composer
class BaseScene extends Composer {
constructor (id, options) {
const opts = {
handlers: [],
enterHandlers: [],
leaveHandlers: [],
...options
}
super(...opts.handlers)
this.id = id
this.options = opts
this.enterHandler = compose(opts.enterHandlers)
this.leaveHandler = compose(opts.leaveHandlers)
}
set ttl (value) {
this.options.ttl = value
}
get ttl () {
return this.options.ttl
}
enter (...fns) {
this.enterHandler = compose([this.enterHandler, ...fns])
return this
}
leave (...fns) {
this.leaveHandler = compose([this.leaveHandler, ...fns])
return this
}
enterMiddleware () {
return this.enterHandler
}
leaveMiddleware () {
return this.leaveHandler
}
}
module.exports = BaseScene
-79
View File
@@ -1,79 +0,0 @@
const debug = require('debug')('telegraf:scenes:context')
const { safePassThru } = require('../composer')
const noop = () => Promise.resolve()
const now = () => Math.floor(Date.now() / 1000)
class SceneContext {
constructor (ctx, scenes, options) {
this.ctx = ctx
this.scenes = scenes
this.options = options
}
get session () {
const sessionName = this.options.sessionName
let session = this.ctx[sessionName].__scenes || {}
if (session.expires < now()) {
session = {}
}
this.ctx[sessionName].__scenes = session
return session
}
get state () {
this.session.state = this.session.state || {}
return this.session.state
}
set state (value) {
this.session.state = { ...value }
}
get current () {
const sceneId = this.session.current || this.options.default
return (sceneId && this.scenes.has(sceneId)) ? this.scenes.get(sceneId) : null
}
reset () {
const sessionName = this.options.sessionName
delete this.ctx[sessionName].__scenes
}
enter (sceneId, initialState, silent) {
if (!sceneId || !this.scenes.has(sceneId)) {
throw new Error(`Can't find scene: ${sceneId}`)
}
const leave = silent ? noop() : this.leave()
return leave.then(() => {
debug('Enter scene', sceneId, initialState, silent)
this.session.current = sceneId
this.state = initialState
const ttl = this.current.ttl || this.options.ttl
if (ttl) {
this.session.expires = now() + ttl
}
if (silent) {
return Promise.resolve()
}
const handler = typeof this.current.enterMiddleware === 'function'
? this.current.enterMiddleware()
: this.current.middleware()
return handler(this.ctx, noop)
})
}
reenter () {
return this.enter(this.session.current, this.state)
}
leave () {
debug('Leave scene')
const handler = this.current && this.current.leaveMiddleware
? this.current.leaveMiddleware()
: safePassThru()
return handler(this.ctx, noop).then(() => this.reset())
}
}
module.exports = SceneContext
-28
View File
@@ -1,28 +0,0 @@
class WizardContext {
constructor (ctx, steps) {
this.ctx = ctx
this.steps = steps
this.state = ctx.scene.state
this.cursor = ctx.scene.session.cursor || 0
}
get step () {
return this.cursor >= 0 && this.steps[this.cursor]
}
selectStep (index) {
this.cursor = index
this.ctx.scene.session.cursor = index
return this
}
next () {
return this.selectStep(this.cursor + 1)
}
back () {
return this.selectStep(this.cursor - 1)
}
}
module.exports = WizardContext
-51
View File
@@ -1,51 +0,0 @@
const Composer = require('../../composer')
const WizardContext = require('./context')
const { compose, unwrap } = Composer
class WizardScene extends Composer {
constructor (id, options, ...steps) {
super()
this.id = id
this.options = typeof options === 'function'
? { steps: [options, ...steps], leaveHandlers: [] }
: { steps: steps, leaveHandlers: [], ...options }
this.leaveHandler = compose(this.options.leaveHandlers)
}
set ttl (value) {
this.options.ttl = value
}
get ttl () {
return this.options.ttl
}
leave (...fns) {
this.leaveHandler = compose([this.leaveHandler, ...fns])
return this
}
leaveMiddleware () {
return this.leaveHandler
}
middleware () {
return compose([
(ctx, next) => {
const wizard = new WizardContext(ctx, this.options.steps)
ctx.wizard = wizard
return next()
},
super.middleware(),
(ctx, next) => {
if (!ctx.wizard.step) {
ctx.wizard.selectStep(0)
return ctx.scene.leave()
}
return unwrap(ctx.wizard.step)(ctx, next)
}
])
}
}
module.exports = WizardScene
-33
View File
@@ -1,33 +0,0 @@
module.exports = function (opts) {
const options = {
property: 'session',
store: new Map(),
getSessionKey: (ctx) => ctx.from && ctx.chat && `${ctx.from.id}:${ctx.chat.id}`,
...opts
}
const ttlMs = options.ttl && options.ttl * 1000
return (ctx, next) => {
const key = options.getSessionKey(ctx)
if (!key) {
return next(ctx)
}
const now = Date.now()
return Promise.resolve(options.store.get(key))
.then((state) => state || { session: {} })
.then(({ session, expires }) => {
if (expires && expires < now) {
session = {}
}
Object.defineProperty(ctx, options.property, {
get: function () { return session },
set: function (newValue) { session = { ...newValue } }
})
return next(ctx).then(() => options.store.set(key, {
session,
expires: ttlMs ? now + ttlMs : null
}))
})
}
}
-51
View File
@@ -1,51 +0,0 @@
const SceneContext = require('./scenes/context')
const Composer = require('./composer')
const { compose, optional, lazy, safePassThru } = Composer
class Stage extends Composer {
constructor (scenes = [], options) {
super()
this.options = {
sessionName: 'session',
...options
}
this.scenes = new Map()
scenes.forEach((scene) => this.register(scene))
}
register (...scenes) {
scenes.forEach((scene) => {
if (!scene || !scene.id || typeof scene.middleware !== 'function') {
throw new Error('telegraf: Unsupported scene')
}
this.scenes.set(scene.id, scene)
})
return this
}
middleware () {
const handler = compose([
(ctx, next) => {
ctx.scene = new SceneContext(ctx, this.scenes, this.options)
return next()
},
super.middleware(),
lazy((ctx) => ctx.scene.current || safePassThru())
])
return optional((ctx) => ctx[this.options.sessionName], handler)
}
static enter (...args) {
return (ctx) => ctx.scene.enter(...args)
}
static reenter (...args) {
return (ctx) => ctx.scene.reenter(...args)
}
static leave (...args) {
return (ctx) => ctx.scene.leave(...args)
}
}
module.exports = Stage
-221
View File
@@ -1,221 +0,0 @@
const debug = require('debug')('telegraf:core')
const Telegram = require('./telegram')
const Extra = require('./extra')
const Composer = require('./composer')
const Markup = require('./markup')
const session = require('./session')
const Router = require('./router')
const Stage = require('./stage')
const BaseScene = require('./scenes/base')
const Context = require('./context')
const generateCallback = require('./core/network/webhook')
const crypto = require('crypto')
const { URL } = require('url')
const DEFAULT_OPTIONS = {
retryAfter: 1,
handlerTimeout: 0,
contextType: Context
}
const noop = () => { }
class Telegraf extends Composer {
constructor (token, options) {
super()
this.options = {
...DEFAULT_OPTIONS,
...options
}
this.token = token
this.handleError = (err) => {
console.error()
console.error((err.stack || err.toString()).replace(/^/gm, ' '))
console.error()
throw err
}
this.context = {}
this.polling = {
offset: 0,
started: false
}
}
set token (token) {
this.telegram = new Telegram(token, this.telegram
? this.telegram.options
: this.options.telegram
)
}
get token () {
return this.telegram.token
}
set webhookReply (webhookReply) {
this.telegram.webhookReply = webhookReply
}
get webhookReply () {
return this.telegram.webhookReply
}/* eslint brace-style: 0 */
catch (handler) {
this.handleError = handler
return this
}
webhookCallback (path = '/') {
return generateCallback(path, (update, res) => this.handleUpdate(update, res), debug)
}
startPolling (timeout = 30, limit = 100, allowedUpdates, stopCallback = noop) {
this.polling.timeout = timeout
this.polling.limit = limit
this.polling.allowedUpdates = allowedUpdates
? Array.isArray(allowedUpdates) ? allowedUpdates : [`${allowedUpdates}`]
: null
this.polling.stopCallback = stopCallback
if (!this.polling.started) {
this.polling.started = true
this.fetchUpdates()
}
return this
}
startWebhook (hookPath, tlsOptions, port, host, cb) {
const webhookCb = this.webhookCallback(hookPath)
const callback = cb && typeof cb === 'function'
? (req, res) => webhookCb(req, res, () => cb(req, res))
: webhookCb
this.webhookServer = tlsOptions
? require('https').createServer(tlsOptions, callback)
: require('http').createServer(callback)
this.webhookServer.listen(port, host, () => {
debug('Webhook listening on port: %s', port)
})
return this
}
launch (config = {}) {
debug('Connecting to Telegram')
return this.telegram.getMe()
.then((botInfo) => {
debug(`Launching @${botInfo.username}`)
this.options.username = botInfo.username
this.context.botInfo = botInfo
if (!config.webhook) {
const { timeout, limit, allowedUpdates, stopCallback } = config.polling || {}
return this.telegram.deleteWebhook()
.then(() => this.startPolling(timeout, limit, allowedUpdates, stopCallback))
.then(() => debug('Bot started with long-polling'))
}
if (typeof config.webhook.domain !== 'string' && typeof config.webhook.hookPath !== 'string') {
throw new Error('Webhook domain or webhook path is required')
}
let domain = config.webhook.domain || ''
if (domain.startsWith('https://') || domain.startsWith('http://')) {
domain = new URL(domain).host
}
const hookPath = config.webhook.hookPath || `/telegraf/${crypto.randomBytes(32).toString('hex')}`
const { port, host, tlsOptions, cb } = config.webhook
this.startWebhook(hookPath, tlsOptions, port, host, cb)
if (!domain) {
debug('Bot started with webhook')
return
}
return this.telegram
.setWebhook(`https://${domain}${hookPath}`)
.then(() => debug(`Bot started with webhook @ https://${domain}`))
})
.catch((err) => {
console.error('Launch failed')
console.error(err.stack || err.toString())
})
}
stop (cb = noop) {
debug('Stopping bot...')
return new Promise((resolve) => {
const done = () => resolve() & cb()
if (this.webhookServer) {
return this.webhookServer.close(done)
} else if (!this.polling.started) {
return done()
}
this.polling.stopCallback = done
this.polling.started = false
})
}
handleUpdates (updates) {
if (!Array.isArray(updates)) {
return Promise.reject(new Error('Updates must be an array'))
}
const processAll = Promise.all(updates.map((update) => this.handleUpdate(update)))
if (this.options.handlerTimeout === 0) {
return processAll
}
return Promise.race([
processAll,
new Promise((resolve) => setTimeout(resolve, this.options.handlerTimeout))
])
}
handleUpdate (update, webhookResponse) {
debug('Processing update', update.update_id)
const tg = new Telegram(this.token, this.telegram.options, webhookResponse)
const TelegrafContext = this.options.contextType
const ctx = new TelegrafContext(update, tg, this.options)
Object.assign(ctx, this.context)
return this.middleware()(ctx).catch((err) => this.handleError(err, ctx))
}
fetchUpdates () {
if (!this.polling.started) {
this.polling.stopCallback && this.polling.stopCallback()
return
}
const { timeout, limit, offset, allowedUpdates } = this.polling
this.telegram.getUpdates(timeout, limit, offset, allowedUpdates)
.catch((err) => {
if (err.code === 401 || err.code === 409) {
throw err
}
const wait = (err.parameters && err.parameters.retry_after) || this.options.retryAfter
console.error(`Failed to fetch updates. Waiting: ${wait}s`, err.message)
return new Promise((resolve) => setTimeout(resolve, wait * 1000, []))
})
.then((updates) => this.polling.started
? this.handleUpdates(updates).then(() => updates)
: []
)
.catch((err) => {
console.error('Failed to process updates.', err)
this.polling.started = false
this.polling.offset = 0
this.polling.stopCallback && this.polling.stopCallback()
return []
})
.then((updates) => {
if (updates.length > 0) {
this.polling.offset = updates[updates.length - 1].update_id + 1
}
this.fetchUpdates()
})
}
}
module.exports = Object.assign(Telegraf, {
Context,
Composer,
default: Telegraf,
Extra,
Markup,
Router,
Telegraf,
Telegram,
Stage,
BaseScene,
session
})
-433
View File
@@ -1,433 +0,0 @@
const replicators = require('./core/replicators')
const ApiClient = require('./core/network/client')
class Telegram extends ApiClient {
getMe () {
return this.callApi('getMe')
}
getFile (fileId) {
return this.callApi('getFile', { file_id: fileId })
}
getFileLink (fileId) {
return Promise.resolve(fileId)
.then((fileId) => {
if (fileId && fileId.file_path) {
return fileId
}
const id = fileId && fileId.file_id ? fileId.file_id : fileId
return this.getFile(id)
})
.then((file) => `${this.options.apiRoot}/file/bot${this.token}/${file.file_path}`)
}
getUpdates (timeout, limit, offset, allowedUpdates) {
const url = `getUpdates?offset=${offset}&limit=${limit}&timeout=${timeout}`
return this.callApi(url, {
allowed_updates: allowedUpdates
})
}
getWebhookInfo () {
return this.callApi('getWebhookInfo')
}
getGameHighScores (userId, inlineMessageId, chatId, messageId) {
return this.callApi('getGameHighScores', {
user_id: userId,
inline_message_id: inlineMessageId,
chat_id: chatId,
message_id: messageId
})
}
setGameScore (userId, score, inlineMessageId, chatId, messageId, editMessage = true, force) {
return this.callApi('setGameScore', {
force,
score,
user_id: userId,
inline_message_id: inlineMessageId,
chat_id: chatId,
message_id: messageId,
disable_edit_message: !editMessage
})
}
setWebhook (url, certificate, maxConnections, allowedUpdates) {
return this.callApi('setWebhook', {
url,
certificate,
max_connections: maxConnections,
allowed_updates: allowedUpdates
})
}
deleteWebhook () {
return this.callApi('deleteWebhook')
}
sendMessage (chatId, text, extra) {
return this.callApi('sendMessage', { chat_id: chatId, text, ...extra })
}
forwardMessage (chatId, fromChatId, messageId, extra) {
return this.callApi('forwardMessage', {
chat_id: chatId,
from_chat_id: fromChatId,
message_id: messageId,
...extra
})
}
sendChatAction (chatId, action) {
return this.callApi('sendChatAction', { chat_id: chatId, action })
}
getUserProfilePhotos (userId, offset, limit) {
return this.callApi('getUserProfilePhotos', { user_id: userId, offset, limit })
}
sendLocation (chatId, latitude, longitude, extra) {
return this.callApi('sendLocation', { chat_id: chatId, latitude, longitude, ...extra })
}
sendVenue (chatId, latitude, longitude, title, address, extra) {
return this.callApi('sendVenue', {
latitude,
longitude,
title,
address,
chat_id: chatId,
...extra
})
}
sendInvoice (chatId, invoice, extra) {
return this.callApi('sendInvoice', { chat_id: chatId, ...invoice, ...extra })
}
sendContact (chatId, phoneNumber, firstName, extra) {
return this.callApi('sendContact', { chat_id: chatId, phone_number: phoneNumber, first_name: firstName, ...extra })
}
sendPhoto (chatId, photo, extra) {
return this.callApi('sendPhoto', { chat_id: chatId, photo, ...extra })
}
sendDice (chatId, extra) {
return this.callApi('sendDice', { chat_id: chatId, ...extra })
}
sendDocument (chatId, document, extra) {
return this.callApi('sendDocument', { chat_id: chatId, document, ...extra })
}
sendAudio (chatId, audio, extra) {
return this.callApi('sendAudio', { chat_id: chatId, audio, ...extra })
}
sendSticker (chatId, sticker, extra) {
return this.callApi('sendSticker', { chat_id: chatId, sticker, ...extra })
}
sendVideo (chatId, video, extra) {
return this.callApi('sendVideo', { chat_id: chatId, video, ...extra })
}
sendAnimation (chatId, animation, extra) {
return this.callApi('sendAnimation', { chat_id: chatId, animation, ...extra })
}
sendVideoNote (chatId, videoNote, extra) {
return this.callApi('sendVideoNote', { chat_id: chatId, video_note: videoNote, ...extra })
}
sendVoice (chatId, voice, extra) {
return this.callApi('sendVoice', { chat_id: chatId, voice, ...extra })
}
sendGame (chatId, gameName, extra) {
return this.callApi('sendGame', { chat_id: chatId, game_short_name: gameName, ...extra })
}
sendMediaGroup (chatId, media, extra) {
return this.callApi('sendMediaGroup', { chat_id: chatId, media, ...extra })
}
sendPoll (chatId, question, options, extra) {
return this.callApi('sendPoll', { chat_id: chatId, type: 'regular', question, options, ...extra })
}
sendQuiz (chatId, question, options, extra) {
return this.callApi('sendPoll', { chat_id: chatId, type: 'quiz', question, options, ...extra })
}
stopPoll (chatId, messageId, extra) {
return this.callApi('stopPoll', { chat_id: chatId, message_id: messageId, ...extra })
}
getChat (chatId) {
return this.callApi('getChat', { chat_id: chatId })
}
getChatAdministrators (chatId) {
return this.callApi('getChatAdministrators', { chat_id: chatId })
}
getChatMember (chatId, userId) {
return this.callApi('getChatMember', { chat_id: chatId, user_id: userId })
}
getChatMembersCount (chatId) {
return this.callApi('getChatMembersCount', { chat_id: chatId })
}
answerInlineQuery (inlineQueryId, results, extra) {
return this.callApi('answerInlineQuery', { inline_query_id: inlineQueryId, results, ...extra })
}
setChatPermissions (chatId, permissions) {
return this.callApi('setChatPermissions', { chat_id: chatId, permissions })
}
kickChatMember (chatId, userId, untilDate) {
return this.callApi('kickChatMember', { chat_id: chatId, user_id: userId, until_date: untilDate })
}
promoteChatMember (chatId, userId, extra) {
return this.callApi('promoteChatMember', { chat_id: chatId, user_id: userId, ...extra })
}
restrictChatMember (chatId, userId, extra) {
return this.callApi('restrictChatMember', { chat_id: chatId, user_id: userId, ...extra })
}
setChatAdministratorCustomTitle (chatId, userId, title) {
return this.callApi('setChatAdministratorCustomTitle', { chat_id: chatId, user_id: userId, custom_title: title })
}
exportChatInviteLink (chatId) {
return this.callApi('exportChatInviteLink', { chat_id: chatId })
}
setChatPhoto (chatId, photo) {
return this.callApi('setChatPhoto', { chat_id: chatId, photo })
}
deleteChatPhoto (chatId) {
return this.callApi('deleteChatPhoto', { chat_id: chatId })
}
setChatTitle (chatId, title) {
return this.callApi('setChatTitle', { chat_id: chatId, title })
}
setChatDescription (chatId, description) {
return this.callApi('setChatDescription', { chat_id: chatId, description })
}
pinChatMessage (chatId, messageId, extra) {
return this.callApi('pinChatMessage', { chat_id: chatId, message_id: messageId, ...extra })
}
unpinChatMessage (chatId) {
return this.callApi('unpinChatMessage', { chat_id: chatId })
}
leaveChat (chatId) {
return this.callApi('leaveChat', { chat_id: chatId })
}
unbanChatMember (chatId, userId) {
return this.callApi('unbanChatMember', { chat_id: chatId, user_id: userId })
}
answerCbQuery (callbackQueryId, text, showAlert, extra) {
return this.callApi('answerCallbackQuery', {
text,
show_alert: showAlert,
callback_query_id: callbackQueryId,
...extra
})
}
answerGameQuery (callbackQueryId, url) {
return this.callApi('answerCallbackQuery', {
url,
callback_query_id: callbackQueryId
})
}
answerShippingQuery (shippingQueryId, ok, shippingOptions, errorMessage) {
return this.callApi('answerShippingQuery', {
ok,
shipping_query_id: shippingQueryId,
shipping_options: shippingOptions,
error_message: errorMessage
})
}
answerPreCheckoutQuery (preCheckoutQueryId, ok, errorMessage) {
return this.callApi('answerPreCheckoutQuery', {
ok,
pre_checkout_query_id: preCheckoutQueryId,
error_message: errorMessage
})
}
editMessageText (chatId, messageId, inlineMessageId, text, extra) {
return this.callApi('editMessageText', {
text,
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
...extra
})
}
editMessageCaption (chatId, messageId, inlineMessageId, caption, extra = {}) {
return this.callApi('editMessageCaption', {
caption,
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
parse_mode: extra.parse_mode,
reply_markup: extra.parse_mode || extra.reply_markup ? extra.reply_markup : extra
})
}
editMessageMedia (chatId, messageId, inlineMessageId, media, extra = {}) {
return this.callApi('editMessageMedia', {
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
media: { ...media, parse_mode: extra.parse_mode },
reply_markup: extra.reply_markup ? extra.reply_markup : extra
})
}
editMessageReplyMarkup (chatId, messageId, inlineMessageId, markup) {
return this.callApi('editMessageReplyMarkup', {
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
reply_markup: markup
})
}
editMessageLiveLocation (latitude, longitude, chatId, messageId, inlineMessageId, markup) {
return this.callApi('editMessageLiveLocation', {
latitude,
longitude,
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
reply_markup: markup
})
}
stopMessageLiveLocation (chatId, messageId, inlineMessageId, markup) {
return this.callApi('stopMessageLiveLocation', {
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
reply_markup: markup
})
}
deleteMessage (chatId, messageId) {
return this.callApi('deleteMessage', {
chat_id: chatId,
message_id: messageId
})
}
setChatStickerSet (chatId, setName) {
return this.callApi('setChatStickerSet', {
chat_id: chatId,
sticker_set_name: setName
})
}
deleteChatStickerSet (chatId) {
return this.callApi('deleteChatStickerSet', { chat_id: chatId })
}
getStickerSet (name) {
return this.callApi('getStickerSet', { name })
}
uploadStickerFile (ownerId, stickerFile) {
return this.callApi('uploadStickerFile', {
user_id: ownerId,
png_sticker: stickerFile
})
}
createNewStickerSet (ownerId, name, title, stickerData) {
return this.callApi('createNewStickerSet', {
name,
title,
user_id: ownerId,
...stickerData
})
}
addStickerToSet (ownerId, name, stickerData, isMasks) {
return this.callApi('addStickerToSet', {
name,
user_id: ownerId,
is_masks: isMasks,
...stickerData
})
}
setStickerPositionInSet (sticker, position) {
return this.callApi('setStickerPositionInSet', {
sticker,
position
})
}
setStickerSetThumb (name, userId, thumb) {
return this.callApi('setStickerSetThumb', { name, user_id: userId, thumb })
}
deleteStickerFromSet (sticker) {
return this.callApi('deleteStickerFromSet', { sticker })
}
getMyCommands () {
return this.callApi('getMyCommands')
}
setMyCommands (commands) {
return this.callApi('setMyCommands', { commands })
}
setPassportDataErrors (userId, errors) {
return this.callApi('setPassportDataErrors', {
user_id: userId,
errors: errors
})
}
sendCopy (chatId, message, extra) {
if (!message) {
throw new Error('Message is required')
}
const type = Object.keys(replicators.copyMethods).find((type) => message[type])
if (!type) {
throw new Error('Unsupported message type')
}
const opts = {
chat_id: chatId,
...replicators[type](message),
...extra
}
return this.callApi(replicators.copyMethods[type], opts)
}
}
module.exports = Telegram
View File
Whitespace-only changes.
-59
View File
@@ -1,59 +0,0 @@
{
"_from": "telegram-typings@^3.6.0",
"_id": "telegram-typings@3.6.1",
"_inBundle": false,
"_integrity": "sha512-njVv1EAhIZnmQVLocZEADYUyqA1WIXuVcDYlsp+mXua/XB0pxx+PKtMSPeZ/EE4wPWTw9h/hA9ASTT6yQelkiw==",
"_location": "/telegram-typings",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "telegram-typings@^3.6.0",
"name": "telegram-typings",
"escapedName": "telegram-typings",
"rawSpec": "^3.6.0",
"saveSpec": null,
"fetchSpec": "^3.6.0"
},
"_requiredBy": [
"/telegraf"
],
"_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",
"author": {
"name": "Sergey Sova",
"email": "mail@sergeysova.com",
"url": "https://sergeysova.com"
},
"bugs": {
"url": "https://github.com/sergeysova/telegram-typings/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Telegram typings for TypeScript and Flowtype to create bots",
"homepage": "https://github.com/sergeysova/telegram-typings#readme",
"keywords": [
"telegram",
"bots",
"typings",
"types",
"flow",
"type",
"typescript",
"script",
"build",
"generate"
],
"license": "MIT",
"main": "index.js",
"name": "telegram-typings",
"repository": {
"type": "git",
"url": "git+https://github.com/sergeysova/telegram-typings.git"
},
"typings": "telegram-typings.d.ts",
"version": "3.6.1"
}