├── .gitignore
├── Game.js
├── Game.ts
├── Log.js
├── Log.ts
├── Player.js
├── Player.ts
├── Pollen.js
├── Pollen.ts
├── README.md
├── State.js
├── State.ts
├── SteamMonsterLobby.njsproj
├── Tools.js
├── Tools.ts
├── app.js
├── app.ts
├── ipfilter.js
├── package.json
├── public
├── LocalHostLoader.user.js
├── MonsterLobby.user.js
├── PollenClient.js
├── PollenClient.ts
└── style.css
├── tpl
├── admin.jade
└── login.jade
└── typings
├── body-parser
└── body-parser.d.ts
├── form-data
└── form-data.d.ts
├── jquery
└── jquery.d.ts
├── node
└── node.d.ts
├── redis
└── redis.d.ts
├── request
└── request.d.ts
└── validator
└── validator.d.ts
/.gitignore:
--------------------------------------------------------------------------------
1 | lib-cov
2 | *.seed
3 | *.log
4 | *.csv
5 | *.dat
6 | *.out
7 | *.pid
8 | *.gz
9 |
10 | pids
11 | logs
12 | results
13 | build
14 |
15 | node_modules
16 |
17 | *.map
18 |
19 |
20 | # User-specific files
21 | *.suo
22 | *.user
23 | *.userosscache
24 | *.sln.docstates
25 |
26 | # User-specific files (MonoDevelop/Xamarin Studio)
27 | *.userprefs
28 |
29 | # Build results
30 | [Dd]ebug/
31 | [Dd]ebugPublic/
32 | [Rr]elease/
33 | [Rr]eleases/
34 | x64/
35 | x86/
36 | build/
37 | bld/
38 | [Bb]in/
39 | [Oo]bj/
40 |
41 | # Visual Studo 2015 cache/options directory
42 | .vs/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUNIT
49 | *.VisualState.xml
50 | TestResult.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | *_i.c
58 | *_p.c
59 | *_i.h
60 | *.ilk
61 | *.meta
62 | *.obj
63 | *.pch
64 | *.pdb
65 | *.pgc
66 | *.pgd
67 | *.rsp
68 | *.sbr
69 | *.tlb
70 | *.tli
71 | *.tlh
72 | *.tmp
73 | *.tmp_proj
74 | *.log
75 | *.vspscc
76 | *.vssscc
77 | .builds
78 | *.pidb
79 | *.svclog
80 | *.scc
81 |
82 | # Chutzpah Test files
83 | _Chutzpah*
84 |
85 | # Visual C++ cache files
86 | ipch/
87 | *.aps
88 | *.ncb
89 | *.opensdf
90 | *.sdf
91 | *.cachefile
92 |
93 | # Visual Studio profiler
94 | *.psess
95 | *.vsp
96 | *.vspx
97 |
98 | # TFS 2012 Local Workspace
99 | $tf/
100 |
101 | # Guidance Automation Toolkit
102 | *.gpState
103 |
104 | # ReSharper is a .NET coding add-in
105 | _ReSharper*/
106 | *.[Rr]e[Ss]harper
107 | *.DotSettings.user
108 |
109 | # JustCode is a .NET coding addin-in
110 | .JustCode
111 |
112 | # TeamCity is a build add-in
113 | _TeamCity*
114 |
115 | # DotCover is a Code Coverage Tool
116 | *.dotCover
117 |
118 | # NCrunch
119 | _NCrunch_*
120 | .*crunch*.local.xml
121 |
122 | # MightyMoose
123 | *.mm.*
124 | AutoTest.Net/
125 |
126 | # Web workbench (sass)
127 | .sass-cache/
128 |
129 | # Installshield output folder
130 | [Ee]xpress/
131 |
132 | # DocProject is a documentation generator add-in
133 | DocProject/buildhelp/
134 | DocProject/Help/*.HxT
135 | DocProject/Help/*.HxC
136 | DocProject/Help/*.hhc
137 | DocProject/Help/*.hhk
138 | DocProject/Help/*.hhp
139 | DocProject/Help/Html2
140 | DocProject/Help/html
141 |
142 | # Click-Once directory
143 | publish/
144 |
145 | # Publish Web Output
146 | *.[Pp]ublish.xml
147 | *.azurePubxml
148 | # TODO: Comment the next line if you want to checkin your web deploy settings
149 | # but database connection strings (with potential passwords) will be unencrypted
150 | *.pubxml
151 | *.publishproj
152 |
153 | # NuGet Packages
154 | *.nupkg
155 | # The packages folder can be ignored because of Package Restore
156 | **/packages/*
157 | # except build/, which is used as an MSBuild target.
158 | !**/packages/build/
159 | # Uncomment if necessary however generally it will be regenerated when needed
160 | #!**/packages/repositories.config
161 |
162 | # Windows Azure Build Output
163 | csx/
164 | *.build.csdef
165 |
166 | # Windows Store app package directory
167 | AppPackages/
168 |
169 | # Others
170 | *.[Cc]ache
171 | ClientBin/
172 | [Ss]tyle[Cc]op.*
173 | ~$*
174 | *~
175 | *.dbmdl
176 | *.dbproj.schemaview
177 | *.pfx
178 | *.publishsettings
179 | node_modules/
180 | bower_components/
181 |
182 | # RIA/Silverlight projects
183 | Generated_Code/
184 |
185 | # Backup & report files from converting an old project file
186 | # to a newer Visual Studio version. Backup files are not needed,
187 | # because we have git ;-)
188 | _UpgradeReport_Files/
189 | Backup*/
190 | UpgradeLog*.XML
191 | UpgradeLog*.htm
192 |
193 | # SQL Server files
194 | *.mdf
195 | *.ldf
196 |
197 | # Business Intelligence projects
198 | *.rdl.data
199 | *.bim.layout
200 | *.bim_*.settings
201 |
202 | # Microsoft Fakes
203 | FakesAssemblies/
204 |
205 | # Node.js Tools for Visual Studio
206 | .ntvs_analysis.dat
207 |
208 | # Visual Studio 6 build log
209 | *.plg
210 |
211 | # Visual Studio 6 workspace options file
212 | *.opt
213 |
214 | lobby_config.js
--------------------------------------------------------------------------------
/Game.js:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 | var request = require('request');
4 | (function (GameType) {
5 | GameType[GameType["Unoffical"] = 0] = "Unoffical";
6 | GameType[GameType["Offical"] = 1] = "Offical";
7 | })(exports.GameType || (exports.GameType = {}));
8 | var GameType = exports.GameType;
9 | var GameData = (function () {
10 | function GameData() {
11 | }
12 | return GameData;
13 | })();
14 | exports.GameData = GameData;
15 | function api(url, onsuccess) {
16 | //http://steamapi-a.akamaihd.net/ITowerAttackMiniGameService/GetPlayerNames/v0001/?gameid=48915
17 | }
18 | var Game = (function () {
19 | function Game() {
20 | this.gameType = 0 /* Unoffical */;
21 | this.name = "UNKNOWN";
22 | this.level = 0;
23 | this.totalPlayerCount = 0;
24 | this.estimatedKnown = '';
25 | this.knownPlayerCount = 0;
26 | this.likenewCount = 0;
27 | this.wormholeCount = 0;
28 | }
29 | return Game;
30 | })();
31 | exports.Game = Game;
32 | function fetchOfficialPlayerList(gm, callback) {
33 | var query = "http://steamapi-a.akamaihd.net/ITowerAttackMiniGameService/GetPlayerNames/v0001/?gameid=";
34 | var finalUrl = query + this.roomId;
35 | var self = gm;
36 | request(finalUrl, function (error, response, body) {
37 | if (!error && response.statusCode == 200) {
38 | try {
39 | var data = JSON.parse(body);
40 | if (callback) {
41 | callback(data);
42 | }
43 | }
44 | catch (e) {
45 | console.log(e);
46 | }
47 | }
48 | });
49 | }
50 | exports.fetchOfficialPlayerList = fetchOfficialPlayerList;
51 | function fetchGameDetails(gm, callback) {
52 | var query = "http://steamapi-a.akamaihd.net/ITowerAttackMiniGameService/GetGameData/v0001/?gameid=";
53 | var finalUrl = query + this.roomId + "&include_stats=1&format=json";
54 | var self = gm;
55 | request(finalUrl, function (error, response, body) {
56 | if (!error && response.statusCode == 200) {
57 | try {
58 | var data = JSON.parse(body);
59 | if (data) {
60 | if (data.response) {
61 | if (data.response.game_data) {
62 | self.level = data.response.game_data.level;
63 | }
64 | if (data.response.stats) {
65 | self.totalPlayerCount = data.response.stats.num_players;
66 | }
67 | }
68 | }
69 | if (callback) {
70 | callback(data);
71 | }
72 | }
73 | catch (e) {
74 | console.log(e);
75 | }
76 | }
77 | });
78 | }
79 | exports.fetchGameDetails = fetchGameDetails;
80 | //# sourceMappingURL=Game.js.map
--------------------------------------------------------------------------------
/Game.ts:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 |
4 | import state = require("./State");
5 |
6 | import http = require('http');
7 |
8 | import request = require('request');
9 |
10 | export enum GameType {
11 | Unoffical,
12 | Offical,
13 | }
14 |
15 | export class GameData {
16 |
17 | }
18 |
19 | function api(url, onsuccess) {
20 | //http://steamapi-a.akamaihd.net/ITowerAttackMiniGameService/GetPlayerNames/v0001/?gameid=48915
21 |
22 | }
23 |
24 | export class Game {
25 |
26 | public gameType: GameType = GameType.Unoffical;
27 |
28 | public roomId: number;
29 | public name: string = "UNKNOWN";
30 |
31 | public level: number = 0;
32 |
33 | public totalPlayerCount: number = 0;
34 |
35 | public estimatedKnown: string = '';
36 | public knownPlayerCount: number = 0;
37 |
38 | public likenewCount: number = 0;
39 | public wormholeCount: number = 0;
40 |
41 |
42 | }
43 |
44 |
45 | export function fetchOfficialPlayerList(gm: Game,callback?: Function) {
46 | var query = "http://steamapi-a.akamaihd.net/ITowerAttackMiniGameService/GetPlayerNames/v0001/?gameid=";
47 | var finalUrl = query + this.roomId;
48 |
49 | var self = gm;
50 |
51 | request(finalUrl, function (error, response, body) {
52 | if (!error && response.statusCode == 200) {
53 | try
54 | {
55 | var data = JSON.parse(body);
56 | if (callback) {
57 | callback(data);
58 | }
59 | }
60 | catch (e) {
61 | console.log(e);
62 | }
63 | }
64 | });
65 | }
66 |
67 | export function fetchGameDetails(gm: Game,callback?: Function) {
68 | var query = "http://steamapi-a.akamaihd.net/ITowerAttackMiniGameService/GetGameData/v0001/?gameid=";
69 | var finalUrl = query + this.roomId + "&include_stats=1&format=json";
70 |
71 | var self = gm;
72 |
73 | request(finalUrl, function (error, response, body) {
74 | if (!error && response.statusCode == 200) {
75 | try
76 | {
77 | var data = JSON.parse(body);
78 |
79 | if (data) {
80 | if (data.response) {
81 | if (data.response.game_data) {
82 | self.level = data.response.game_data.level;
83 | }
84 | if (data.response.stats) {
85 | self.totalPlayerCount = data.response.stats.num_players;
86 | }
87 | }
88 | }
89 |
90 | if (callback) {
91 | callback(data);
92 | }
93 | }
94 | catch (e) {
95 | console.log(e);
96 | }
97 | }
98 | });
99 | }
--------------------------------------------------------------------------------
/Log.js:
--------------------------------------------------------------------------------
1 | exports.logs = [];
2 | function push(value) {
3 | exports.logs.push(value);
4 | console.log(value);
5 | }
6 | exports.push = push;
7 | function info(value) {
8 | //push( "[INFO] " + value);
9 | }
10 | exports.info = info;
11 | //# sourceMappingURL=Log.js.map
--------------------------------------------------------------------------------
/Log.ts:
--------------------------------------------------------------------------------
1 |
2 | export var logs: string[] = []
3 |
4 | export function push(value: string) {
5 | logs.push(value);
6 | console.log(value);
7 | }
8 |
9 | export function info(value: string) {
10 | //push( "[INFO] " + value);
11 | }
--------------------------------------------------------------------------------
/Player.js:
--------------------------------------------------------------------------------
1 | var state = require("./State");
2 | var game = require("./Game");
3 | var validator = require("validator");
4 | (function (PlayerState) {
5 | PlayerState[PlayerState["Waiting"] = 0] = "Waiting";
6 | PlayerState[PlayerState["Selected"] = 1] = "Selected";
7 | PlayerState[PlayerState["Joining"] = 2] = "Joining";
8 | PlayerState[PlayerState["Loading"] = 3] = "Loading";
9 | PlayerState[PlayerState["InCorrectGame"] = 4] = "InCorrectGame";
10 | PlayerState[PlayerState["InWrongGame"] = 5] = "InWrongGame";
11 | })(exports.PlayerState || (exports.PlayerState = {}));
12 | var PlayerState = exports.PlayerState;
13 | var Player = (function () {
14 | function Player() {
15 | this.state = 0 /* Waiting */;
16 | this.likenewCount = 0;
17 | this.wormholeCount = 0;
18 | this.playerGame = null;
19 | this.playerMustGame = null;
20 | this.ugly = false;
21 | this.joinTimeout = 150000; // time out as milliseconds
22 | this.loadingTimeout = 10000;
23 | }
24 | // timeout in seconds
25 | Player.prototype.joinGame = function (gameId, timeout) {
26 | this.playerMustGame = state.globalState.getOrCreateGame(gameId);
27 | this.state = 2 /* Joining */;
28 | this.joinTimeout = timeout * 1000;
29 | this.joinIssueStamp = new Date().getTime();
30 | this.playerSocket.emit("joinGame", { id: gameId });
31 | };
32 | Player.prototype.leaveGame = function (timeout) {
33 | this.playerSocket.emit('leaveGame', {});
34 | };
35 | Player.prototype.playerLeavedGame = function () {
36 | if (this.playerGame != null) {
37 | this.playerGame = null;
38 | this.state = 0 /* Waiting */;
39 | }
40 | };
41 | Player.prototype.announce = function (usr, msg) {
42 | var data = { user: validator.escape(usr), message: validator.escape(msg) };
43 | if (this.playerSocket != null) {
44 | this.playerSocket.emit('announce', data);
45 | }
46 | };
47 | Player.prototype.sendHello = function () {
48 | if (this.playerSocket == null)
49 | return;
50 | var helloData = {};
51 | helloData['state'] = this.state;
52 | if (this.playerMustGame != null) {
53 | helloData['gameid'] = this.playerMustGame.roomId;
54 | }
55 | if (this.playerGame != null) {
56 | helloData['wormholes'] = this.playerGame.wormholeCount;
57 | helloData['likenews'] = this.playerGame.likenewCount;
58 | helloData['brothers'] = this.playerGame.estimatedKnown;
59 | }
60 | if (this.state == 2 /* Joining */) {
61 | var curTime = new Date().getTime();
62 | if (curTime - this.joinIssueStamp > this.joinTimeout) {
63 | this.state = 3 /* Loading */;
64 | }
65 | }
66 | helloData['playerCount'] = state.globalState.estimatedActives;
67 | helloData['playersInGame'] = state.globalState.estimatedInGames;
68 | this.playerSocket.emit("hello", helloData); // what do we need to update anyway?
69 | };
70 | Player.prototype.playerMadeIntoGame = function (gameid) {
71 | if (this.playerGame == null) {
72 | var g = state.globalState.getOrCreateGame(gameid);
73 | if (g.gameType == 1 /* Offical */) {
74 | this.playerMustGame = g;
75 | this.playerGame = g;
76 | this.state = 4 /* InCorrectGame */;
77 | return;
78 | }
79 | }
80 | if (this.playerMustGame != null && gameid == this.playerMustGame.roomId) {
81 | this.state = 4 /* InCorrectGame */;
82 | }
83 | else {
84 | this.state = 5 /* InWrongGame */;
85 | }
86 | if (this.playerGame != null && this.playerGame.roomId == gameid)
87 | return;
88 | var g = state.globalState.getOrCreateGame(gameid);
89 | this.playerGame = g;
90 | };
91 | return Player;
92 | })();
93 | exports.Player = Player;
94 | //# sourceMappingURL=Player.js.map
--------------------------------------------------------------------------------
/Player.ts:
--------------------------------------------------------------------------------
1 |
2 |
3 | import pollen = require('./Pollen');
4 | import state = require("./State");
5 | import game = require("./Game");
6 | import validator = require("validator");
7 |
8 | export enum PlayerState {
9 | Waiting,
10 | Selected,
11 | Joining,
12 | Loading,
13 | InCorrectGame,
14 | InWrongGame,
15 | }
16 |
17 | export class Player {
18 | public steamName: string;
19 | public steamId: string;
20 |
21 | public lastHeartBeat: number;
22 |
23 | public playerSocket: pollen.PollenSocket;
24 |
25 | public state: PlayerState = PlayerState.Waiting;
26 |
27 | public likenewCount: number = 0;
28 | public wormholeCount: number = 0;
29 |
30 | public playerGame: game.Game = null;
31 | public playerMustGame: game.Game = null;
32 |
33 | public lastMessageTime: number;
34 | public ugly: boolean = false;
35 |
36 | public joinIssueStamp: number;
37 | public joinTimeout: number = 150000; // time out as milliseconds
38 |
39 | public loadingTimeout: number = 10000;
40 |
41 | // timeout in seconds
42 | public joinGame(gameId, timeout: number) {
43 |
44 | this.playerMustGame = state.globalState.getOrCreateGame(gameId);
45 | this.state = PlayerState.Joining;
46 |
47 | this.joinTimeout = timeout * 1000;
48 | this.joinIssueStamp = new Date().getTime();
49 |
50 | this.playerSocket.emit("joinGame", { id: gameId });
51 | }
52 |
53 | public leaveGame(timeout: number) {
54 | this.playerSocket.emit('leaveGame', {});
55 | }
56 |
57 | public playerLeavedGame() {
58 | if (this.playerGame != null) {
59 | this.playerGame = null;
60 | this.state = PlayerState.Waiting;
61 | }
62 | }
63 |
64 | public announce(usr: string, msg: string) {
65 |
66 | var data = { user: validator.escape(usr), message: validator.escape(msg) };
67 |
68 | if (this.playerSocket != null) {
69 | this.playerSocket.emit('announce', data);
70 | }
71 | }
72 |
73 | public sendHello() {
74 | if (this.playerSocket == null) return;
75 |
76 | var helloData = {}
77 |
78 | helloData['state'] = this.state;
79 |
80 | if (this.playerMustGame != null) {
81 | helloData['gameid'] = this.playerMustGame.roomId;
82 | }
83 |
84 | if (this.playerGame != null) {
85 | helloData['wormholes'] = this.playerGame.wormholeCount;
86 | helloData['likenews'] = this.playerGame.likenewCount;
87 | helloData['brothers'] = this.playerGame.estimatedKnown;
88 | }
89 |
90 | if (this.state == PlayerState.Joining) {
91 | var curTime = new Date().getTime();
92 | if (curTime - this.joinIssueStamp > this.joinTimeout) {
93 | this.state = PlayerState.Loading;
94 | }
95 | }
96 |
97 | helloData['playerCount'] = state.globalState.estimatedActives;
98 | helloData['playersInGame'] = state.globalState.estimatedInGames;
99 |
100 | this.playerSocket.emit("hello", helloData); // what do we need to update anyway?
101 | }
102 |
103 | public playerMadeIntoGame(gameid: number) {
104 | if (this.playerGame == null) {
105 | var g: game.Game = state.globalState.getOrCreateGame(gameid);
106 | if (g.gameType == game.GameType.Offical) {
107 | this.playerMustGame = g;
108 | this.playerGame = g;
109 | this.state = PlayerState.InCorrectGame;
110 | return;
111 | }
112 | }
113 |
114 | if (this.playerMustGame != null && gameid == this.playerMustGame.roomId) {
115 | this.state = PlayerState.InCorrectGame;
116 | }
117 | else {
118 | this.state = PlayerState.InWrongGame;
119 | }
120 |
121 | if (this.playerGame != null && this.playerGame.roomId == gameid) return;
122 |
123 | var g: game.Game = state.globalState.getOrCreateGame(gameid);
124 | this.playerGame = g;
125 | }
126 | }
--------------------------------------------------------------------------------
/Pollen.js:
--------------------------------------------------------------------------------
1 | var __extends = this.__extends || function (d, b) {
2 | for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
3 | function __() { this.constructor = d; }
4 | __.prototype = b.prototype;
5 | d.prototype = new __();
6 | };
7 | var events = require('events');
8 | //// SIMPLE POLLING PACKET SERVER
9 | var PollenSocket = (function () {
10 | function PollenSocket() {
11 | this.packets = [];
12 | this.internalEvents = new events.EventEmitter();
13 | }
14 | PollenSocket.prototype.emit = function (event, data) {
15 | this.packets.push({ event: event, data: data });
16 | };
17 | PollenSocket.prototype.receivedData = function (packets) {
18 | for (var i = 0; i < packets.length; i++) {
19 | var s = packets[i];
20 | var eventName = s.event;
21 | var eventData = s.data;
22 | this.internalEvents.emit(eventName, eventData);
23 | }
24 | };
25 | PollenSocket.prototype.on = function (event, callback) {
26 | this.internalEvents.on(event, callback);
27 | };
28 | return PollenSocket;
29 | })();
30 | exports.PollenSocket = PollenSocket;
31 | var PollenServer = (function (_super) {
32 | __extends(PollenServer, _super);
33 | function PollenServer(appobj) {
34 | _super.call(this);
35 | this.sockets = [];
36 | this.maxRequestsPerSecond = 500; // adjust delay with this
37 | this.avgResponseTime = 0;
38 | this.clientInterval = 1500;
39 | this.requestCounter = 0;
40 | this.lastRequestCheck = 0;
41 | this.requestSpeed = 0;
42 | this.loadFactor = 0;
43 | this.lastIntervalChange = 0;
44 | this.app = appobj;
45 | }
46 | PollenServer.prototype.getSocket = function (id) {
47 | return this.sockets[id];
48 | };
49 | PollenServer.prototype.start = function () {
50 | var self = this;
51 | this.app.post('/pollen/:socket', function (req, res) {
52 | res.header("Connection", "close");
53 | self.requestCounter++;
54 | var id = req.params.socket;
55 | var body = req.body;
56 | var sck = self.getSocket(id);
57 | if (typeof sck === 'undefined') {
58 | sck = new PollenSocket();
59 | sck.socketId = id;
60 | sck.on('connect', function (data) {
61 | sck.emit('connect', { resuming: true, delay: self.clientInterval });
62 | });
63 | //sck.emit('connect', { resuming: false , delay: self.clientInterval});
64 | self.sockets[id] = sck;
65 | self.emit('connection', sck);
66 | }
67 | sck.receivedData(body);
68 | sck.lastRequest = new Date().getTime();
69 | if (sck.packets.length > 0) {
70 | res.json(sck.packets);
71 | sck.packets = []; // we sent the packets
72 | return;
73 | }
74 | res.json([]);
75 | });
76 | // calculate server load
77 | setInterval(function () {
78 | self.requestSpeed = self.requestCounter - self.lastRequestCheck;
79 | self.lastRequestCheck = self.requestCounter;
80 | self.loadFactor = Math.ceil((self.requestSpeed / self.maxRequestsPerSecond) * 100);
81 | console.log("ReqPsec: " + self.requestSpeed + " LoadF: " + self.loadFactor + " Reqs: " + self.requestCounter + ' CI:' + self.clientInterval);
82 | var curTime = new Date().getTime();
83 | // change speed every 5 second
84 | if (curTime - self.lastRequestCheck < 5000) {
85 | return;
86 | }
87 | if (self.loadFactor > 160) {
88 | // slow down in half
89 | self.clientInterval = Math.ceil(self.clientInterval * 1.25);
90 | console.log('Slowing down client intervals to: ' + self.clientInterval);
91 | self.lastIntervalChange = curTime;
92 | for (var s in self.sockets) {
93 | var sck = self.sockets[s];
94 | sck.emit('reinterval', { delay: self.clientInterval });
95 | }
96 | }
97 | if (self.loadFactor < 50) {
98 | // slow down in %30
99 | var newInterval = Math.ceil(self.clientInterval / 1.25);
100 | if (newInterval > 500) {
101 | self.clientInterval = newInterval;
102 | console.log('Speeding up client intervals to: ' + self.clientInterval);
103 | self.lastIntervalChange = curTime;
104 | for (var s in self.sockets) {
105 | var sck = self.sockets[s];
106 | sck.emit('reinterval', { delay: self.clientInterval });
107 | }
108 | }
109 | }
110 | }, 1000);
111 | // purge dead sockets
112 | setInterval(function () {
113 | var purgeList = [];
114 | var curDate = new Date().getTime();
115 | for (var s in self.sockets) {
116 | var sck = self.sockets[s];
117 | if (curDate - sck.lastRequest > 10000) {
118 | purgeList.push(s);
119 | }
120 | }
121 | for (var i = 0; i < purgeList.length; i++) {
122 | var s2 = purgeList[i];
123 | self.sockets[s2].internalEvents.emit('disconnect', {});
124 | delete self.sockets[s2];
125 | }
126 | }, 3000);
127 | };
128 | return PollenServer;
129 | })(events.EventEmitter);
130 | exports.PollenServer = PollenServer;
131 | //# sourceMappingURL=Pollen.js.map
--------------------------------------------------------------------------------
/Pollen.ts:
--------------------------------------------------------------------------------
1 | import express = require("express");
2 | import events = require('events');
3 |
4 | //// SIMPLE POLLING PACKET SERVER
5 |
6 | export class PollenSocket {
7 | public socketId: string;
8 | public lastRequest: number;
9 |
10 | public packets: Object[] = [];
11 |
12 | public internalEvents: events.EventEmitter = new events.EventEmitter();
13 |
14 | public emit(event:string, data: any) {
15 | this.packets.push({ event: event, data: data });
16 | }
17 |
18 | public receivedData(packets: any[]) {
19 | for (var i = 0; i < packets.length; i++) {
20 | var s = packets[i];
21 | var eventName = s.event;
22 | var eventData = s.data;
23 | this.internalEvents.emit(eventName, eventData);
24 | }
25 | }
26 |
27 | public on(event: string, callback: Function) {
28 | this.internalEvents.on(event, callback);
29 | }
30 | }
31 |
32 | export class PollenServer extends events.EventEmitter {
33 | public app: express.Express;
34 |
35 | public sockets: PollenSocket[] = [];
36 | public maxRequestsPerSecond: number = 500; // adjust delay with this
37 |
38 | public avgResponseTime: number = 0;
39 | public clientInterval: number = 1500;
40 |
41 | public requestCounter: number = 0;
42 | public lastRequestCheck: number = 0;
43 |
44 | public requestSpeed: number = 0;
45 | public loadFactor: number = 0;
46 | public lastIntervalChange: number = 0;
47 |
48 | public getSocket(id) {
49 | return this.sockets[id];
50 | }
51 |
52 |
53 | public start() {
54 | var self = this;
55 |
56 | this.app.post('/pollen/:socket', function (req, res) {
57 | res.header("Connection", "close");
58 |
59 | self.requestCounter++;
60 |
61 | var id = req.params.socket;
62 |
63 | var body = req.body;
64 |
65 | var sck = self.getSocket(id);
66 | if (typeof sck === 'undefined') {
67 | sck = new PollenSocket();
68 | sck.socketId = id;
69 | sck.on('connect', function (data) {
70 | sck.emit('connect', { resuming: true, delay: self.clientInterval });
71 | });
72 |
73 | //sck.emit('connect', { resuming: false , delay: self.clientInterval});
74 | self.sockets[id] = sck;
75 |
76 | self.emit('connection', sck);
77 | }
78 |
79 | sck.receivedData(body);
80 |
81 | sck.lastRequest = new Date().getTime();
82 |
83 | if (sck.packets.length > 0) {
84 | res.json(sck.packets);
85 | sck.packets = []; // we sent the packets
86 | return;
87 | }
88 |
89 | res.json([]);
90 |
91 | });
92 |
93 | // calculate server load
94 | setInterval(function () {
95 | self.requestSpeed = self.requestCounter - self.lastRequestCheck;
96 | self.lastRequestCheck = self.requestCounter;
97 | self.loadFactor = Math.ceil((self.requestSpeed / self.maxRequestsPerSecond) * 100);
98 | console.log("ReqPsec: " + self.requestSpeed + " LoadF: " + self.loadFactor + " Reqs: " + self.requestCounter + ' CI:' + self.clientInterval);
99 |
100 | var curTime = new Date().getTime();
101 |
102 | // change speed every 5 second
103 | if (curTime - self.lastRequestCheck < 5000) {
104 | return;
105 | }
106 |
107 | if (self.loadFactor > 160) {
108 |
109 | // slow down in half
110 | self.clientInterval = Math.ceil(self.clientInterval * 1.25);
111 |
112 | console.log('Slowing down client intervals to: ' + self.clientInterval);
113 | self.lastIntervalChange = curTime;
114 | // slow people down
115 | for (var s in self.sockets) {
116 | var sck = self.sockets[s];
117 | sck.emit('reinterval', {delay: self.clientInterval});
118 | }
119 | }
120 | if (self.loadFactor < 50) {
121 | // slow down in %30
122 | var newInterval = Math.ceil(self.clientInterval / 1.25);
123 |
124 |
125 | if (newInterval > 500) {
126 | self.clientInterval = newInterval;
127 | console.log('Speeding up client intervals to: ' + self.clientInterval);
128 | self.lastIntervalChange = curTime;
129 |
130 | // slow people down
131 | for (var s in self.sockets) {
132 | var sck = self.sockets[s];
133 | sck.emit('reinterval', { delay: self.clientInterval });
134 | }
135 | }
136 | }
137 | }, 1000);
138 |
139 | // purge dead sockets
140 | setInterval(function () {
141 |
142 | var purgeList = [];
143 | var curDate = new Date().getTime();
144 |
145 | for (var s in self.sockets) {
146 | var sck = self.sockets[s];
147 | if (curDate - sck.lastRequest > 10000) {
148 | purgeList.push(s);
149 | }
150 | }
151 |
152 | for (var i = 0; i < purgeList.length; i++){
153 | var s2 = purgeList[i];
154 | self.sockets[s2].internalEvents.emit('disconnect', {});
155 | delete self.sockets[s2];
156 | }
157 |
158 | }, 3000);
159 | }
160 |
161 | public constructor(appobj: express.Express) {
162 | super();
163 | this.app = appobj;
164 | }
165 | }
166 |
167 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | =======
2 | # SteamMonsterLobby
3 | Steam Summer Mini Game 2015 Mass lobby joiner system
4 |
--------------------------------------------------------------------------------
/State.js:
--------------------------------------------------------------------------------
1 | ///
2 | var player = require("./Player");
3 | var game = require("./Game");
4 | var log = require('./Log');
5 | var validator = require("validator");
6 | var redis = require("redis");
7 | var tools = require('./Tools');
8 | exports.db = redis.createClient();
9 | exports.db.on("error", function (err) {
10 | console.log("Error " + err);
11 | });
12 | var StateManager = (function () {
13 | function StateManager() {
14 | this.players = [];
15 | this.games = {};
16 | this.totalActivePlayers = 0;
17 | this.totalPlayersInGame = 0;
18 | this.estimatedActives = '';
19 | this.estimatedInGames = '';
20 | this.unofficalGames = 0;
21 | this.uglies = 0;
22 | // steam id to player dictionary
23 | this.steamPlayer = {};
24 | var self = this;
25 | exports.db.get("games", function (err, reply) {
26 | self.games = JSON.parse(reply);
27 | if (self.games == null) {
28 | self.games = {};
29 | }
30 | console.log("GAMES LOADED FROM DB");
31 | });
32 | }
33 | StateManager.prototype.saveGames = function () {
34 | exports.db.set("games", JSON.stringify(this.games));
35 | console.log("GAMES SAVED TO DB");
36 | };
37 | StateManager.prototype.playerJoined = function (p) {
38 | if (this.players.indexOf(p) > -1) {
39 | return;
40 | }
41 | this.players.push(p);
42 | log.info("Player connected: " + p.steamName + " SteamId:" + p.steamId);
43 | };
44 | StateManager.prototype.announce = function (usr, msg) {
45 | var data = { user: validator.escape(usr), message: validator.escape(msg) };
46 | for (var i = 0; i < this.players.length; i++) {
47 | var p = this.players[i];
48 | if (p.playerSocket != null) {
49 | p.playerSocket.emit('announce', data);
50 | }
51 | }
52 | };
53 | StateManager.prototype.recountEverything = function () {
54 | var actives = 0;
55 | var ingames = 0;
56 | this.uglies = 0;
57 | for (var key in this.games) {
58 | var g = this.games[key];
59 | g.likenewCount = 0;
60 | g.knownPlayerCount = 0;
61 | g.wormholeCount = 0;
62 | }
63 | var time = new Date().getTime();
64 | for (var i = 0; i < this.players.length; i++) {
65 | var p = this.players[i];
66 | if (p.playerSocket != null) {
67 | if (p.playerGame) {
68 | p.playerGame.likenewCount += p.likenewCount;
69 | p.playerGame.knownPlayerCount++;
70 | p.playerGame.wormholeCount += p.wormholeCount;
71 | ingames++;
72 | }
73 | if (p.ugly) {
74 | this.uglies++;
75 | }
76 | if (p.state == player.PlayerState.Loading) {
77 | var afterTime = p.joinIssueStamp + p.joinTimeout;
78 | if (time - afterTime > p.loadingTimeout) {
79 | p.state = player.PlayerState.Waiting;
80 | p.playerMustGame = null;
81 | }
82 | }
83 | actives++;
84 | }
85 | }
86 | this.unofficalGames = 0;
87 | var deleted = false;
88 | for (var key in this.games) {
89 | var g = this.games[key];
90 | g.estimatedKnown = tools.estimate(g.knownPlayerCount);
91 | if (g.gameType == game.GameType.Unoffical) {
92 | if (g.knownPlayerCount == 0) {
93 | delete this.games[g.roomId];
94 | deleted = true;
95 | }
96 | else {
97 | this.unofficalGames++;
98 | }
99 | }
100 | else {
101 | }
102 | }
103 | this.saveGames();
104 | this.totalActivePlayers = actives;
105 | this.totalPlayersInGame = ingames;
106 | this.estimatedActives = tools.estimate(actives);
107 | this.estimatedInGames = tools.estimate(ingames);
108 | };
109 | StateManager.prototype.getGame = function (roomId) {
110 | var g = this.games[roomId];
111 | return g;
112 | };
113 | StateManager.prototype.getOrCreateGame = function (roomId) {
114 | var g = this.games[roomId];
115 | if (!g) {
116 | g = new game.Game();
117 | g.roomId = roomId;
118 | this.games[roomId] = g;
119 | }
120 | return g;
121 | };
122 | // security problem: we are not verifying if client is correctly sent his steamid
123 | StateManager.prototype.getOrCreatePlayer = function (steamid) {
124 | var k = this.getSteamPlayer(steamid);
125 | if (k == null) {
126 | var p = new player.Player();
127 | p.steamId = steamid;
128 | this.steamPlayer[steamid] = p;
129 | return p;
130 | }
131 | return k;
132 | };
133 | StateManager.prototype.getSteamPlayer = function (steamid) {
134 | return this.steamPlayer[steamid];
135 | };
136 | StateManager.prototype.queuePlayerDisconnected = function (p) {
137 | var curTime = new Date().getTime();
138 | if (curTime - p.lastHeartBeat > 8000) {
139 | this.playerDisconnected(p);
140 | }
141 | };
142 | StateManager.prototype.playerConnectionLost = function (p, socket) {
143 | if (p.playerSocket == socket) {
144 | p.playerSocket = null;
145 | }
146 | else {
147 | log.info("Player reconnected with different socket: " + p.steamName);
148 | return;
149 | }
150 | this.queuePlayerDisconnected(p);
151 | log.info("Player connection lost: " + p.steamName);
152 | };
153 | // this sometimes happens mistakenly so it would be good to have a timeout
154 | StateManager.prototype.playerDisconnected = function (p) {
155 | log.info("Player disconnected: " + p.steamName);
156 | };
157 | return StateManager;
158 | })();
159 | exports.StateManager = StateManager;
160 | exports.globalState = new StateManager();
161 | setInterval(function () {
162 | exports.globalState.recountEverything();
163 | }, 5000);
164 | //# sourceMappingURL=State.js.map
--------------------------------------------------------------------------------
/State.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | import player = require("./Player");
4 | import game = require("./Game");
5 | import log = require('./Log');
6 | import validator = require("validator");
7 | import redis = require("redis");
8 | import tools = require('./Tools');
9 |
10 | export var db = redis.createClient();
11 |
12 | db.on("error", function (err) {
13 | console.log("Error " + err);
14 | });
15 |
16 |
17 |
18 | export class StateManager {
19 | public players: player.Player[] = [];
20 | public games: { [roomid: string]: game.Game; } = {};
21 |
22 | public totalActivePlayers: number = 0;
23 | public totalPlayersInGame: number = 0;
24 |
25 | public estimatedActives: string = '';
26 | public estimatedInGames: string = '';
27 |
28 | public unofficalGames: number = 0;
29 |
30 | public uglies: number = 0;
31 |
32 | // steam id to player dictionary
33 | public steamPlayer = {};
34 |
35 | public constructor() {
36 | var self = this;
37 |
38 | db.get("games", function (err,reply:any) {
39 | self.games = <{ [roomid: string]: game.Game; }> JSON.parse(reply);
40 | if (self.games == null) {
41 | self.games = {};
42 | }
43 | console.log("GAMES LOADED FROM DB");
44 | });
45 | }
46 |
47 | public saveGames() {
48 | db.set("games", JSON.stringify(this.games));
49 | console.log("GAMES SAVED TO DB");
50 | }
51 |
52 | public playerJoined(p: player.Player) {
53 | if (this.players.indexOf(p) > -1) {
54 | return;
55 | }
56 | this.players.push(p);
57 | log.info("Player connected: " + p.steamName + " SteamId:" + p.steamId);
58 | }
59 |
60 | public announce(usr: string, msg: string) {
61 |
62 | var data = { user: validator.escape(usr), message: validator.escape(msg) };
63 |
64 | for (var i = 0; i < this.players.length; i++) {
65 | var p = this.players[i];
66 | if (p.playerSocket != null) {
67 | p.playerSocket.emit('announce', data );
68 | }
69 | }
70 | }
71 |
72 | public recountEverything() {
73 |
74 | var actives = 0;
75 | var ingames = 0;
76 |
77 | this.uglies = 0;
78 |
79 | for (var key in this.games) {
80 | var g = this.games[key];
81 | g.likenewCount = 0;
82 | g.knownPlayerCount = 0;
83 | g.wormholeCount = 0;
84 | }
85 |
86 | var time = new Date().getTime();
87 |
88 | for (var i = 0; i < this.players.length; i++) {
89 | var p = this.players[i];
90 | if (p.playerSocket != null) {
91 | if (p.playerGame) {
92 | p.playerGame.likenewCount += p.likenewCount;
93 | p.playerGame.knownPlayerCount++;
94 | p.playerGame.wormholeCount += p.wormholeCount;
95 | ingames++;
96 | }
97 |
98 | if (p.ugly) {
99 | this.uglies++;
100 | }
101 |
102 | if (p.state == player.PlayerState.Loading) {
103 | var afterTime = p.joinIssueStamp + p.joinTimeout;
104 | if (time - afterTime > p.loadingTimeout) {
105 | p.state = player.PlayerState.Waiting;
106 | p.playerMustGame = null;
107 | }
108 | }
109 |
110 | actives++;
111 | }
112 | }
113 |
114 | this.unofficalGames = 0;
115 |
116 | var deleted = false;
117 | for (var key in this.games) {
118 | var g = this.games[key];
119 |
120 |
121 | g.estimatedKnown = tools.estimate(g.knownPlayerCount);
122 | if (g.gameType == game.GameType.Unoffical) {
123 | if (g.knownPlayerCount == 0) {
124 | delete this.games[g.roomId];
125 | deleted = true;
126 | }
127 | else {
128 | this.unofficalGames++;
129 | }
130 | }
131 | else {
132 | //game.fetchGameDetails(g);
133 | }
134 | }
135 |
136 |
137 | this.saveGames();
138 |
139 |
140 | this.totalActivePlayers = actives;
141 | this.totalPlayersInGame = ingames;
142 |
143 | this.estimatedActives = tools.estimate(actives);
144 | this.estimatedInGames = tools.estimate(ingames);
145 | }
146 |
147 | public getGame(roomId: number) {
148 | var g = this.games[roomId];
149 | return g;
150 | }
151 |
152 | public getOrCreateGame(roomId: number) {
153 | var g = this.games[roomId];
154 | if (!g) {
155 | g = new game.Game();
156 | g.roomId = roomId;
157 | this.games[roomId] = g;
158 | //this.saveGames();
159 | }
160 |
161 | return g;
162 | }
163 |
164 | // security problem: we are not verifying if client is correctly sent his steamid
165 | public getOrCreatePlayer(steamid) {
166 | var k = this.getSteamPlayer(steamid);
167 |
168 | if (k == null) {
169 | var p = new player.Player();
170 | p.steamId = steamid;
171 | this.steamPlayer[steamid] = p;
172 | return p;
173 | }
174 |
175 | return k;
176 | }
177 |
178 |
179 | public getSteamPlayer(steamid) {
180 | return this.steamPlayer[steamid];
181 | }
182 |
183 | public queuePlayerDisconnected(p: player.Player) {
184 |
185 | var curTime = new Date().getTime();
186 |
187 | if (curTime - p.lastHeartBeat > 8000) {
188 | this.playerDisconnected(p);
189 | }
190 | }
191 |
192 | public playerConnectionLost(p: player.Player, socket) {
193 | if (p.playerSocket == socket) {
194 | p.playerSocket = null;
195 | }
196 | else {
197 | log.info("Player reconnected with different socket: " + p.steamName);
198 | return;
199 | }
200 |
201 | this.queuePlayerDisconnected(p);
202 | log.info("Player connection lost: " + p.steamName);
203 | }
204 |
205 | // this sometimes happens mistakenly so it would be good to have a timeout
206 | public playerDisconnected(p: player.Player) {
207 | log.info("Player disconnected: " + p.steamName);
208 | }
209 | }
210 |
211 | export var globalState = new StateManager();
212 |
213 | setInterval(function () {
214 | globalState.recountEverything();
215 | }, 5000);
--------------------------------------------------------------------------------
/SteamMonsterLobby.njsproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 11.0
5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
6 | SteamMonsterLobby
7 | SteamMonsterGameMaster.js
8 |
9 |
10 |
11 | Debug
12 | 2.0
13 | 316dbf9a-1cea-4809-a941-c9bed0940063
14 |
15 |
16 | app.ts
17 | False
18 |
19 |
20 | .
21 | .
22 | v4.0
23 | {3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}
24 | ShowAllFiles
25 | true
26 | CommonJS
27 | true
28 | false
29 |
30 |
31 | true
32 |
33 |
34 | true
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | False
69 | True
70 | 0
71 | /
72 | http://localhost:48022/
73 | False
74 | True
75 | http://localhost:1337
76 | False
77 |
78 |
79 |
80 |
81 |
82 |
83 | CurrentPage
84 | True
85 | False
86 | False
87 | False
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 | False
97 | False
98 |
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/Tools.js:
--------------------------------------------------------------------------------
1 | function randomStr(length) {
2 | var data = "0123456789abcdefghijklmnoprstqvxyz";
3 | var result = "";
4 | for (var i = 0; i < length; i++) {
5 | result += data.charAt(Math.round(Math.random() * data.length));
6 | }
7 | return result;
8 | }
9 | exports.randomStr = randomStr;
10 | // obfuscate some numbers
11 | function estimate(value, fold) {
12 | if (fold === void 0) { fold = 50; }
13 | var oddness = value % fold;
14 | var final = (value - oddness);
15 | return '+' + final;
16 | }
17 | exports.estimate = estimate;
18 | //# sourceMappingURL=Tools.js.map
--------------------------------------------------------------------------------
/Tools.ts:
--------------------------------------------------------------------------------
1 |
2 | export function randomStr(length: number): string {
3 | var data = "0123456789abcdefghijklmnoprstqvxyz";
4 | var result = "";
5 | for (var i = 0; i < length; i++) {
6 | result += data.charAt(Math.round(Math.random() * data.length));
7 | }
8 | return result;
9 | }
10 |
11 |
12 | // obfuscate some numbers
13 | export function estimate(value: number, fold: number = 50): string {
14 | var oddness = value % fold;
15 | var final = (value - oddness);
16 | return '+' + final;
17 | }
--------------------------------------------------------------------------------
/app.js:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 | ///
4 | ///
5 | var log = require('./Log');
6 | var ipfilter = require('./ipfilter');
7 | var express = require("express");
8 | var app = express();
9 | var port = 3900;
10 | var bodyParser = require('body-parser');
11 | var cookieParser = require('cookie-parser');
12 | global['config'] = require('./lobby_config');
13 | var config = global['config'];
14 | var allowedIps = config.adminIp;
15 | var filterMod = ipfilter(allowedIps, { mode: 'allow' });
16 | app.set('views', __dirname + '/tpl');
17 | app.set('view engine', "jade");
18 | app.engine('jade', require('jade').__express);
19 | //app.use(express.static(__dirname + '/public'));
20 | app.use(bodyParser.urlencoded({ extended: false }));
21 | app.use(bodyParser.json());
22 | app.use(cookieParser());
23 | var player = require("./Player");
24 | var stateManager = require("./State");
25 | var game = require("./Game");
26 | var state = stateManager.globalState;
27 | var tools = require('./Tools');
28 | var sessions = {};
29 | var debug = typeof v8debug === 'object';
30 | app.all("/*", function (req, res, next) {
31 | res.header("Access-Control-Allow-Origin", "*");
32 | res.header("Access-Control-Allow-Headers", "origin, content-type");
33 | next();
34 | });
35 | app.get("/", filterMod, needLogin, function (req, res) {
36 | res.render("admin", state);
37 | });
38 | var systemplayer = new player.Player();
39 | systemplayer.steamName = "SYSTEM";
40 | if (debug) {
41 | console.log("DEBUG MODE, ENABLING DEBUG SCRIPT HOST");
42 | app.get('/script', function (req, res) {
43 | res.sendFile('public/MonsterLobby.user.js', { root: __dirname });
44 | });
45 | }
46 | app.post("/api/announcement", filterMod, needLogin, function (req, res) {
47 | state.announce(req.body.usr, req.body.msg);
48 | res.json({ status: 'ok' });
49 | });
50 | app.post('/api/abandonGame', filterMod, needLogin, function (req, res) {
51 | var gameId = parseInt(req.body.gameid);
52 | var retryTime = parseInt(req.body.retry);
53 | for (var i = 0; i < state.players.length; i++) {
54 | var p = state.players[i];
55 | if (p.playerSocket != null) {
56 | if (p.playerGame != null) {
57 | if (!p.ugly && p.playerGame.roomId == gameId) {
58 | p.leaveGame(retryTime);
59 | p.announce("SYSTEM", "Abandoning this room.");
60 | }
61 | }
62 | }
63 | }
64 | // soft abandon (let the players know they are in wrong game)
65 | var g = state.getGame(gameId);
66 | if (g) {
67 | g.gameType = game.GameType.Unoffical;
68 | }
69 | res.redirect("/");
70 | });
71 | app.post("/api/joinGame", filterMod, needLogin, function (req, res) {
72 | var joinList = [];
73 | var playerCount = req.body.count;
74 | var gameName = req.body.name;
75 | var gameId = req.body.gameid;
76 | var retryTime = req.body.retry;
77 | for (var i = 0; i < state.players.length; i++) {
78 | if (joinList.length >= playerCount)
79 | break;
80 | var p = state.players[i];
81 | if (p.playerSocket != null && p.state == player.PlayerState.Waiting && !p.ugly) {
82 | p.state = player.PlayerState.Selected;
83 | joinList.push(p);
84 | }
85 | }
86 | state.announce('SYSTEM', 'Randomly selected ' + joinList.length + ' players.');
87 | var room = state.getOrCreateGame(gameId);
88 | room.name = gameName;
89 | room.gameType = game.GameType.Offical;
90 | state.saveGames();
91 | state.announce('SYSTEM', 'Commencing join to room.');
92 | for (var i = 0; i < joinList.length; i++) {
93 | var p2 = joinList[i];
94 | p2.joinGame(gameId, retryTime);
95 | }
96 | res.redirect("/");
97 | });
98 | // display logs
99 | app.get("/api/logs/:count", filterMod, needLogin, function (req, res) {
100 | var count = req.params.count;
101 | var length = log.logs.length;
102 | var start = length - count;
103 | if (start < 0) {
104 | start = 0;
105 | }
106 | var end = start + count;
107 | if (end > log.logs.length) {
108 | end = log.logs.length;
109 | }
110 | var result = [];
111 | result.push("req:" + count + "start:" + start + "end:" + end);
112 | for (var i = end - 1; i >= start; i--) {
113 | result.push(i + log.logs[i]);
114 | }
115 | res.send(result.join("\n"));
116 | });
117 | app.post("/api/login", filterMod, function (req, res) {
118 | if (req.body.password == config.adminPassword) {
119 | var sessionStr = tools.randomStr(16);
120 | res.cookie("session", sessionStr);
121 | sessions[sessionStr] = { login: true, ip: req.ip };
122 | res.redirect("/");
123 | return;
124 | }
125 | res.redirect("/?failed=1");
126 | });
127 | function needLogin(req, res, next) {
128 | if (!checkLogin(req)) {
129 | var args = { loginFailed: false };
130 | if (req.query.failed == "1") {
131 | args["loginFailed"] = true;
132 | }
133 | res.render("login", args);
134 | return;
135 | }
136 | next();
137 | }
138 | function getSessionData(req) {
139 | if (typeof req.cookies == "undefined") {
140 | return false;
141 | }
142 | if (typeof req.cookies.session == 'undefined') {
143 | return false;
144 | }
145 | var sessionId = req.cookies.session;
146 | return sessions[sessionId];
147 | }
148 | function checkLogin(req) {
149 | var sessionData = getSessionData(req);
150 | if (sessionData == null) {
151 | return false;
152 | }
153 | if (typeof sessionData.ip !== "undefined") {
154 | if (sessionData.ip != req.ip) {
155 | return false;
156 | }
157 | }
158 | if (typeof sessionData.login !== "undefined") {
159 | return sessionData.login;
160 | }
161 | return false;
162 | }
163 | var pollen = require('./Pollen');
164 | var appServer = app.listen(port);
165 | var server = new pollen.PollenServer(app);
166 | var validator = require("validator");
167 | //var server = io.listen(37005, { pingInterval: 5000, allowUpgrades: false, transports: ['polling'] });
168 | server.on('connection', function (socket) {
169 | socket.on('hello', function (data) {
170 | var p = state.getOrCreatePlayer(data.id);
171 | p.steamName = data.name;
172 | p.playerSocket = socket;
173 | socket["player"] = p;
174 | state.playerJoined(p);
175 | p.sendHello();
176 | });
177 | socket.on('heartbeat', function (data) {
178 | var p = socket["player"];
179 | if (p != null) {
180 | var cur = new Date();
181 | p.lastHeartBeat = cur.getTime();
182 | if (typeof data != "undefined" && data != null) {
183 | if ("likenews" in data && "wormholes" in data) {
184 | if (!validator.isInt(data.likenews) || !validator.isInt(data.wormholes)) {
185 | log.info("Troll detected: " + p.steamName);
186 | }
187 | else {
188 | p.likenewCount = parseInt(data.likenews);
189 | p.wormholeCount = parseInt(data.wormholes);
190 | }
191 | }
192 | if (data.gameid !== "undefined") {
193 | if (validator.isInt(data.gameid)) {
194 | if (data.gameid == 0) {
195 | p.playerLeavedGame();
196 | }
197 | else {
198 | p.playerMadeIntoGame(parseInt(data.gameid));
199 | }
200 | }
201 | }
202 | }
203 | p.sendHello();
204 | }
205 | });
206 | socket.on('disconnect', function () {
207 | var p = socket["player"];
208 | if (p != null) {
209 | state.playerConnectionLost(p, socket);
210 | }
211 | });
212 | });
213 | server.start();
214 | log.info("Server started on port " + port);
215 | //# sourceMappingURL=app.js.map
--------------------------------------------------------------------------------
/app.ts:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 | ///
4 | ///
5 |
6 | import net = require('net');
7 | import fs = require('fs');
8 | import log = require('./Log');
9 |
10 | var ipfilter = require('./ipfilter');
11 |
12 | import express = require("express");
13 | var app = express();
14 | var port = 3900;
15 | import bodyParser = require('body-parser');
16 | var cookieParser = require('cookie-parser');
17 |
18 | global['config'] = require('./lobby_config');
19 |
20 | var config = global['config'];
21 |
22 | var allowedIps = config.adminIp;
23 | var filterMod = ipfilter(allowedIps, { mode: 'allow' });
24 |
25 | app.set('views', __dirname + '/tpl');
26 | app.set('view engine', "jade");
27 | app.engine('jade', require('jade').__express);
28 | //app.use(express.static(__dirname + '/public'));
29 | app.use(bodyParser.urlencoded({ extended: false }));
30 | app.use(bodyParser.json());
31 | app.use(cookieParser());
32 |
33 | import player = require("./Player");
34 | import stateManager = require("./State");
35 | import game = require("./Game");
36 |
37 | var state = stateManager.globalState;
38 |
39 | import tools = require('./Tools');
40 |
41 | var sessions = {}
42 |
43 | /*var state = {
44 | lobbies: [],
45 | players:[]
46 | }*/
47 |
48 | declare var v8debug: any;
49 | var debug = typeof v8debug === 'object';
50 |
51 | app.all("/*", function (req, res, next) {
52 | res.header("Access-Control-Allow-Origin", "*");
53 | res.header("Access-Control-Allow-Headers", "origin, content-type");
54 | next();
55 | });
56 |
57 |
58 | app.get("/", filterMod, needLogin, function (req, res) {
59 | res.render("admin", state);
60 | });
61 |
62 |
63 | var systemplayer = new player.Player();
64 | systemplayer.steamName = "SYSTEM";
65 |
66 |
67 | if (debug) {
68 | console.log("DEBUG MODE, ENABLING DEBUG SCRIPT HOST");
69 | app.get('/script', function (req, res) {
70 | res.sendFile('public/MonsterLobby.user.js', { root: __dirname })
71 | });
72 | }
73 |
74 |
75 | app.post("/api/announcement", filterMod, needLogin, function (req, res) {
76 |
77 | state.announce(req.body.usr, req.body.msg);
78 |
79 | res.json({ status: 'ok' });
80 | });
81 |
82 | app.post('/api/abandonGame', filterMod, needLogin, function (req, res) {
83 |
84 | var gameId = parseInt(req.body.gameid);
85 | var retryTime = parseInt(req.body.retry);
86 |
87 |
88 | // hard abandon (forcefully leave players)
89 | for (var i = 0; i < state.players.length; i++) {
90 | var p = state.players[i];
91 | if (p.playerSocket != null) {
92 | if (p.playerGame != null) {
93 | if (!p.ugly && p.playerGame.roomId == gameId) {
94 | p.leaveGame(retryTime);
95 | p.announce("SYSTEM", "Abandoning this room.");
96 | }
97 | }
98 | }
99 | }
100 |
101 | // soft abandon (let the players know they are in wrong game)
102 | var g: game.Game = state.getGame(gameId);
103 | if (g) {
104 | g.gameType = game.GameType.Unoffical;
105 | }
106 |
107 | res.redirect("/");
108 | });
109 |
110 | app.post("/api/joinGame", filterMod, needLogin, function (req, res) {
111 |
112 | var joinList = [];
113 |
114 | var playerCount = req.body.count;
115 | var gameName = req.body.name;
116 | var gameId = req.body.gameid;
117 | var retryTime = req.body.retry;
118 |
119 | for (var i = 0; i < state.players.length; i++) {
120 | if (joinList.length >= playerCount) break;
121 |
122 | var p = state.players[i];
123 | if (p.playerSocket != null && p.state == player.PlayerState.Waiting && !p.ugly) {
124 | p.state = player.PlayerState.Selected;
125 | joinList.push(p);
126 | }
127 | }
128 |
129 | state.announce('SYSTEM', 'Randomly selected ' + joinList.length + ' players.');
130 |
131 | var room: game.Game = state.getOrCreateGame(gameId);
132 | room.name = gameName;
133 | room.gameType = game.GameType.Offical;
134 | state.saveGames();
135 |
136 | state.announce('SYSTEM', 'Commencing join to room.');
137 |
138 | for (var i = 0; i < joinList.length; i++) {
139 | var p2 = joinList[i];
140 | p2.joinGame(gameId, retryTime);
141 | }
142 |
143 | res.redirect("/");
144 | });
145 |
146 | // display logs
147 | app.get("/api/logs/:count", filterMod, needLogin, function (req, res) {
148 |
149 | var count = req.params.count;
150 |
151 | var length = log.logs.length;
152 | var start = length - count;
153 |
154 |
155 | if (start < 0) {
156 | start = 0;
157 | }
158 |
159 | var end = start + count;
160 | if (end > log.logs.length) {
161 | end = log.logs.length;
162 | }
163 |
164 | var result = [];
165 |
166 | result.push( "req:" + count + "start:" + start + "end:" + end );
167 |
168 | for (var i = end-1; i >= start; i--) {
169 | result.push( i + log.logs[i]);
170 | }
171 |
172 | res.send(result.join("\n"));
173 | });
174 |
175 |
176 | app.post("/api/login", filterMod, function (req, res) {
177 | if (req.body.password == config.adminPassword) {
178 | var sessionStr = tools.randomStr(16);
179 | res.cookie("session", sessionStr);
180 | sessions[sessionStr] = { login: true, ip: req.ip };
181 | res.redirect("/");
182 | return;
183 | }
184 |
185 | res.redirect("/?failed=1");
186 | });
187 |
188 | function needLogin(req, res, next) {
189 |
190 | if (!checkLogin(req)) {
191 | var args = { loginFailed: false }
192 | if (req.query.failed == "1") {
193 | args["loginFailed"] = true;
194 | }
195 | res.render("login", args);
196 | return;
197 | }
198 |
199 | next();
200 | }
201 |
202 | function getSessionData(req: express.Request) {
203 | if (typeof req.cookies == "undefined") {
204 | return false;
205 | }
206 |
207 | if (typeof req.cookies.session == 'undefined') {
208 | return false;
209 | }
210 |
211 | var sessionId = req.cookies.session;
212 | return sessions[sessionId];
213 | }
214 |
215 | function checkLogin(req: express.Request): boolean {
216 | var sessionData = getSessionData(req);
217 | if (sessionData == null) {
218 | return false;
219 | }
220 |
221 | if (typeof sessionData.ip !== "undefined")
222 | {
223 | if (sessionData.ip != req.ip) {
224 | return false;
225 | }
226 | }
227 |
228 | if (typeof sessionData.login !== "undefined") {
229 | return sessionData.login;
230 | }
231 |
232 | return false;
233 | }
234 |
235 | import pollen = require('./Pollen');
236 |
237 | var appServer = app.listen(port);
238 |
239 | var server = new pollen.PollenServer(app);
240 |
241 | import validator = require("validator");
242 |
243 | //var server = io.listen(37005, { pingInterval: 5000, allowUpgrades: false, transports: ['polling'] });
244 |
245 | server.on('connection', function (socket: pollen.PollenSocket) {
246 |
247 | socket.on('hello', function (data) {
248 | var p = state.getOrCreatePlayer(data.id);
249 | p.steamName = data.name;
250 | p.playerSocket = socket;
251 | socket["player"] = p;
252 |
253 | state.playerJoined(p);
254 | p.sendHello();
255 | });
256 |
257 | socket.on('heartbeat', function (data) {
258 |
259 | var p: player.Player = socket["player"];
260 | if (p != null) {
261 |
262 | var cur = new Date();
263 | p.lastHeartBeat = cur.getTime();
264 | if (typeof data != "undefined" && data != null) {
265 | if ("likenews" in data && "wormholes" in data) {
266 | if (!validator.isInt(data.likenews) || !validator.isInt(data.wormholes)) {
267 | log.info("Troll detected: " + p.steamName);
268 | }
269 | else {
270 | p.likenewCount = parseInt(data.likenews);
271 | p.wormholeCount = parseInt(data.wormholes);
272 | }
273 | }
274 |
275 | if (data.gameid !== "undefined") {
276 | if (validator.isInt(data.gameid)) {
277 | if (data.gameid == 0) {
278 | p.playerLeavedGame();
279 | }
280 | else {
281 | p.playerMadeIntoGame(parseInt(data.gameid));
282 | }
283 | }
284 | }
285 | }
286 |
287 | p.sendHello();
288 | }
289 | });
290 |
291 | socket.on('disconnect', function () {
292 | var p = socket["player"];
293 | if (p != null) {
294 | state.playerConnectionLost(p, socket);
295 | }
296 | });
297 |
298 | });
299 |
300 | server.start();
301 |
302 | log.info("Server started on port " + port);
303 |
304 |
--------------------------------------------------------------------------------
/ipfilter.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Express - IP Filter
3 | * Copyright(c) 2014 Bradley and Montgomery Inc.
4 | * MIT Licensed
5 | */
6 |
7 | 'use strict';
8 |
9 | /**
10 | * Module dependencies.
11 | */
12 | var _ = require('lodash'),
13 | iputil = require('ip'),
14 | Netmask = require('netmask').Netmask;
15 |
16 | /**
17 | * express-ipfilter:
18 | *
19 | * IP Filtering middleware;
20 | *
21 | * Examples:
22 | *
23 | * var ipfilter = require('ipfilter'),
24 | * ips = ['127.0.0.1'];
25 | *
26 | * app.use(ipfilter(ips));
27 | *
28 | * Options:
29 | *
30 | * - `mode` whether to deny or grant access to the IPs provided. Defaults to 'deny'.
31 | * - `log` console log actions. Defaults to true.
32 | * - `errorCode` the HTTP status code to use when denying access. Defaults to 401.
33 | * - `errorMessage` the error message to use when denying access. Defaults to 'Unauthorized'.
34 | * - `allowPrivateIPs` whether to grant access to any IP using the private IP address space unless explicitly denied. Defaults to false.
35 | * - 'cidr' whether ips are ips with a submnet mask. Defaults to 'false'.
36 | * - 'ranges' whether ranges are supplied as ips
37 | * - 'excluding' routes that should be excluded from ip filtering
38 | *
39 | * @param [Array] IP addresses
40 | * @param {Object} options
41 | * @api public
42 | */
43 | module.exports = function ipfilter(ips, opts) {
44 | ips = ips || false;
45 |
46 | var logger = function(message){ console.log(message);};
47 | var settings = _.defaults( opts || {}, {
48 | mode: 'deny',
49 | log: true,
50 | logF: logger,
51 | errorCode: 401,
52 | errorMessage: 'Unauthorized',
53 | allowPrivateIPs: false,
54 | cidr: false,
55 | ranges: false,
56 | excluding: []
57 | });
58 |
59 | var getClientIp = function(req) {
60 | var ipAddress = req.connection.remoteAddress;
61 | if (ipAddress === "::1") return "127.0.0.1";
62 | if (ipAddress.indexOf('::ffff:') == 0)
63 | ipAddress = ipAddress.substr(7);
64 |
65 | return ipAddress;
66 | };
67 |
68 | var matchClientIp = function(ip){
69 | var mode = settings.mode.toLowerCase(),
70 | allowedIp = false,
71 | notBannedIp = false,
72 | isPrivateIpOkay = false; // Normalize mode
73 |
74 | if(settings.cidr){
75 | for(var i = 0; i < ips.length; i++){
76 |
77 | var block = new Netmask(ips[i]);
78 |
79 | if(block.contains(ip)){
80 | allowedIp = (mode === 'allow');
81 | if(mode === 'deny'){
82 | notBannedIp = false;
83 | }
84 | break;
85 | }else{
86 | notBannedIp = (mode === 'deny');
87 | isPrivateIpOkay = settings.allowPrivateIPs && iputil.isPrivate(ip);
88 | }
89 | }
90 | }else if(settings.ranges){
91 | var filteredSet = _.filter(ips,function(ipSet){
92 | if(ipSet.length > 1){
93 | var startIp = iputil.toLong(ipSet[0]);
94 | var endIp = iputil.toLong(ipSet[1]);
95 | var longIp = iputil.toLong(ip);
96 | return longIp >= startIp && longIp <= endIp;
97 | }else{
98 | return ip === ipSet[0];
99 | }
100 | });
101 |
102 | allowedIp = (mode === 'allow' && filteredSet.length > 0);
103 | notBannedIp = (mode === 'deny' && filteredSet.length === 0);
104 | isPrivateIpOkay = settings.allowPrivateIPs && iputil.isPrivate(ip) && !(mode === 'deny' && filteredSet.length > 0);
105 | }else{
106 | allowedIp = (mode === 'allow' && ips.indexOf(ip) !== -1);
107 | notBannedIp = (mode === 'deny' && ips.indexOf(ip) === -1);
108 | isPrivateIpOkay = settings.allowPrivateIPs && iputil.isPrivate(ip) && !(mode === 'deny' && ips.indexOf(ip) !== -1);
109 | }
110 |
111 | return allowedIp || notBannedIp || isPrivateIpOkay;
112 | };
113 |
114 | return function(req, res, next) {
115 | if(settings.excluding.length > 0){
116 | var results = _.filter(settings.excluding,function(exclude){
117 | var regex = new RegExp(exclude);
118 | return regex.test(req.url);
119 | });
120 |
121 | if(results.length > 0){
122 | if(settings.log){
123 | console.log('Access granted for excluded path: ' + results[0]);
124 | }
125 | return next();
126 | }
127 | }
128 |
129 | var ip = getClientIp(req);
130 | // If no IPs were specified, skip
131 | // this middleware
132 | if(!ips || !ips.length) { return next(); }
133 |
134 | if(matchClientIp(ip,req)) {
135 | // Grant access
136 | if(settings.log) {
137 | settings.logF('Access granted to IP address: ' + ip);
138 | }
139 |
140 | return next();
141 | }
142 |
143 | // Deny access
144 | if(settings.log) {
145 | settings.logF('Access denied to IP address: ' + ip);
146 | }
147 |
148 | res.statusCode = settings.errorCode;
149 | return res.end(settings.errorMessage);
150 | };
151 | };
152 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "SteamMonsterGameMaster.js",
3 | "version": "0.0.0",
4 | "description": "SteamMonsterGameMaster.js",
5 | "main": "app.js",
6 | "author": {
7 | "name": "codetorex",
8 | "email": ""
9 | },
10 | "dependencies": {
11 | "express": "^4.12.4",
12 | "jade": "^1.11.0"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/public/LocalHostLoader.user.js:
--------------------------------------------------------------------------------
1 | // ==UserScript==
2 | // @name LOCALHOST LOADER
3 | // @namespace https://github.com/codetorex/SteamMonsterLobby
4 | // @description A script that runs the Steam Monster Minigame for you. Now with megajump. Brought to you by the Ye Olde Wormhole Schemers and DannyDaemonic
5 | // @version 5.0.2
6 | // @match *://steamcommunity.com/minigame*
7 | // @match *://steamcommunity.com//minigame*
8 | // @match *://steamcommunity.com/minigame/towerattack*
9 | // @match *://steamcommunity.com//minigame/towerattack*
10 | // @grant GM_xmlhttpRequest
11 | // ==/UserScript==
12 |
13 | (function (x) {
14 |
15 | // Options
16 | var script_url = 'http://localhost:3900/script';
17 | var loader_version = '5.0.2';
18 |
19 | // Load the actual script
20 | GM_xmlhttpRequest({
21 | method: "GET",
22 | url: script_url,
23 | onload: function (response) {
24 | var scriptElement = document.createElement("script");
25 | scriptElement.type = "text/javascript";
26 | scriptElement.innerHTML = response.responseText;
27 | document.body.appendChild(scriptElement);
28 | }
29 | });
30 |
31 | }(window));
32 |
--------------------------------------------------------------------------------
/public/MonsterLobby.user.js:
--------------------------------------------------------------------------------
1 | // ==UserScript==
2 | // @name LOBBY SCRIPT DISABLER
3 | // @namespace https://github.com/codetorex/SteamMonsterLobby
4 | // @description Auto-join script for 2015 Summer Steam Monster Minigame
5 | // @match http://example.org/
6 | // @updateURL http://example.org/script.js
7 | // @downloadURL http://example.org/script.js
8 | // @grant none
9 | // ==/UserScript==
10 | // Makes sure no more script updates
--------------------------------------------------------------------------------
/public/PollenClient.js:
--------------------------------------------------------------------------------
1 | ///
2 | function Emitter(obj) {
3 | if (obj)
4 | return mixin(obj);
5 | }
6 | ;
7 | function mixin(obj) {
8 | for (var key in Emitter.prototype) {
9 | obj[key] = Emitter.prototype[key];
10 | }
11 | return obj;
12 | }
13 | Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
14 | this._callbacks = this._callbacks || {};
15 | (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
16 | return this;
17 | };
18 | Emitter.prototype.once = function (event, fn) {
19 | function on() {
20 | this.off(event, on);
21 | fn.apply(this, arguments);
22 | }
23 | on['fn'] = fn;
24 | this.on(event, on);
25 | return this;
26 | };
27 | Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
28 | this._callbacks = this._callbacks || {};
29 | // all
30 | if (0 == arguments.length) {
31 | this._callbacks = {};
32 | return this;
33 | }
34 | // specific event
35 | var callbacks = this._callbacks['$' + event];
36 | if (!callbacks)
37 | return this;
38 | // remove all handlers
39 | if (1 == arguments.length) {
40 | delete this._callbacks['$' + event];
41 | return this;
42 | }
43 | // remove specific handler
44 | var cb;
45 | for (var i = 0; i < callbacks.length; i++) {
46 | cb = callbacks[i];
47 | if (cb === fn || cb.fn === fn) {
48 | callbacks.splice(i, 1);
49 | break;
50 | }
51 | }
52 | return this;
53 | };
54 | Emitter.prototype.emit = function (event) {
55 | this._callbacks = this._callbacks || {};
56 | var args = [].slice.call(arguments, 1), callbacks = this._callbacks['$' + event];
57 | if (callbacks) {
58 | callbacks = callbacks.slice(0);
59 | for (var i = 0, len = callbacks.length; i < len; ++i) {
60 | callbacks[i].apply(this, args);
61 | }
62 | }
63 | return this;
64 | };
65 | Emitter.prototype.listeners = function (event) {
66 | this._callbacks = this._callbacks || {};
67 | return this._callbacks['$' + event] || [];
68 | };
69 | Emitter.prototype.hasListeners = function (event) {
70 | return !!this.listeners(event).length;
71 | };
72 | var GreaseMonkeyRequester = (function () {
73 | function GreaseMonkeyRequester() {
74 | this.isrequesting = false;
75 | }
76 | GreaseMonkeyRequester.prototype.request = function (url, data, timeout, callback, fail) {
77 | this.isrequesting = true;
78 | var self = this;
79 | GM_xmlhttpRequest({
80 | method: "POST",
81 | url: url,
82 | data: data,
83 | timeout: timeout,
84 | headers: {
85 | "Content-Type": "application/json"
86 | },
87 | onload: function (response) {
88 | callback(response.responseText);
89 | self.isrequesting = false;
90 | },
91 | ontimeout: function (response) {
92 | fail(response);
93 | self.isrequesting = false;
94 | },
95 | onerror: function (response) {
96 | fail(response);
97 | self.isrequesting = false;
98 | },
99 | });
100 | };
101 | return GreaseMonkeyRequester;
102 | })();
103 | var XMLHttpRequester = (function () {
104 | function XMLHttpRequester() {
105 | this.isrequesting = false;
106 | }
107 | XMLHttpRequester.prototype.request = function (url, data, timeout, callback, fail) {
108 | this.isrequesting = true;
109 | var self = this;
110 | var xmlhttp = new XMLHttpRequest();
111 | xmlhttp.onload = function () {
112 | self.isrequesting = false;
113 | if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
114 | callback(xmlhttp.responseText);
115 | }
116 | };
117 | xmlhttp.timeout = timeout;
118 | xmlhttp.onerror = function () {
119 | self.isrequesting = false;
120 | fail(xmlhttp);
121 | };
122 | xmlhttp.ontimeout = function () {
123 | self.isrequesting = false;
124 | fail(xmlhttp);
125 | };
126 | xmlhttp.open("POST", url, true);
127 | xmlhttp.setRequestHeader("Content-Type", "application/json");
128 | xmlhttp.send(data);
129 | };
130 | return XMLHttpRequester;
131 | })();
132 | var PollenClient = (function () {
133 | function PollenClient(requester) {
134 | this.interval = null;
135 | this.packets = [];
136 | this.domain = '/pollen/';
137 | this.internalEvents = {};
138 | this.connected = false;
139 | this.reconnecting = false;
140 | Emitter(this.internalEvents);
141 | this.requester = requester;
142 | this.socketId = this.randomStr(16);
143 | var self = this;
144 | self.on('connect', function (data) {
145 | self.setSocketInterval(data.delay);
146 | self.reconnecting = false;
147 | self.connected = true;
148 | });
149 | self.on('reinterval', function (data) {
150 | self.setSocketInterval(data.delay);
151 | });
152 | }
153 | PollenClient.prototype.addPacket = function (event, data) {
154 | this.packets.push({ event: event, data: data });
155 | };
156 | PollenClient.prototype.emit = function (event, data) {
157 | if (!this.connected)
158 | return;
159 | this.packets.push({ event: event, data: data });
160 | };
161 | PollenClient.prototype.on = function (event, callback) {
162 | this.internalEvents.on(event, callback);
163 | };
164 | PollenClient.prototype.received = function (body) {
165 | var packets;
166 | if (typeof body == "string") {
167 | packets = JSON.parse(body);
168 | }
169 | else {
170 | packets = body;
171 | }
172 | for (var i = 0; i < packets.length; i++) {
173 | var s = packets[i];
174 | var eventName = s.event;
175 | var eventData = s.data;
176 | this.internalEvents.emit(eventName, eventData);
177 | }
178 | };
179 | PollenClient.prototype.randomStr = function (length) {
180 | var data = "0123456789abcdefghijklmnoprstqvxyz";
181 | var result = "";
182 | for (var i = 0; i < length; i++) {
183 | result += data.charAt(Math.round(Math.random() * data.length));
184 | }
185 | return result;
186 | };
187 | PollenClient.prototype.request = function () {
188 | if (this.requester.isrequesting) {
189 | return;
190 | }
191 | var url = this.url;
192 | var body = JSON.stringify(this.packets);
193 | this.packets = [];
194 | var self = this;
195 | var timeout = 10000;
196 | if (this.reconnecting == true || this.connected) {
197 | timeout = 0;
198 | }
199 | this.requester.request(this.url + this.domain + this.socketId, body, timeout, function (data) {
200 | self.received(data);
201 | }, function () {
202 | if (self.reconnecting == false) {
203 | if (self.connected) {
204 | self.internalEvents.emit('disconnect');
205 | self.connected = false;
206 | }
207 | else {
208 | self.internalEvents.emit('offline');
209 | }
210 | }
211 | else {
212 | self.packets = [];
213 | self.addPacket('connect');
214 | self.request();
215 | }
216 | });
217 | };
218 | PollenClient.prototype.setSocketInterval = function (delay) {
219 | var self = this;
220 | if (this.interval != null) {
221 | clearInterval(this.interval);
222 | }
223 | this.interval = setInterval(function () {
224 | self.request();
225 | }, delay);
226 | };
227 | PollenClient.prototype.connect = function (url) {
228 | this.url = url;
229 | this.packets = [];
230 | this.addPacket('connect');
231 | this.request();
232 | };
233 | PollenClient.prototype.reconnect = function () {
234 | this.reconnecting = true;
235 | this.packets = [];
236 | this.addPacket('connect');
237 | this.request();
238 | };
239 | return PollenClient;
240 | })();
241 | var socket = new PollenClient(new XMLHttpRequester());
242 | //# sourceMappingURL=PollenClient.js.map
--------------------------------------------------------------------------------
/public/PollenClient.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | function Emitter(obj) {
4 | if (obj) return mixin(obj);
5 | };
6 |
7 | function mixin(obj) {
8 | for (var key in Emitter.prototype) {
9 | obj[key] = Emitter.prototype[key];
10 | }
11 | return obj;
12 | }
13 |
14 | Emitter.prototype.on =
15 | Emitter.prototype.addEventListener = function (event, fn) {
16 | this._callbacks = this._callbacks || {};
17 | (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
18 | .push(fn);
19 | return this;
20 | };
21 |
22 | Emitter.prototype.once = function (event, fn: Function) {
23 | function on() {
24 | this.off(event, on);
25 | fn.apply(this, arguments);
26 | }
27 |
28 | on['fn'] = fn;
29 | this.on(event, on);
30 | return this;
31 | };
32 |
33 | Emitter.prototype.off =
34 | Emitter.prototype.removeListener =
35 | Emitter.prototype.removeAllListeners =
36 | Emitter.prototype.removeEventListener = function (event, fn) {
37 | this._callbacks = this._callbacks || {};
38 |
39 | // all
40 | if (0 == arguments.length) {
41 | this._callbacks = {};
42 | return this;
43 | }
44 |
45 | // specific event
46 | var callbacks = this._callbacks['$' + event];
47 | if (!callbacks) return this;
48 |
49 | // remove all handlers
50 | if (1 == arguments.length) {
51 | delete this._callbacks['$' + event];
52 | return this;
53 | }
54 |
55 | // remove specific handler
56 | var cb;
57 | for (var i = 0; i < callbacks.length; i++) {
58 | cb = callbacks[i];
59 | if (cb === fn || cb.fn === fn) {
60 | callbacks.splice(i, 1);
61 | break;
62 | }
63 | }
64 | return this;
65 | };
66 |
67 | Emitter.prototype.emit = function (event) {
68 | this._callbacks = this._callbacks || {};
69 | var args = [].slice.call(arguments, 1)
70 | , callbacks = this._callbacks['$' + event];
71 |
72 | if (callbacks) {
73 | callbacks = callbacks.slice(0);
74 | for (var i = 0, len = callbacks.length; i < len; ++i) {
75 | callbacks[i].apply(this, args);
76 | }
77 | }
78 |
79 | return this;
80 | };
81 |
82 | Emitter.prototype.listeners = function (event) {
83 | this._callbacks = this._callbacks || {};
84 | return this._callbacks['$' + event] || [];
85 | };
86 |
87 | Emitter.prototype.hasListeners = function (event) {
88 | return !!this.listeners(event).length;
89 | };
90 |
91 | interface PollenRequester {
92 | isrequesting: boolean;
93 | request(url: string, data: string, timeout: number, callback: Function, fail: Function);
94 | }
95 |
96 | declare var GM_xmlhttpRequest: any;
97 |
98 | class GreaseMonkeyRequester implements PollenRequester {
99 | public isrequesting: boolean = false;
100 |
101 | public request(url: string, data: string, timeout: number, callback: Function, fail: Function) {
102 | this.isrequesting = true;
103 | var self = this;
104 | GM_xmlhttpRequest({
105 | method: "POST",
106 | url: url,
107 | data: data,
108 | timeout: timeout,
109 | headers: {
110 | "Content-Type": "application/json"
111 | },
112 | onload: function (response) {
113 | callback(response.responseText);
114 | self.isrequesting = false;
115 | },
116 | ontimeout: function (response) {
117 | fail(response);
118 | self.isrequesting = false;
119 | },
120 | onerror: function (response) {
121 | fail(response);
122 | self.isrequesting = false;
123 | },
124 | });
125 | }
126 | }
127 |
128 | class XMLHttpRequester implements PollenRequester {
129 | public isrequesting: boolean = false;
130 | public request(url: string, data: string, timeout: number, callback: Function, fail: Function) {
131 | this.isrequesting = true;
132 | var self = this;
133 |
134 | var xmlhttp = new XMLHttpRequest();
135 | xmlhttp.onload = function () {
136 | self.isrequesting = false;
137 | if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
138 | callback(xmlhttp.responseText);
139 | }
140 |
141 | }
142 |
143 | xmlhttp.timeout = timeout;
144 |
145 | xmlhttp.onerror = function () {
146 | self.isrequesting = false;
147 | fail(xmlhttp);
148 |
149 | }
150 |
151 | xmlhttp.ontimeout = function () {
152 | self.isrequesting = false;
153 | fail(xmlhttp);
154 | }
155 |
156 | xmlhttp.open("POST", url, true);
157 | xmlhttp.setRequestHeader("Content-Type", "application/json");
158 | xmlhttp.send(data);
159 | }
160 | }
161 |
162 |
163 | class PollenClient {
164 | public url: string;
165 | public interval: any = null;
166 | public packets: Object[] = [];
167 | public domain: string = '/pollen/';
168 | public socketId: string;
169 |
170 | public internalEvents: any = {};
171 | public requester: PollenRequester;
172 |
173 | public connected: boolean = false;
174 | public reconnecting: boolean = false;
175 |
176 | public addPacket(event: string, data?: any) {
177 | this.packets.push({ event: event, data: data });
178 | }
179 |
180 | public emit(event: string, data?: any) {
181 | if (!this.connected) return;
182 | this.packets.push({ event: event, data: data });
183 | }
184 |
185 | public on(event: string, callback: Function) {
186 | this.internalEvents.on(event, callback);
187 | }
188 |
189 | public received(body: string) {
190 | var packets;
191 | if (typeof body == "string") {
192 | packets = JSON.parse(body);
193 | }
194 | else {
195 | packets = body;
196 | }
197 |
198 | for (var i = 0; i < packets.length; i++) {
199 | var s = packets[i];
200 | var eventName = s.event;
201 | var eventData = s.data;
202 | this.internalEvents.emit(eventName, eventData);
203 | }
204 | }
205 |
206 | public randomStr(length: number): string {
207 | var data = "0123456789abcdefghijklmnoprstqvxyz";
208 | var result = "";
209 | for (var i = 0; i < length; i++) {
210 | result += data.charAt(Math.round(Math.random() * data.length));
211 | }
212 | return result;
213 | }
214 |
215 | public request() {
216 | if (this.requester.isrequesting) {
217 | return;
218 | }
219 |
220 | var url = this.url;
221 | var body = JSON.stringify(this.packets);
222 | this.packets = [];
223 | var self = this;
224 | var timeout = 10000;
225 | if (this.reconnecting == true || this.connected) {
226 | timeout = 0;
227 | }
228 | this.requester.request(this.url + this.domain + this.socketId, body, timeout, function (data) {
229 | self.received(data);
230 | }, function () {
231 | if (self.reconnecting == false) {
232 | if (self.connected) {
233 | self.internalEvents.emit('disconnect');
234 | self.connected = false;
235 | }
236 | else {
237 | self.internalEvents.emit('offline');
238 | }
239 | }
240 | else {
241 | self.packets = [];
242 | self.addPacket('connect');
243 | self.request();
244 | }
245 | });
246 | }
247 |
248 | public setSocketInterval(delay: number) {
249 | var self = this;
250 | if (this.interval != null) {
251 | clearInterval(this.interval);
252 | }
253 |
254 | this.interval = setInterval(function () {
255 | self.request();
256 | }, delay);
257 | }
258 |
259 | public connect(url: string) {
260 | this.url = url;
261 | this.packets = [];
262 | this.addPacket('connect');
263 | this.request();
264 | }
265 |
266 | public reconnect() {
267 | this.reconnecting = true;
268 | this.packets = [];
269 | this.addPacket('connect');
270 | this.request();
271 | }
272 |
273 |
274 | public constructor(requester: PollenRequester) {
275 | Emitter(this.internalEvents);
276 | this.requester = requester;
277 | this.socketId = this.randomStr(16);
278 |
279 | var self = this;
280 | self.on('connect', function (data) {
281 | self.setSocketInterval(data.delay);
282 | self.reconnecting = false;
283 | self.connected = true;
284 | });
285 |
286 | self.on('reinterval', function (data) {
287 | self.setSocketInterval(data.delay);
288 | });
289 | }
290 | }
291 |
292 | var socket: PollenClient = new PollenClient(new XMLHttpRequester());
293 |
294 |
295 |
--------------------------------------------------------------------------------
/public/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | }
3 |
4 | .failed
5 | {
6 | color: red;
7 | }
8 |
9 | .list-group-item-text span.val
10 | {
11 | margin-right: 10px;
12 | }
13 |
14 | #lobbyControlPanel .button
15 | {
16 | margin-left: 20px;
17 | }
--------------------------------------------------------------------------------
/tpl/admin.jade:
--------------------------------------------------------------------------------
1 | doctype
2 | html
3 | head
4 | title= "Reddit Botnet Admin"
5 | script(src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js')
6 | link(rel='stylesheet', href='/style.css')
7 | link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css')
8 | link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css')
9 | script(src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js')
10 | style.
11 | #anns .usr {
12 | margin-right: 10px;
13 | color: darkorange;
14 | }
15 |
16 | .games button{
17 | position: absolute;
18 | height: 80%;
19 | top:10%;
20 | right: 10px;
21 | }
22 |
23 | .val {
24 | margin-left: 5px;
25 | margin-right: 10px;
26 | }
27 |
28 | body
29 | nav.navbar.navbar-inverse
30 | div.container
31 | div.navbar-header
32 | div.navbar-brand Reddit Botnet Admin Panel
33 | ul.nav.navbar-nav
34 | li
35 | a(href="/") Home
36 | li
37 | a Players
38 | span.badge=players.length
39 | li
40 | a Games
41 | span.badge=games.length
42 |
43 | div.container
44 | div.col-sm-12.well#tools
45 | button.btn.btn-lg.btn-default(data-toggle="modal",data-target="#join-lobby-modal")
46 | span.glyphicon.glyphicon-send
47 | | Join Game
48 |
49 | div.col-sm-12
50 | h4 Current Offical Games
51 | div.list-group.games
52 | each game, key in games
53 | if game.gameType == 1
54 | a.list-group-item.lobby(data-id=game.roomId)
55 | h4.list-group-item-heading=game.name
56 | p.list-group-item-text
57 | span Total Players
58 | span.val.badge.btn-info=game.totalPlayerCount
59 | span Known Players
60 | span.val.badge.btn-info=game.knownPlayerCount
61 | span Wormholes
62 | span.val.badge.btn-info=game.wormholeCount
63 | span Likenews
64 | span.val.badge.btn-info=game.likenewCount
65 | span Game Id
66 | span.val.badge.btn-info=game.roomId
67 | span Game Level
68 | span.val.badge.btn-info=game.level
69 | span Game Type
70 | span.val.badge.btn-info=game.gameType
71 | button.btn.btn-danger.abandoner(type="button") Abandon
72 |
73 | h4 Current Unoffical Games
74 | div.list-group.games
75 | each game, key in games
76 | if game.gameType == 0
77 | a.list-group-item.lobby(data-id=game.roomId)
78 | h4.list-group-item-heading=game.name
79 | p.list-group-item-text
80 | span Total Players
81 | span.val.badge.btn-info=game.totalPlayerCount
82 | span Known Players
83 | span.val.badge.btn-info=game.knownPlayerCount
84 | span Wormholes
85 | span.val.badge.btn-info=game.wormholeCount
86 | span Likenews
87 | span.val.badge.btn-info=game.likenewCount
88 | span Game Id
89 | span.val.badge.btn-info=game.roomId
90 | span Game Level
91 | span.val.badge.btn-info=game.level
92 | span Game Type
93 | span.val.badge.btn-info=game.gameType
94 | button.btn.btn-danger.abandoner(type="button") Abandon
95 |
96 |
97 |
98 | div.col-sm-12
99 | h4 Announcement
100 | div.well#anns(style="height:200px;")
101 | div.col-sm-8
102 | input.form-control#annmsg(type="text",value="",placeholder="Message")
103 | div.col-sm-4
104 | input.form-control#annusr(type="text",value="havenoammo")
105 |
106 |
107 |
108 | div.modal.fade#join-lobby-modal(tabindex="-1")
109 | div.modal-dialog
110 | div.modal-content
111 | div.modal-header
112 | button.close(data-dismiss="modal",aria-label="Close") ×
113 | h4.modal-title Join Game
114 | div.modal-body
115 | form#create-lobby-form(method="post", action="/api/joinGame")
116 | div.form-group
117 | label Game Name
118 | input.form-control(name="name", type="text", value="MSG215 Room #1")
119 | div.form-group
120 | label Player Count
121 | input.form-control(name="count", type="text", value="1475")
122 | div.form-group
123 | label Game Id
124 | input.form-control(name="gameid", type="text", placeholder="00000")
125 | div.form-group
126 | label Retry Timeout (seconds)
127 | input.form-control(name="retry", type="text", value="120")
128 |
129 | div.modal-footer
130 | button.btn.btn-default(data-dismiss="modal") Close
131 | button.btn.btn-primary.btn-ok(name="submit", type="submit", value="") Join
132 |
133 | script.
134 | $(document).ready( function(){
135 | $('.modal .btn-ok').click(function(){
136 | $(this).closest('.modal').find('form').submit();
137 | });
138 |
139 | function apicall(api, data, ok )
140 | {
141 | if (typeof ok === "undefined")
142 | {
143 | ok = function() {
144 | location.reload();
145 | }
146 | }
147 |
148 | $.ajax({
149 | type: "POST",
150 | url:'/api/' + api,
151 | data: data,
152 | dataType: 'json'
153 | }).done(function( data ){
154 | ok(data);
155 | });
156 | }
157 |
158 | $('.abandoner').click(function(){
159 | var gm = $(this).closest('a');
160 | console.log(gm);
161 | var gmId = parseInt( gm.attr('data-id') );
162 | console.log(gmId);
163 | apicall('abandonGame', { gameid: gmId } );
164 | });
165 |
166 |
167 | function sendChat() {
168 | var usr = $('#annusr').val();
169 | var msg = $('#annmsg').val();
170 |
171 | apicall('announcement', {usr: usr, msg: msg}, function( data ){
172 | if (data.status == 'ok')
173 | {
174 | $('#anns').append('
' + usr + '' + msg + '
');
175 | }
176 | });
177 |
178 | //socket.emit('chat', { message: msg });
179 | $('#annmsg').val('');
180 | }
181 |
182 | $('#annmsg').keyup(function (e) {
183 | if (e.keyCode == 13) {
184 | sendChat();
185 | }
186 | });
187 | });
--------------------------------------------------------------------------------
/tpl/login.jade:
--------------------------------------------------------------------------------
1 | doctype
2 | html
3 | head
4 | title= "Reddit steam summer game beating botnet main page"
5 | link(rel='stylesheet', href='/style.css')
6 | body
7 | div.login.container-fluid
8 | div You have to login to see the content.
9 | if loginFailed
10 | .failed
11 | | Login failed
12 | | Admin Password:
13 | form(method='post', action='/api/login')
14 | input#password(name='password',style='width:350px;')
15 | br
16 | input#send(type='submit', value='Login')
--------------------------------------------------------------------------------
/typings/body-parser/body-parser.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for body-parser
2 | // Project: http://expressjs.com
3 | // Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle
4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped
5 |
6 | ///
7 |
8 | declare module "body-parser" {
9 | import express = require('express');
10 |
11 | /**
12 | * bodyParser: use individual json/urlencoded middlewares
13 | * @deprecated
14 | */
15 |
16 | function bodyParser(options?: {
17 | /**
18 | * if deflated bodies will be inflated. (default: true)
19 | */
20 | inflate?: boolean;
21 | /**
22 | * maximum request body size. (default: '100kb')
23 | */
24 | limit?: any;
25 | /**
26 | * function to verify body content, the parsing can be aborted by throwing an error.
27 | */
28 | verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
29 | /**
30 | * only parse objects and arrays. (default: true)
31 | */
32 | strict?: boolean;
33 | /**
34 | * passed to JSON.parse().
35 | */
36 | receiver?: (key: string, value: any) => any;
37 | /**
38 | * parse extended syntax with the qs module. (default: true)
39 | */
40 | extended?: boolean;
41 | }): express.RequestHandler;
42 |
43 | module bodyParser {
44 | export function json(options?: {
45 | /**
46 | * if deflated bodies will be inflated. (default: true)
47 | */
48 | inflate?: boolean;
49 | /**
50 | * maximum request body size. (default: '100kb')
51 | */
52 | limit?: any;
53 | /**
54 | * request content-type to parse, passed directly to the type-is library. (default: 'json')
55 | */
56 | type?: any;
57 | /**
58 | * function to verify body content, the parsing can be aborted by throwing an error.
59 | */
60 | verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
61 | /**
62 | * only parse objects and arrays. (default: true)
63 | */
64 | strict?: boolean;
65 | /**
66 | * passed to JSON.parse().
67 | */
68 | receiver?: (key: string, value: any) => any;
69 | }): express.RequestHandler;
70 |
71 | export function raw(options?: {
72 | /**
73 | * if deflated bodies will be inflated. (default: true)
74 | */
75 | inflate?: boolean;
76 | /**
77 | * maximum request body size. (default: '100kb')
78 | */
79 | limit?: any;
80 | /**
81 | * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream')
82 | */
83 | type?: any;
84 | /**
85 | * function to verify body content, the parsing can be aborted by throwing an error.
86 | */
87 | verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
88 | }): express.RequestHandler;
89 |
90 | export function text(options?: {
91 | /**
92 | * if deflated bodies will be inflated. (default: true)
93 | */
94 | inflate?: boolean;
95 | /**
96 | * maximum request body size. (default: '100kb')
97 | */
98 | limit?: any;
99 | /**
100 | * request content-type to parse, passed directly to the type-is library. (default: 'text/plain')
101 | */
102 | type?: any;
103 | /**
104 | * function to verify body content, the parsing can be aborted by throwing an error.
105 | */
106 | verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
107 | /**
108 | * the default charset to parse as, if not specified in content-type. (default: 'utf-8')
109 | */
110 | defaultCharset?: string;
111 | }): express.RequestHandler;
112 |
113 | export function urlencoded(options?: {
114 | /**
115 | * if deflated bodies will be inflated. (default: true)
116 | */
117 | inflate?: boolean;
118 | /**
119 | * maximum request body size. (default: '100kb')
120 | */
121 | limit?: any;
122 | /**
123 | * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded')
124 | */
125 | type?: any;
126 | /**
127 | * function to verify body content, the parsing can be aborted by throwing an error.
128 | */
129 | verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
130 | /**
131 | * parse extended syntax with the qs module. (default: true)
132 | */
133 | extended?: boolean;
134 | }): express.RequestHandler;
135 | }
136 |
137 | export = bodyParser;
138 | }
--------------------------------------------------------------------------------
/typings/form-data/form-data.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for form-data
2 | // Project: https://github.com/felixge/node-form-data
3 | // Definitions by: Carlos Ballesteros Velasco
4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped
5 |
6 | // Imported from: https://github.com/soywiz/typescript-node-definitions/form-data.d.ts
7 |
8 | declare module "form-data" {
9 | export class FormData {
10 | append(key: string, value: any): FormData;
11 | getHeaders(): Object;
12 | // TODO expand pipe
13 | pipe(to: any): any;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/typings/node/node.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for Node.js v0.12.0
2 | // Project: http://nodejs.org/
3 | // Definitions by: Microsoft TypeScript , DefinitelyTyped
4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped
5 |
6 | /************************************************
7 | * *
8 | * Node.js v0.12.0 API *
9 | * *
10 | ************************************************/
11 |
12 | /************************************************
13 | * *
14 | * GLOBAL *
15 | * *
16 | ************************************************/
17 | declare var process: NodeJS.Process;
18 | declare var global: NodeJS.Global;
19 |
20 | declare var __filename: string;
21 | declare var __dirname: string;
22 |
23 | declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
24 | declare function clearTimeout(timeoutId: NodeJS.Timer): void;
25 | declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
26 | declare function clearInterval(intervalId: NodeJS.Timer): void;
27 | declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any;
28 | declare function clearImmediate(immediateId: any): void;
29 |
30 | declare var require: {
31 | (id: string): any;
32 | resolve(id:string): string;
33 | cache: any;
34 | extensions: any;
35 | main: any;
36 | };
37 |
38 | declare var module: {
39 | exports: any;
40 | require(id: string): any;
41 | id: string;
42 | filename: string;
43 | loaded: boolean;
44 | parent: any;
45 | children: any[];
46 | };
47 |
48 | // Same as module.exports
49 | declare var exports: any;
50 | declare var SlowBuffer: {
51 | new (str: string, encoding?: string): Buffer;
52 | new (size: number): Buffer;
53 | new (size: Uint8Array): Buffer;
54 | new (array: any[]): Buffer;
55 | prototype: Buffer;
56 | isBuffer(obj: any): boolean;
57 | byteLength(string: string, encoding?: string): number;
58 | concat(list: Buffer[], totalLength?: number): Buffer;
59 | };
60 |
61 |
62 | // Buffer class
63 | interface Buffer extends NodeBuffer {}
64 |
65 | /**
66 | * Raw data is stored in instances of the Buffer class.
67 | * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
68 | * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
69 | */
70 | declare var Buffer: {
71 | /**
72 | * Allocates a new buffer containing the given {str}.
73 | *
74 | * @param str String to store in buffer.
75 | * @param encoding encoding to use, optional. Default is 'utf8'
76 | */
77 | new (str: string, encoding?: string): Buffer;
78 | /**
79 | * Allocates a new buffer of {size} octets.
80 | *
81 | * @param size count of octets to allocate.
82 | */
83 | new (size: number): Buffer;
84 | /**
85 | * Allocates a new buffer containing the given {array} of octets.
86 | *
87 | * @param array The octets to store.
88 | */
89 | new (array: Uint8Array): Buffer;
90 | /**
91 | * Allocates a new buffer containing the given {array} of octets.
92 | *
93 | * @param array The octets to store.
94 | */
95 | new (array: any[]): Buffer;
96 | prototype: Buffer;
97 | /**
98 | * Returns true if {obj} is a Buffer
99 | *
100 | * @param obj object to test.
101 | */
102 | isBuffer(obj: any): boolean;
103 | /**
104 | * Returns true if {encoding} is a valid encoding argument.
105 | * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
106 | *
107 | * @param encoding string to test.
108 | */
109 | isEncoding(encoding: string): boolean;
110 | /**
111 | * Gives the actual byte length of a string. encoding defaults to 'utf8'.
112 | * This is not the same as String.prototype.length since that returns the number of characters in a string.
113 | *
114 | * @param string string to test.
115 | * @param encoding encoding used to evaluate (defaults to 'utf8')
116 | */
117 | byteLength(string: string, encoding?: string): number;
118 | /**
119 | * Returns a buffer which is the result of concatenating all the buffers in the list together.
120 | *
121 | * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
122 | * If the list has exactly one item, then the first item of the list is returned.
123 | * If the list has more than one item, then a new Buffer is created.
124 | *
125 | * @param list An array of Buffer objects to concatenate
126 | * @param totalLength Total length of the buffers when concatenated.
127 | * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
128 | */
129 | concat(list: Buffer[], totalLength?: number): Buffer;
130 | };
131 |
132 | /************************************************
133 | * *
134 | * GLOBAL INTERFACES *
135 | * *
136 | ************************************************/
137 | declare module NodeJS {
138 | export interface ErrnoException extends Error {
139 | errno?: number;
140 | code?: string;
141 | path?: string;
142 | syscall?: string;
143 | }
144 |
145 | export interface EventEmitter {
146 | addListener(event: string, listener: Function): EventEmitter;
147 | on(event: string, listener: Function): EventEmitter;
148 | once(event: string, listener: Function): EventEmitter;
149 | removeListener(event: string, listener: Function): EventEmitter;
150 | removeAllListeners(event?: string): EventEmitter;
151 | setMaxListeners(n: number): void;
152 | listeners(event: string): Function[];
153 | emit(event: string, ...args: any[]): boolean;
154 | }
155 |
156 | export interface ReadableStream extends EventEmitter {
157 | readable: boolean;
158 | read(size?: number): string|Buffer;
159 | setEncoding(encoding: string): void;
160 | pause(): void;
161 | resume(): void;
162 | pipe(destination: T, options?: { end?: boolean; }): T;
163 | unpipe(destination?: T): void;
164 | unshift(chunk: string): void;
165 | unshift(chunk: Buffer): void;
166 | wrap(oldStream: ReadableStream): ReadableStream;
167 | }
168 |
169 | export interface WritableStream extends EventEmitter {
170 | writable: boolean;
171 | write(buffer: Buffer, cb?: Function): boolean;
172 | write(str: string, cb?: Function): boolean;
173 | write(str: string, encoding?: string, cb?: Function): boolean;
174 | end(): void;
175 | end(buffer: Buffer, cb?: Function): void;
176 | end(str: string, cb?: Function): void;
177 | end(str: string, encoding?: string, cb?: Function): void;
178 | }
179 |
180 | export interface ReadWriteStream extends ReadableStream, WritableStream {}
181 |
182 | export interface Process extends EventEmitter {
183 | stdout: WritableStream;
184 | stderr: WritableStream;
185 | stdin: ReadableStream;
186 | argv: string[];
187 | execPath: string;
188 | abort(): void;
189 | chdir(directory: string): void;
190 | cwd(): string;
191 | env: any;
192 | exit(code?: number): void;
193 | getgid(): number;
194 | setgid(id: number): void;
195 | setgid(id: string): void;
196 | getuid(): number;
197 | setuid(id: number): void;
198 | setuid(id: string): void;
199 | version: string;
200 | versions: {
201 | http_parser: string;
202 | node: string;
203 | v8: string;
204 | ares: string;
205 | uv: string;
206 | zlib: string;
207 | openssl: string;
208 | };
209 | config: {
210 | target_defaults: {
211 | cflags: any[];
212 | default_configuration: string;
213 | defines: string[];
214 | include_dirs: string[];
215 | libraries: string[];
216 | };
217 | variables: {
218 | clang: number;
219 | host_arch: string;
220 | node_install_npm: boolean;
221 | node_install_waf: boolean;
222 | node_prefix: string;
223 | node_shared_openssl: boolean;
224 | node_shared_v8: boolean;
225 | node_shared_zlib: boolean;
226 | node_use_dtrace: boolean;
227 | node_use_etw: boolean;
228 | node_use_openssl: boolean;
229 | target_arch: string;
230 | v8_no_strict_aliasing: number;
231 | v8_use_snapshot: boolean;
232 | visibility: string;
233 | };
234 | };
235 | kill(pid: number, signal?: string): void;
236 | pid: number;
237 | title: string;
238 | arch: string;
239 | platform: string;
240 | memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; };
241 | nextTick(callback: Function): void;
242 | umask(mask?: number): number;
243 | uptime(): number;
244 | hrtime(time?:number[]): number[];
245 |
246 | // Worker
247 | send?(message: any, sendHandle?: any): void;
248 | }
249 |
250 | export interface Global {
251 | Array: typeof Array;
252 | ArrayBuffer: typeof ArrayBuffer;
253 | Boolean: typeof Boolean;
254 | Buffer: typeof Buffer;
255 | DataView: typeof DataView;
256 | Date: typeof Date;
257 | Error: typeof Error;
258 | EvalError: typeof EvalError;
259 | Float32Array: typeof Float32Array;
260 | Float64Array: typeof Float64Array;
261 | Function: typeof Function;
262 | GLOBAL: Global;
263 | Infinity: typeof Infinity;
264 | Int16Array: typeof Int16Array;
265 | Int32Array: typeof Int32Array;
266 | Int8Array: typeof Int8Array;
267 | Intl: typeof Intl;
268 | JSON: typeof JSON;
269 | Map: typeof Map;
270 | Math: typeof Math;
271 | NaN: typeof NaN;
272 | Number: typeof Number;
273 | Object: typeof Object;
274 | Promise: Function;
275 | RangeError: typeof RangeError;
276 | ReferenceError: typeof ReferenceError;
277 | RegExp: typeof RegExp;
278 | Set: typeof Set;
279 | String: typeof String;
280 | Symbol: Function;
281 | SyntaxError: typeof SyntaxError;
282 | TypeError: typeof TypeError;
283 | URIError: typeof URIError;
284 | Uint16Array: typeof Uint16Array;
285 | Uint32Array: typeof Uint32Array;
286 | Uint8Array: typeof Uint8Array;
287 | Uint8ClampedArray: Function;
288 | WeakMap: typeof WeakMap;
289 | WeakSet: Function;
290 | clearImmediate: (immediateId: any) => void;
291 | clearInterval: (intervalId: NodeJS.Timer) => void;
292 | clearTimeout: (timeoutId: NodeJS.Timer) => void;
293 | console: typeof console;
294 | decodeURI: typeof decodeURI;
295 | decodeURIComponent: typeof decodeURIComponent;
296 | encodeURI: typeof encodeURI;
297 | encodeURIComponent: typeof encodeURIComponent;
298 | escape: (str: string) => string;
299 | eval: typeof eval;
300 | global: Global;
301 | isFinite: typeof isFinite;
302 | isNaN: typeof isNaN;
303 | parseFloat: typeof parseFloat;
304 | parseInt: typeof parseInt;
305 | process: Process;
306 | root: Global;
307 | setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any;
308 | setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;
309 | setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;
310 | undefined: typeof undefined;
311 | unescape: (str: string) => string;
312 | gc: () => void;
313 | }
314 |
315 | export interface Timer {
316 | ref() : void;
317 | unref() : void;
318 | }
319 | }
320 |
321 | /**
322 | * @deprecated
323 | */
324 | interface NodeBuffer {
325 | [index: number]: number;
326 | write(string: string, offset?: number, length?: number, encoding?: string): number;
327 | toString(encoding?: string, start?: number, end?: number): string;
328 | toJSON(): any;
329 | length: number;
330 | copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
331 | slice(start?: number, end?: number): Buffer;
332 | writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
333 | writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
334 | writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
335 | writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
336 | readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
337 | readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
338 | readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
339 | readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
340 | readUInt8(offset: number, noAsset?: boolean): number;
341 | readUInt16LE(offset: number, noAssert?: boolean): number;
342 | readUInt16BE(offset: number, noAssert?: boolean): number;
343 | readUInt32LE(offset: number, noAssert?: boolean): number;
344 | readUInt32BE(offset: number, noAssert?: boolean): number;
345 | readInt8(offset: number, noAssert?: boolean): number;
346 | readInt16LE(offset: number, noAssert?: boolean): number;
347 | readInt16BE(offset: number, noAssert?: boolean): number;
348 | readInt32LE(offset: number, noAssert?: boolean): number;
349 | readInt32BE(offset: number, noAssert?: boolean): number;
350 | readFloatLE(offset: number, noAssert?: boolean): number;
351 | readFloatBE(offset: number, noAssert?: boolean): number;
352 | readDoubleLE(offset: number, noAssert?: boolean): number;
353 | readDoubleBE(offset: number, noAssert?: boolean): number;
354 | writeUInt8(value: number, offset: number, noAssert?: boolean): void;
355 | writeUInt16LE(value: number, offset: number, noAssert?: boolean): void;
356 | writeUInt16BE(value: number, offset: number, noAssert?: boolean): void;
357 | writeUInt32LE(value: number, offset: number, noAssert?: boolean): void;
358 | writeUInt32BE(value: number, offset: number, noAssert?: boolean): void;
359 | writeInt8(value: number, offset: number, noAssert?: boolean): void;
360 | writeInt16LE(value: number, offset: number, noAssert?: boolean): void;
361 | writeInt16BE(value: number, offset: number, noAssert?: boolean): void;
362 | writeInt32LE(value: number, offset: number, noAssert?: boolean): void;
363 | writeInt32BE(value: number, offset: number, noAssert?: boolean): void;
364 | writeFloatLE(value: number, offset: number, noAssert?: boolean): void;
365 | writeFloatBE(value: number, offset: number, noAssert?: boolean): void;
366 | writeDoubleLE(value: number, offset: number, noAssert?: boolean): void;
367 | writeDoubleBE(value: number, offset: number, noAssert?: boolean): void;
368 | fill(value: any, offset?: number, end?: number): void;
369 | }
370 |
371 | /************************************************
372 | * *
373 | * MODULES *
374 | * *
375 | ************************************************/
376 | declare module "buffer" {
377 | export var INSPECT_MAX_BYTES: number;
378 | }
379 |
380 | declare module "querystring" {
381 | export function stringify(obj: any, sep?: string, eq?: string): string;
382 | export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any;
383 | export function escape(str: string): string;
384 | export function unescape(str: string): string;
385 | }
386 |
387 | declare module "events" {
388 | export class EventEmitter implements NodeJS.EventEmitter {
389 | static listenerCount(emitter: EventEmitter, event: string): number;
390 |
391 | addListener(event: string, listener: Function): EventEmitter;
392 | on(event: string, listener: Function): EventEmitter;
393 | once(event: string, listener: Function): EventEmitter;
394 | removeListener(event: string, listener: Function): EventEmitter;
395 | removeAllListeners(event?: string): EventEmitter;
396 | setMaxListeners(n: number): void;
397 | listeners(event: string): Function[];
398 | emit(event: string, ...args: any[]): boolean;
399 | }
400 | }
401 |
402 | declare module "http" {
403 | import events = require("events");
404 | import net = require("net");
405 | import stream = require("stream");
406 |
407 | export interface Server extends events.EventEmitter {
408 | listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server;
409 | listen(port: number, hostname?: string, callback?: Function): Server;
410 | listen(path: string, callback?: Function): Server;
411 | listen(handle: any, listeningListener?: Function): Server;
412 | close(cb?: any): Server;
413 | address(): { port: number; family: string; address: string; };
414 | maxHeadersCount: number;
415 | }
416 | /**
417 | * @deprecated Use IncomingMessage
418 | */
419 | export interface ServerRequest extends IncomingMessage {
420 | connection: net.Socket;
421 | }
422 | export interface ServerResponse extends events.EventEmitter, stream.Writable {
423 | // Extended base methods
424 | write(buffer: Buffer): boolean;
425 | write(buffer: Buffer, cb?: Function): boolean;
426 | write(str: string, cb?: Function): boolean;
427 | write(str: string, encoding?: string, cb?: Function): boolean;
428 | write(str: string, encoding?: string, fd?: string): boolean;
429 |
430 | writeContinue(): void;
431 | writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void;
432 | writeHead(statusCode: number, headers?: any): void;
433 | statusCode: number;
434 | setHeader(name: string, value: string): void;
435 | sendDate: boolean;
436 | getHeader(name: string): string;
437 | removeHeader(name: string): void;
438 | write(chunk: any, encoding?: string): any;
439 | addTrailers(headers: any): void;
440 |
441 | // Extended base methods
442 | end(): void;
443 | end(buffer: Buffer, cb?: Function): void;
444 | end(str: string, cb?: Function): void;
445 | end(str: string, encoding?: string, cb?: Function): void;
446 | end(data?: any, encoding?: string): void;
447 | }
448 | export interface ClientRequest extends events.EventEmitter, stream.Writable {
449 | // Extended base methods
450 | write(buffer: Buffer): boolean;
451 | write(buffer: Buffer, cb?: Function): boolean;
452 | write(str: string, cb?: Function): boolean;
453 | write(str: string, encoding?: string, cb?: Function): boolean;
454 | write(str: string, encoding?: string, fd?: string): boolean;
455 |
456 | write(chunk: any, encoding?: string): void;
457 | abort(): void;
458 | setTimeout(timeout: number, callback?: Function): void;
459 | setNoDelay(noDelay?: boolean): void;
460 | setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;
461 |
462 | // Extended base methods
463 | end(): void;
464 | end(buffer: Buffer, cb?: Function): void;
465 | end(str: string, cb?: Function): void;
466 | end(str: string, encoding?: string, cb?: Function): void;
467 | end(data?: any, encoding?: string): void;
468 | }
469 | export interface IncomingMessage extends events.EventEmitter, stream.Readable {
470 | httpVersion: string;
471 | headers: any;
472 | rawHeaders: string[];
473 | trailers: any;
474 | rawTrailers: any;
475 | setTimeout(msecs: number, callback: Function): NodeJS.Timer;
476 | /**
477 | * Only valid for request obtained from http.Server.
478 | */
479 | method?: string;
480 | /**
481 | * Only valid for request obtained from http.Server.
482 | */
483 | url?: string;
484 | /**
485 | * Only valid for response obtained from http.ClientRequest.
486 | */
487 | statusCode?: number;
488 | /**
489 | * Only valid for response obtained from http.ClientRequest.
490 | */
491 | statusMessage?: string;
492 | socket: net.Socket;
493 | }
494 | /**
495 | * @deprecated Use IncomingMessage
496 | */
497 | export interface ClientResponse extends IncomingMessage { }
498 |
499 | export interface AgentOptions {
500 | /**
501 | * Keep sockets around in a pool to be used by other requests in the future. Default = false
502 | */
503 | keepAlive?: boolean;
504 | /**
505 | * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
506 | * Only relevant if keepAlive is set to true.
507 | */
508 | keepAliveMsecs?: number;
509 | /**
510 | * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
511 | */
512 | maxSockets?: number;
513 | /**
514 | * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
515 | */
516 | maxFreeSockets?: number;
517 | }
518 |
519 | export class Agent {
520 | maxSockets: number;
521 | sockets: any;
522 | requests: any;
523 |
524 | constructor(opts?: AgentOptions);
525 |
526 | /**
527 | * Destroy any sockets that are currently in use by the agent.
528 | * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled,
529 | * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise,
530 | * sockets may hang open for quite a long time before the server terminates them.
531 | */
532 | destroy(): void;
533 | }
534 |
535 | export var STATUS_CODES: {
536 | [errorCode: number]: string;
537 | [errorCode: string]: string;
538 | };
539 | export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server;
540 | export function createClient(port?: number, host?: string): any;
541 | export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest;
542 | export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest;
543 | export var globalAgent: Agent;
544 | }
545 |
546 | declare module "cluster" {
547 | import child = require("child_process");
548 | import events = require("events");
549 |
550 | export interface ClusterSettings {
551 | exec?: string;
552 | args?: string[];
553 | silent?: boolean;
554 | }
555 |
556 | export class Worker extends events.EventEmitter {
557 | id: string;
558 | process: child.ChildProcess;
559 | suicide: boolean;
560 | send(message: any, sendHandle?: any): void;
561 | kill(signal?: string): void;
562 | destroy(signal?: string): void;
563 | disconnect(): void;
564 | }
565 |
566 | export var settings: ClusterSettings;
567 | export var isMaster: boolean;
568 | export var isWorker: boolean;
569 | export function setupMaster(settings?: ClusterSettings): void;
570 | export function fork(env?: any): Worker;
571 | export function disconnect(callback?: Function): void;
572 | export var worker: Worker;
573 | export var workers: Worker[];
574 |
575 | // Event emitter
576 | export function addListener(event: string, listener: Function): void;
577 | export function on(event: string, listener: Function): any;
578 | export function once(event: string, listener: Function): void;
579 | export function removeListener(event: string, listener: Function): void;
580 | export function removeAllListeners(event?: string): void;
581 | export function setMaxListeners(n: number): void;
582 | export function listeners(event: string): Function[];
583 | export function emit(event: string, ...args: any[]): boolean;
584 | }
585 |
586 | declare module "zlib" {
587 | import stream = require("stream");
588 | export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; }
589 |
590 | export interface Gzip extends stream.Transform { }
591 | export interface Gunzip extends stream.Transform { }
592 | export interface Deflate extends stream.Transform { }
593 | export interface Inflate extends stream.Transform { }
594 | export interface DeflateRaw extends stream.Transform { }
595 | export interface InflateRaw extends stream.Transform { }
596 | export interface Unzip extends stream.Transform { }
597 |
598 | export function createGzip(options?: ZlibOptions): Gzip;
599 | export function createGunzip(options?: ZlibOptions): Gunzip;
600 | export function createDeflate(options?: ZlibOptions): Deflate;
601 | export function createInflate(options?: ZlibOptions): Inflate;
602 | export function createDeflateRaw(options?: ZlibOptions): DeflateRaw;
603 | export function createInflateRaw(options?: ZlibOptions): InflateRaw;
604 | export function createUnzip(options?: ZlibOptions): Unzip;
605 |
606 | export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
607 | export function deflateSync(buf: Buffer, options?: ZlibOptions): any;
608 | export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
609 | export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any;
610 | export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
611 | export function gzipSync(buf: Buffer, options?: ZlibOptions): any;
612 | export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
613 | export function gunzipSync(buf: Buffer, options?: ZlibOptions): any;
614 | export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
615 | export function inflateSync(buf: Buffer, options?: ZlibOptions): any;
616 | export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
617 | export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any;
618 | export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
619 | export function unzipSync(buf: Buffer, options?: ZlibOptions): any;
620 |
621 | // Constants
622 | export var Z_NO_FLUSH: number;
623 | export var Z_PARTIAL_FLUSH: number;
624 | export var Z_SYNC_FLUSH: number;
625 | export var Z_FULL_FLUSH: number;
626 | export var Z_FINISH: number;
627 | export var Z_BLOCK: number;
628 | export var Z_TREES: number;
629 | export var Z_OK: number;
630 | export var Z_STREAM_END: number;
631 | export var Z_NEED_DICT: number;
632 | export var Z_ERRNO: number;
633 | export var Z_STREAM_ERROR: number;
634 | export var Z_DATA_ERROR: number;
635 | export var Z_MEM_ERROR: number;
636 | export var Z_BUF_ERROR: number;
637 | export var Z_VERSION_ERROR: number;
638 | export var Z_NO_COMPRESSION: number;
639 | export var Z_BEST_SPEED: number;
640 | export var Z_BEST_COMPRESSION: number;
641 | export var Z_DEFAULT_COMPRESSION: number;
642 | export var Z_FILTERED: number;
643 | export var Z_HUFFMAN_ONLY: number;
644 | export var Z_RLE: number;
645 | export var Z_FIXED: number;
646 | export var Z_DEFAULT_STRATEGY: number;
647 | export var Z_BINARY: number;
648 | export var Z_TEXT: number;
649 | export var Z_ASCII: number;
650 | export var Z_UNKNOWN: number;
651 | export var Z_DEFLATED: number;
652 | export var Z_NULL: number;
653 | }
654 |
655 | declare module "os" {
656 | export function tmpdir(): string;
657 | export function hostname(): string;
658 | export function type(): string;
659 | export function platform(): string;
660 | export function arch(): string;
661 | export function release(): string;
662 | export function uptime(): number;
663 | export function loadavg(): number[];
664 | export function totalmem(): number;
665 | export function freemem(): number;
666 | export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[];
667 | export function networkInterfaces(): any;
668 | export var EOL: string;
669 | }
670 |
671 | declare module "https" {
672 | import tls = require("tls");
673 | import events = require("events");
674 | import http = require("http");
675 |
676 | export interface ServerOptions {
677 | pfx?: any;
678 | key?: any;
679 | passphrase?: string;
680 | cert?: any;
681 | ca?: any;
682 | crl?: any;
683 | ciphers?: string;
684 | honorCipherOrder?: boolean;
685 | requestCert?: boolean;
686 | rejectUnauthorized?: boolean;
687 | NPNProtocols?: any;
688 | SNICallback?: (servername: string) => any;
689 | }
690 |
691 | export interface RequestOptions {
692 | host?: string;
693 | hostname?: string;
694 | port?: number;
695 | path?: string;
696 | method?: string;
697 | headers?: any;
698 | auth?: string;
699 | agent?: any;
700 | pfx?: any;
701 | key?: any;
702 | passphrase?: string;
703 | cert?: any;
704 | ca?: any;
705 | ciphers?: string;
706 | rejectUnauthorized?: boolean;
707 | }
708 |
709 | export interface Agent {
710 | maxSockets: number;
711 | sockets: any;
712 | requests: any;
713 | }
714 | export var Agent: {
715 | new (options?: RequestOptions): Agent;
716 | };
717 | export interface Server extends tls.Server { }
718 | export function createServer(options: ServerOptions, requestListener?: Function): Server;
719 | export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;
720 | export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;
721 | export var globalAgent: Agent;
722 | }
723 |
724 | declare module "punycode" {
725 | export function decode(string: string): string;
726 | export function encode(string: string): string;
727 | export function toUnicode(domain: string): string;
728 | export function toASCII(domain: string): string;
729 | export var ucs2: ucs2;
730 | interface ucs2 {
731 | decode(string: string): string;
732 | encode(codePoints: number[]): string;
733 | }
734 | export var version: any;
735 | }
736 |
737 | declare module "repl" {
738 | import stream = require("stream");
739 | import events = require("events");
740 |
741 | export interface ReplOptions {
742 | prompt?: string;
743 | input?: NodeJS.ReadableStream;
744 | output?: NodeJS.WritableStream;
745 | terminal?: boolean;
746 | eval?: Function;
747 | useColors?: boolean;
748 | useGlobal?: boolean;
749 | ignoreUndefined?: boolean;
750 | writer?: Function;
751 | }
752 | export function start(options: ReplOptions): events.EventEmitter;
753 | }
754 |
755 | declare module "readline" {
756 | import events = require("events");
757 | import stream = require("stream");
758 |
759 | export interface ReadLine extends events.EventEmitter {
760 | setPrompt(prompt: string, length: number): void;
761 | prompt(preserveCursor?: boolean): void;
762 | question(query: string, callback: Function): void;
763 | pause(): void;
764 | resume(): void;
765 | close(): void;
766 | write(data: any, key?: any): void;
767 | }
768 | export interface ReadLineOptions {
769 | input: NodeJS.ReadableStream;
770 | output: NodeJS.WritableStream;
771 | completer?: Function;
772 | terminal?: boolean;
773 | }
774 | export function createInterface(options: ReadLineOptions): ReadLine;
775 | }
776 |
777 | declare module "vm" {
778 | export interface Context { }
779 | export interface Script {
780 | runInThisContext(): void;
781 | runInNewContext(sandbox?: Context): void;
782 | }
783 | export function runInThisContext(code: string, filename?: string): void;
784 | export function runInNewContext(code: string, sandbox?: Context, filename?: string): void;
785 | export function runInContext(code: string, context: Context, filename?: string): void;
786 | export function createContext(initSandbox?: Context): Context;
787 | export function createScript(code: string, filename?: string): Script;
788 | }
789 |
790 | declare module "child_process" {
791 | import events = require("events");
792 | import stream = require("stream");
793 |
794 | export interface ChildProcess extends events.EventEmitter {
795 | stdin: stream.Writable;
796 | stdout: stream.Readable;
797 | stderr: stream.Readable;
798 | pid: number;
799 | kill(signal?: string): void;
800 | send(message: any, sendHandle?: any): void;
801 | disconnect(): void;
802 | }
803 |
804 | export function spawn(command: string, args?: string[], options?: {
805 | cwd?: string;
806 | stdio?: any;
807 | custom?: any;
808 | env?: any;
809 | detached?: boolean;
810 | }): ChildProcess;
811 | export function exec(command: string, options: {
812 | cwd?: string;
813 | stdio?: any;
814 | customFds?: any;
815 | env?: any;
816 | encoding?: string;
817 | timeout?: number;
818 | maxBuffer?: number;
819 | killSignal?: string;
820 | }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
821 | export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
822 | export function execFile(file: string,
823 | callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
824 | export function execFile(file: string, args?: string[],
825 | callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
826 | export function execFile(file: string, args?: string[], options?: {
827 | cwd?: string;
828 | stdio?: any;
829 | customFds?: any;
830 | env?: any;
831 | encoding?: string;
832 | timeout?: number;
833 | maxBuffer?: string;
834 | killSignal?: string;
835 | }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
836 | export function fork(modulePath: string, args?: string[], options?: {
837 | cwd?: string;
838 | env?: any;
839 | encoding?: string;
840 | }): ChildProcess;
841 | export function execSync(command: string, options?: {
842 | cwd?: string;
843 | input?: string|Buffer;
844 | stdio?: any;
845 | env?: any;
846 | uid?: number;
847 | gid?: number;
848 | timeout?: number;
849 | maxBuffer?: number;
850 | killSignal?: string;
851 | encoding?: string;
852 | }): ChildProcess;
853 | export function execFileSync(command: string, args?: string[], options?: {
854 | cwd?: string;
855 | input?: string|Buffer;
856 | stdio?: any;
857 | env?: any;
858 | uid?: number;
859 | gid?: number;
860 | timeout?: number;
861 | maxBuffer?: number;
862 | killSignal?: string;
863 | encoding?: string;
864 | }): ChildProcess;
865 | }
866 |
867 | declare module "url" {
868 | export interface Url {
869 | href: string;
870 | protocol: string;
871 | auth: string;
872 | hostname: string;
873 | port: string;
874 | host: string;
875 | pathname: string;
876 | search: string;
877 | query: any; // string | Object
878 | slashes: boolean;
879 | hash?: string;
880 | path?: string;
881 | }
882 |
883 | export interface UrlOptions {
884 | protocol?: string;
885 | auth?: string;
886 | hostname?: string;
887 | port?: string;
888 | host?: string;
889 | pathname?: string;
890 | search?: string;
891 | query?: any;
892 | hash?: string;
893 | path?: string;
894 | }
895 |
896 | export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url;
897 | export function format(url: UrlOptions): string;
898 | export function resolve(from: string, to: string): string;
899 | }
900 |
901 | declare module "dns" {
902 | export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string;
903 | export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string;
904 | export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[];
905 | export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
906 | export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
907 | export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
908 | export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
909 | export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
910 | export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
911 | export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
912 | export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
913 | export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[];
914 | }
915 |
916 | declare module "net" {
917 | import stream = require("stream");
918 |
919 | export interface Socket extends stream.Duplex {
920 | // Extended base methods
921 | write(buffer: Buffer): boolean;
922 | write(buffer: Buffer, cb?: Function): boolean;
923 | write(str: string, cb?: Function): boolean;
924 | write(str: string, encoding?: string, cb?: Function): boolean;
925 | write(str: string, encoding?: string, fd?: string): boolean;
926 |
927 | connect(port: number, host?: string, connectionListener?: Function): void;
928 | connect(path: string, connectionListener?: Function): void;
929 | bufferSize: number;
930 | setEncoding(encoding?: string): void;
931 | write(data: any, encoding?: string, callback?: Function): void;
932 | destroy(): void;
933 | pause(): void;
934 | resume(): void;
935 | setTimeout(timeout: number, callback?: Function): void;
936 | setNoDelay(noDelay?: boolean): void;
937 | setKeepAlive(enable?: boolean, initialDelay?: number): void;
938 | address(): { port: number; family: string; address: string; };
939 | unref(): void;
940 | ref(): void;
941 |
942 | remoteAddress: string;
943 | remoteFamily: string;
944 | remotePort: number;
945 | localAddress: string;
946 | localPort: number;
947 | bytesRead: number;
948 | bytesWritten: number;
949 |
950 | // Extended base methods
951 | end(): void;
952 | end(buffer: Buffer, cb?: Function): void;
953 | end(str: string, cb?: Function): void;
954 | end(str: string, encoding?: string, cb?: Function): void;
955 | end(data?: any, encoding?: string): void;
956 | }
957 |
958 | export var Socket: {
959 | new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket;
960 | };
961 |
962 | export interface Server extends Socket {
963 | listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server;
964 | listen(path: string, listeningListener?: Function): Server;
965 | listen(handle: any, listeningListener?: Function): Server;
966 | close(callback?: Function): Server;
967 | address(): { port: number; family: string; address: string; };
968 | maxConnections: number;
969 | connections: number;
970 | }
971 | export function createServer(connectionListener?: (socket: Socket) =>void ): Server;
972 | export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server;
973 | export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;
974 | export function connect(port: number, host?: string, connectionListener?: Function): Socket;
975 | export function connect(path: string, connectionListener?: Function): Socket;
976 | export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;
977 | export function createConnection(port: number, host?: string, connectionListener?: Function): Socket;
978 | export function createConnection(path: string, connectionListener?: Function): Socket;
979 | export function isIP(input: string): number;
980 | export function isIPv4(input: string): boolean;
981 | export function isIPv6(input: string): boolean;
982 | }
983 |
984 | declare module "dgram" {
985 | import events = require("events");
986 |
987 | interface RemoteInfo {
988 | address: string;
989 | port: number;
990 | size: number;
991 | }
992 |
993 | interface AddressInfo {
994 | address: string;
995 | family: string;
996 | port: number;
997 | }
998 |
999 | export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
1000 |
1001 | interface Socket extends events.EventEmitter {
1002 | send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void;
1003 | bind(port: number, address?: string, callback?: () => void): void;
1004 | close(): void;
1005 | address(): AddressInfo;
1006 | setBroadcast(flag: boolean): void;
1007 | setMulticastTTL(ttl: number): void;
1008 | setMulticastLoopback(flag: boolean): void;
1009 | addMembership(multicastAddress: string, multicastInterface?: string): void;
1010 | dropMembership(multicastAddress: string, multicastInterface?: string): void;
1011 | }
1012 | }
1013 |
1014 | declare module "fs" {
1015 | import stream = require("stream");
1016 | import events = require("events");
1017 |
1018 | interface Stats {
1019 | isFile(): boolean;
1020 | isDirectory(): boolean;
1021 | isBlockDevice(): boolean;
1022 | isCharacterDevice(): boolean;
1023 | isSymbolicLink(): boolean;
1024 | isFIFO(): boolean;
1025 | isSocket(): boolean;
1026 | dev: number;
1027 | ino: number;
1028 | mode: number;
1029 | nlink: number;
1030 | uid: number;
1031 | gid: number;
1032 | rdev: number;
1033 | size: number;
1034 | blksize: number;
1035 | blocks: number;
1036 | atime: Date;
1037 | mtime: Date;
1038 | ctime: Date;
1039 | }
1040 |
1041 | interface FSWatcher extends events.EventEmitter {
1042 | close(): void;
1043 | }
1044 |
1045 | export interface ReadStream extends stream.Readable {
1046 | close(): void;
1047 | }
1048 | export interface WriteStream extends stream.Writable {
1049 | close(): void;
1050 | }
1051 |
1052 | /**
1053 | * Asynchronous rename.
1054 | * @param oldPath
1055 | * @param newPath
1056 | * @param callback No arguments other than a possible exception are given to the completion callback.
1057 | */
1058 | export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1059 | /**
1060 | * Synchronous rename
1061 | * @param oldPath
1062 | * @param newPath
1063 | */
1064 | export function renameSync(oldPath: string, newPath: string): void;
1065 | export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1066 | export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1067 | export function truncateSync(path: string, len?: number): void;
1068 | export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1069 | export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1070 | export function ftruncateSync(fd: number, len?: number): void;
1071 | export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1072 | export function chownSync(path: string, uid: number, gid: number): void;
1073 | export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1074 | export function fchownSync(fd: number, uid: number, gid: number): void;
1075 | export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1076 | export function lchownSync(path: string, uid: number, gid: number): void;
1077 | export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1078 | export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1079 | export function chmodSync(path: string, mode: number): void;
1080 | export function chmodSync(path: string, mode: string): void;
1081 | export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1082 | export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1083 | export function fchmodSync(fd: number, mode: number): void;
1084 | export function fchmodSync(fd: number, mode: string): void;
1085 | export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1086 | export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1087 | export function lchmodSync(path: string, mode: number): void;
1088 | export function lchmodSync(path: string, mode: string): void;
1089 | export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
1090 | export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
1091 | export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
1092 | export function statSync(path: string): Stats;
1093 | export function lstatSync(path: string): Stats;
1094 | export function fstatSync(fd: number): Stats;
1095 | export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1096 | export function linkSync(srcpath: string, dstpath: string): void;
1097 | export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1098 | export function symlinkSync(srcpath: string, dstpath: string, type?: string): void;
1099 | export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void;
1100 | export function readlinkSync(path: string): string;
1101 | export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void;
1102 | export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void;
1103 | export function realpathSync(path: string, cache?: { [path: string]: string }): string;
1104 | /*
1105 | * Asynchronous unlink - deletes the file specified in {path}
1106 | *
1107 | * @param path
1108 | * @param callback No arguments other than a possible exception are given to the completion callback.
1109 | */
1110 | export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1111 | /*
1112 | * Synchronous unlink - deletes the file specified in {path}
1113 | *
1114 | * @param path
1115 | */
1116 | export function unlinkSync(path: string): void;
1117 | /*
1118 | * Asynchronous rmdir - removes the directory specified in {path}
1119 | *
1120 | * @param path
1121 | * @param callback No arguments other than a possible exception are given to the completion callback.
1122 | */
1123 | export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1124 | /*
1125 | * Synchronous rmdir - removes the directory specified in {path}
1126 | *
1127 | * @param path
1128 | */
1129 | export function rmdirSync(path: string): void;
1130 | /*
1131 | * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
1132 | *
1133 | * @param path
1134 | * @param callback No arguments other than a possible exception are given to the completion callback.
1135 | */
1136 | export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1137 | /*
1138 | * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
1139 | *
1140 | * @param path
1141 | * @param mode
1142 | * @param callback No arguments other than a possible exception are given to the completion callback.
1143 | */
1144 | export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1145 | /*
1146 | * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
1147 | *
1148 | * @param path
1149 | * @param mode
1150 | * @param callback No arguments other than a possible exception are given to the completion callback.
1151 | */
1152 | export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
1153 | /*
1154 | * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
1155 | *
1156 | * @param path
1157 | * @param mode
1158 | * @param callback No arguments other than a possible exception are given to the completion callback.
1159 | */
1160 | export function mkdirSync(path: string, mode?: number): void;
1161 | /*
1162 | * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
1163 | *
1164 | * @param path
1165 | * @param mode
1166 | * @param callback No arguments other than a possible exception are given to the completion callback.
1167 | */
1168 | export function mkdirSync(path: string, mode?: string): void;
1169 | export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void;
1170 | export function readdirSync(path: string): string[];
1171 | export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1172 | export function closeSync(fd: number): void;
1173 | export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
1174 | export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
1175 | export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
1176 | export function openSync(path: string, flags: string, mode?: number): number;
1177 | export function openSync(path: string, flags: string, mode?: string): number;
1178 | export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1179 | export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;
1180 | export function utimesSync(path: string, atime: number, mtime: number): void;
1181 | export function utimesSync(path: string, atime: Date, mtime: Date): void;
1182 | export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1183 | export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;
1184 | export function futimesSync(fd: number, atime: number, mtime: number): void;
1185 | export function futimesSync(fd: number, atime: Date, mtime: Date): void;
1186 | export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
1187 | export function fsyncSync(fd: number): void;
1188 | export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void;
1189 | export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;
1190 | export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void;
1191 | export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;
1192 | /*
1193 | * Asynchronous readFile - Asynchronously reads the entire contents of a file.
1194 | *
1195 | * @param fileName
1196 | * @param encoding
1197 | * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
1198 | */
1199 | export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void;
1200 | /*
1201 | * Asynchronous readFile - Asynchronously reads the entire contents of a file.
1202 | *
1203 | * @param fileName
1204 | * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.
1205 | * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
1206 | */
1207 | export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void;
1208 | /*
1209 | * Asynchronous readFile - Asynchronously reads the entire contents of a file.
1210 | *
1211 | * @param fileName
1212 | * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.
1213 | * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
1214 | */
1215 | export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;
1216 | /*
1217 | * Asynchronous readFile - Asynchronously reads the entire contents of a file.
1218 | *
1219 | * @param fileName
1220 | * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
1221 | */
1222 | export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;
1223 | /*
1224 | * Synchronous readFile - Synchronously reads the entire contents of a file.
1225 | *
1226 | * @param fileName
1227 | * @param encoding
1228 | */
1229 | export function readFileSync(filename: string, encoding: string): string;
1230 | /*
1231 | * Synchronous readFile - Synchronously reads the entire contents of a file.
1232 | *
1233 | * @param fileName
1234 | * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.
1235 | */
1236 | export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string;
1237 | /*
1238 | * Synchronous readFile - Synchronously reads the entire contents of a file.
1239 | *
1240 | * @param fileName
1241 | * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.
1242 | */
1243 | export function readFileSync(filename: string, options?: { flag?: string; }): Buffer;
1244 | export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;
1245 | export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
1246 | export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
1247 | export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;
1248 | export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;
1249 | export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
1250 | export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
1251 | export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;
1252 | export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;
1253 | export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;
1254 | export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void;
1255 | export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void;
1256 | export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void;
1257 | export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher;
1258 | export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher;
1259 | export function exists(path: string, callback?: (exists: boolean) => void): void;
1260 | export function existsSync(path: string): boolean;
1261 | export function createReadStream(path: string, options?: {
1262 | flags?: string;
1263 | encoding?: string;
1264 | fd?: string;
1265 | mode?: number;
1266 | bufferSize?: number;
1267 | }): ReadStream;
1268 | export function createReadStream(path: string, options?: {
1269 | flags?: string;
1270 | encoding?: string;
1271 | fd?: string;
1272 | mode?: string;
1273 | bufferSize?: number;
1274 | }): ReadStream;
1275 | export function createWriteStream(path: string, options?: {
1276 | flags?: string;
1277 | encoding?: string;
1278 | string?: string;
1279 | }): WriteStream;
1280 | }
1281 |
1282 | declare module "path" {
1283 |
1284 | /**
1285 | * A parsed path object generated by path.parse() or consumed by path.format().
1286 | */
1287 | export interface ParsedPath {
1288 | /**
1289 | * The root of the path such as '/' or 'c:\'
1290 | */
1291 | root: string;
1292 | /**
1293 | * The full directory path such as '/home/user/dir' or 'c:\path\dir'
1294 | */
1295 | dir: string;
1296 | /**
1297 | * The file name including extension (if any) such as 'index.html'
1298 | */
1299 | base: string;
1300 | /**
1301 | * The file extension (if any) such as '.html'
1302 | */
1303 | ext: string;
1304 | /**
1305 | * The file name without extension (if any) such as 'index'
1306 | */
1307 | name: string;
1308 | }
1309 |
1310 | /**
1311 | * Normalize a string path, reducing '..' and '.' parts.
1312 | * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
1313 | *
1314 | * @param p string path to normalize.
1315 | */
1316 | export function normalize(p: string): string;
1317 | /**
1318 | * Join all arguments together and normalize the resulting path.
1319 | * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
1320 | *
1321 | * @param paths string paths to join.
1322 | */
1323 | export function join(...paths: any[]): string;
1324 | /**
1325 | * Join all arguments together and normalize the resulting path.
1326 | * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
1327 | *
1328 | * @param paths string paths to join.
1329 | */
1330 | export function join(...paths: string[]): string;
1331 | /**
1332 | * The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
1333 | *
1334 | * Starting from leftmost {from} paramter, resolves {to} to an absolute path.
1335 | *
1336 | * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.
1337 | *
1338 | * @param pathSegments string paths to join. Non-string arguments are ignored.
1339 | */
1340 | export function resolve(...pathSegments: any[]): string;
1341 | /**
1342 | * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
1343 | *
1344 | * @param path path to test.
1345 | */
1346 | export function isAbsolute(path: string): boolean;
1347 | /**
1348 | * Solve the relative path from {from} to {to}.
1349 | * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
1350 | *
1351 | * @param from
1352 | * @param to
1353 | */
1354 | export function relative(from: string, to: string): string;
1355 | /**
1356 | * Return the directory name of a path. Similar to the Unix dirname command.
1357 | *
1358 | * @param p the path to evaluate.
1359 | */
1360 | export function dirname(p: string): string;
1361 | /**
1362 | * Return the last portion of a path. Similar to the Unix basename command.
1363 | * Often used to extract the file name from a fully qualified path.
1364 | *
1365 | * @param p the path to evaluate.
1366 | * @param ext optionally, an extension to remove from the result.
1367 | */
1368 | export function basename(p: string, ext?: string): string;
1369 | /**
1370 | * Return the extension of the path, from the last '.' to end of string in the last portion of the path.
1371 | * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string
1372 | *
1373 | * @param p the path to evaluate.
1374 | */
1375 | export function extname(p: string): string;
1376 | /**
1377 | * The platform-specific file separator. '\\' or '/'.
1378 | */
1379 | export var sep: string;
1380 | /**
1381 | * The platform-specific file delimiter. ';' or ':'.
1382 | */
1383 | export var delimiter: string;
1384 | /**
1385 | * Returns an object from a path string - the opposite of format().
1386 | *
1387 | * @param pathString path to evaluate.
1388 | */
1389 | export function parse(pathString: string): ParsedPath;
1390 | /**
1391 | * Returns a path string from an object - the opposite of parse().
1392 | *
1393 | * @param pathString path to evaluate.
1394 | */
1395 | export function format(pathObject: ParsedPath): string;
1396 |
1397 | export module posix {
1398 | export function normalize(p: string): string;
1399 | export function join(...paths: any[]): string;
1400 | export function resolve(...pathSegments: any[]): string;
1401 | export function isAbsolute(p: string): boolean;
1402 | export function relative(from: string, to: string): string;
1403 | export function dirname(p: string): string;
1404 | export function basename(p: string, ext?: string): string;
1405 | export function extname(p: string): string;
1406 | export var sep: string;
1407 | export var delimiter: string;
1408 | export function parse(p: string): ParsedPath;
1409 | export function format(pP: ParsedPath): string;
1410 | }
1411 |
1412 | export module win32 {
1413 | export function normalize(p: string): string;
1414 | export function join(...paths: any[]): string;
1415 | export function resolve(...pathSegments: any[]): string;
1416 | export function isAbsolute(p: string): boolean;
1417 | export function relative(from: string, to: string): string;
1418 | export function dirname(p: string): string;
1419 | export function basename(p: string, ext?: string): string;
1420 | export function extname(p: string): string;
1421 | export var sep: string;
1422 | export var delimiter: string;
1423 | export function parse(p: string): ParsedPath;
1424 | export function format(pP: ParsedPath): string;
1425 | }
1426 | }
1427 |
1428 | declare module "string_decoder" {
1429 | export interface NodeStringDecoder {
1430 | write(buffer: Buffer): string;
1431 | detectIncompleteChar(buffer: Buffer): number;
1432 | }
1433 | export var StringDecoder: {
1434 | new (encoding: string): NodeStringDecoder;
1435 | };
1436 | }
1437 |
1438 | declare module "tls" {
1439 | import crypto = require("crypto");
1440 | import net = require("net");
1441 | import stream = require("stream");
1442 |
1443 | var CLIENT_RENEG_LIMIT: number;
1444 | var CLIENT_RENEG_WINDOW: number;
1445 |
1446 | export interface TlsOptions {
1447 | pfx?: any; //string or buffer
1448 | key?: any; //string or buffer
1449 | passphrase?: string;
1450 | cert?: any;
1451 | ca?: any; //string or buffer
1452 | crl?: any; //string or string array
1453 | ciphers?: string;
1454 | honorCipherOrder?: any;
1455 | requestCert?: boolean;
1456 | rejectUnauthorized?: boolean;
1457 | NPNProtocols?: any; //array or Buffer;
1458 | SNICallback?: (servername: string) => any;
1459 | }
1460 |
1461 | export interface ConnectionOptions {
1462 | host?: string;
1463 | port?: number;
1464 | socket?: net.Socket;
1465 | pfx?: any; //string | Buffer
1466 | key?: any; //string | Buffer
1467 | passphrase?: string;
1468 | cert?: any; //string | Buffer
1469 | ca?: any; //Array of string | Buffer
1470 | rejectUnauthorized?: boolean;
1471 | NPNProtocols?: any; //Array of string | Buffer
1472 | servername?: string;
1473 | }
1474 |
1475 | export interface Server extends net.Server {
1476 | // Extended base methods
1477 | listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server;
1478 | listen(path: string, listeningListener?: Function): Server;
1479 | listen(handle: any, listeningListener?: Function): Server;
1480 |
1481 | listen(port: number, host?: string, callback?: Function): Server;
1482 | close(): Server;
1483 | address(): { port: number; family: string; address: string; };
1484 | addContext(hostName: string, credentials: {
1485 | key: string;
1486 | cert: string;
1487 | ca: string;
1488 | }): void;
1489 | maxConnections: number;
1490 | connections: number;
1491 | }
1492 |
1493 | export interface ClearTextStream extends stream.Duplex {
1494 | authorized: boolean;
1495 | authorizationError: Error;
1496 | getPeerCertificate(): any;
1497 | getCipher: {
1498 | name: string;
1499 | version: string;
1500 | };
1501 | address: {
1502 | port: number;
1503 | family: string;
1504 | address: string;
1505 | };
1506 | remoteAddress: string;
1507 | remotePort: number;
1508 | }
1509 |
1510 | export interface SecurePair {
1511 | encrypted: any;
1512 | cleartext: any;
1513 | }
1514 |
1515 | export interface SecureContextOptions {
1516 | pfx?: any; //string | buffer
1517 | key?: any; //string | buffer
1518 | passphrase?: string;
1519 | cert?: any; // string | buffer
1520 | ca?: any; // string | buffer
1521 | crl?: any; // string | string[]
1522 | ciphers?: string;
1523 | honorCipherOrder?: boolean;
1524 | }
1525 |
1526 | export interface SecureContext {
1527 | context: any;
1528 | }
1529 |
1530 | export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server;
1531 | export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream;
1532 | export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;
1533 | export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;
1534 | export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair;
1535 | export function createSecureContext(details: SecureContextOptions): SecureContext;
1536 | }
1537 |
1538 | declare module "crypto" {
1539 | export interface CredentialDetails {
1540 | pfx: string;
1541 | key: string;
1542 | passphrase: string;
1543 | cert: string;
1544 | ca: any; //string | string array
1545 | crl: any; //string | string array
1546 | ciphers: string;
1547 | }
1548 | export interface Credentials { context?: any; }
1549 | export function createCredentials(details: CredentialDetails): Credentials;
1550 | export function createHash(algorithm: string): Hash;
1551 | export function createHmac(algorithm: string, key: string): Hmac;
1552 | export function createHmac(algorithm: string, key: Buffer): Hmac;
1553 | interface Hash {
1554 | update(data: any, input_encoding?: string): Hash;
1555 | digest(encoding: 'buffer'): Buffer;
1556 | digest(encoding: string): any;
1557 | digest(): Buffer;
1558 | }
1559 | interface Hmac {
1560 | update(data: any, input_encoding?: string): Hmac;
1561 | digest(encoding: 'buffer'): Buffer;
1562 | digest(encoding: string): any;
1563 | digest(): Buffer;
1564 | }
1565 | export function createCipher(algorithm: string, password: any): Cipher;
1566 | export function createCipheriv(algorithm: string, key: any, iv: any): Cipher;
1567 | interface Cipher {
1568 | update(data: Buffer): Buffer;
1569 | update(data: string, input_encoding?: string, output_encoding?: string): string;
1570 | final(): Buffer;
1571 | final(output_encoding: string): string;
1572 | setAutoPadding(auto_padding: boolean): void;
1573 | }
1574 | export function createDecipher(algorithm: string, password: any): Decipher;
1575 | export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher;
1576 | interface Decipher {
1577 | update(data: Buffer): Buffer;
1578 | update(data: string, input_encoding?: string, output_encoding?: string): string;
1579 | final(): Buffer;
1580 | final(output_encoding: string): string;
1581 | setAutoPadding(auto_padding: boolean): void;
1582 | }
1583 | export function createSign(algorithm: string): Signer;
1584 | interface Signer {
1585 | update(data: any): void;
1586 | sign(private_key: string, output_format: string): string;
1587 | }
1588 | export function createVerify(algorith: string): Verify;
1589 | interface Verify {
1590 | update(data: any): void;
1591 | verify(object: string, signature: string, signature_format?: string): boolean;
1592 | }
1593 | export function createDiffieHellman(prime_length: number): DiffieHellman;
1594 | export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman;
1595 | interface DiffieHellman {
1596 | generateKeys(encoding?: string): string;
1597 | computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string;
1598 | getPrime(encoding?: string): string;
1599 | getGenerator(encoding: string): string;
1600 | getPublicKey(encoding?: string): string;
1601 | getPrivateKey(encoding?: string): string;
1602 | setPublicKey(public_key: string, encoding?: string): void;
1603 | setPrivateKey(public_key: string, encoding?: string): void;
1604 | }
1605 | export function getDiffieHellman(group_name: string): DiffieHellman;
1606 | export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void;
1607 | export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer;
1608 | export function randomBytes(size: number): Buffer;
1609 | export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;
1610 | export function pseudoRandomBytes(size: number): Buffer;
1611 | export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;
1612 | }
1613 |
1614 | declare module "stream" {
1615 | import events = require("events");
1616 |
1617 | export interface Stream extends events.EventEmitter {
1618 | pipe(destination: T, options?: { end?: boolean; }): T;
1619 | }
1620 |
1621 | export interface ReadableOptions {
1622 | highWaterMark?: number;
1623 | encoding?: string;
1624 | objectMode?: boolean;
1625 | }
1626 |
1627 | export class Readable extends events.EventEmitter implements NodeJS.ReadableStream {
1628 | readable: boolean;
1629 | constructor(opts?: ReadableOptions);
1630 | _read(size: number): void;
1631 | read(size?: number): string|Buffer;
1632 | setEncoding(encoding: string): void;
1633 | pause(): void;
1634 | resume(): void;
1635 | pipe(destination: T, options?: { end?: boolean; }): T;
1636 | unpipe(destination?: T): void;
1637 | unshift(chunk: string): void;
1638 | unshift(chunk: Buffer): void;
1639 | wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
1640 | push(chunk: any, encoding?: string): boolean;
1641 | }
1642 |
1643 | export interface WritableOptions {
1644 | highWaterMark?: number;
1645 | decodeStrings?: boolean;
1646 | }
1647 |
1648 | export class Writable extends events.EventEmitter implements NodeJS.WritableStream {
1649 | writable: boolean;
1650 | constructor(opts?: WritableOptions);
1651 | _write(data: Buffer, encoding: string, callback: Function): void;
1652 | _write(data: string, encoding: string, callback: Function): void;
1653 | write(buffer: Buffer, cb?: Function): boolean;
1654 | write(str: string, cb?: Function): boolean;
1655 | write(str: string, encoding?: string, cb?: Function): boolean;
1656 | end(): void;
1657 | end(buffer: Buffer, cb?: Function): void;
1658 | end(str: string, cb?: Function): void;
1659 | end(str: string, encoding?: string, cb?: Function): void;
1660 | }
1661 |
1662 | export interface DuplexOptions extends ReadableOptions, WritableOptions {
1663 | allowHalfOpen?: boolean;
1664 | }
1665 |
1666 | // Note: Duplex extends both Readable and Writable.
1667 | export class Duplex extends Readable implements NodeJS.ReadWriteStream {
1668 | writable: boolean;
1669 | constructor(opts?: DuplexOptions);
1670 | _write(data: Buffer, encoding: string, callback: Function): void;
1671 | _write(data: string, encoding: string, callback: Function): void;
1672 | write(buffer: Buffer, cb?: Function): boolean;
1673 | write(str: string, cb?: Function): boolean;
1674 | write(str: string, encoding?: string, cb?: Function): boolean;
1675 | end(): void;
1676 | end(buffer: Buffer, cb?: Function): void;
1677 | end(str: string, cb?: Function): void;
1678 | end(str: string, encoding?: string, cb?: Function): void;
1679 | }
1680 |
1681 | export interface TransformOptions extends ReadableOptions, WritableOptions {}
1682 |
1683 | // Note: Transform lacks the _read and _write methods of Readable/Writable.
1684 | export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream {
1685 | readable: boolean;
1686 | writable: boolean;
1687 | constructor(opts?: TransformOptions);
1688 | _transform(chunk: Buffer, encoding: string, callback: Function): void;
1689 | _transform(chunk: string, encoding: string, callback: Function): void;
1690 | _flush(callback: Function): void;
1691 | read(size?: number): any;
1692 | setEncoding(encoding: string): void;
1693 | pause(): void;
1694 | resume(): void;
1695 | pipe(destination: T, options?: { end?: boolean; }): T;
1696 | unpipe(destination?: T): void;
1697 | unshift(chunk: string): void;
1698 | unshift(chunk: Buffer): void;
1699 | wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
1700 | push(chunk: any, encoding?: string): boolean;
1701 | write(buffer: Buffer, cb?: Function): boolean;
1702 | write(str: string, cb?: Function): boolean;
1703 | write(str: string, encoding?: string, cb?: Function): boolean;
1704 | end(): void;
1705 | end(buffer: Buffer, cb?: Function): void;
1706 | end(str: string, cb?: Function): void;
1707 | end(str: string, encoding?: string, cb?: Function): void;
1708 | }
1709 |
1710 | export class PassThrough extends Transform {}
1711 | }
1712 |
1713 | declare module "util" {
1714 | export interface InspectOptions {
1715 | showHidden?: boolean;
1716 | depth?: number;
1717 | colors?: boolean;
1718 | customInspect?: boolean;
1719 | }
1720 |
1721 | export function format(format: any, ...param: any[]): string;
1722 | export function debug(string: string): void;
1723 | export function error(...param: any[]): void;
1724 | export function puts(...param: any[]): void;
1725 | export function print(...param: any[]): void;
1726 | export function log(string: string): void;
1727 | export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string;
1728 | export function inspect(object: any, options: InspectOptions): string;
1729 | export function isArray(object: any): boolean;
1730 | export function isRegExp(object: any): boolean;
1731 | export function isDate(object: any): boolean;
1732 | export function isError(object: any): boolean;
1733 | export function inherits(constructor: any, superConstructor: any): void;
1734 | }
1735 |
1736 | declare module "assert" {
1737 | function internal (value: any, message?: string): void;
1738 | module internal {
1739 | export class AssertionError implements Error {
1740 | name: string;
1741 | message: string;
1742 | actual: any;
1743 | expected: any;
1744 | operator: string;
1745 | generatedMessage: boolean;
1746 |
1747 | constructor(options?: {message?: string; actual?: any; expected?: any;
1748 | operator?: string; stackStartFunction?: Function});
1749 | }
1750 |
1751 | export function fail(actual?: any, expected?: any, message?: string, operator?: string): void;
1752 | export function ok(value: any, message?: string): void;
1753 | export function equal(actual: any, expected: any, message?: string): void;
1754 | export function notEqual(actual: any, expected: any, message?: string): void;
1755 | export function deepEqual(actual: any, expected: any, message?: string): void;
1756 | export function notDeepEqual(acutal: any, expected: any, message?: string): void;
1757 | export function strictEqual(actual: any, expected: any, message?: string): void;
1758 | export function notStrictEqual(actual: any, expected: any, message?: string): void;
1759 | export var throws: {
1760 | (block: Function, message?: string): void;
1761 | (block: Function, error: Function, message?: string): void;
1762 | (block: Function, error: RegExp, message?: string): void;
1763 | (block: Function, error: (err: any) => boolean, message?: string): void;
1764 | };
1765 |
1766 | export var doesNotThrow: {
1767 | (block: Function, message?: string): void;
1768 | (block: Function, error: Function, message?: string): void;
1769 | (block: Function, error: RegExp, message?: string): void;
1770 | (block: Function, error: (err: any) => boolean, message?: string): void;
1771 | };
1772 |
1773 | export function ifError(value: any): void;
1774 | }
1775 |
1776 | export = internal;
1777 | }
1778 |
1779 | declare module "tty" {
1780 | import net = require("net");
1781 |
1782 | export function isatty(fd: number): boolean;
1783 | export interface ReadStream extends net.Socket {
1784 | isRaw: boolean;
1785 | setRawMode(mode: boolean): void;
1786 | }
1787 | export interface WriteStream extends net.Socket {
1788 | columns: number;
1789 | rows: number;
1790 | }
1791 | }
1792 |
1793 | declare module "domain" {
1794 | import events = require("events");
1795 |
1796 | export class Domain extends events.EventEmitter {
1797 | run(fn: Function): void;
1798 | add(emitter: events.EventEmitter): void;
1799 | remove(emitter: events.EventEmitter): void;
1800 | bind(cb: (err: Error, data: any) => any): any;
1801 | intercept(cb: (data: any) => any): any;
1802 | dispose(): void;
1803 |
1804 | addListener(event: string, listener: Function): Domain;
1805 | on(event: string, listener: Function): Domain;
1806 | once(event: string, listener: Function): Domain;
1807 | removeListener(event: string, listener: Function): Domain;
1808 | removeAllListeners(event?: string): Domain;
1809 | }
1810 |
1811 | export function create(): Domain;
1812 | }
1813 |
--------------------------------------------------------------------------------
/typings/redis/redis.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for redis
2 | // Project: https://github.com/mranney/node_redis
3 | // Definitions by: Carlos Ballesteros Velasco , Peter Harris
4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped
5 |
6 | // Imported from: https://github.com/soywiz/typescript-node-definitions/redis.d.ts
7 |
8 | ///
9 |
10 | declare module "redis" {
11 | export function createClient(port_arg: number, host_arg?: string, options?: ClientOpts): RedisClient;
12 | export function createClient(unix_socket: string, options?: ClientOpts): RedisClient;
13 | export function createClient(options?: ClientOpts): RedisClient;
14 | export function print(err: Error, reply: any): void;
15 | export var debug_mode: boolean;
16 |
17 | interface MessageHandler {
18 | (channel: string, message: any): void;
19 | }
20 |
21 | interface CommandT { //This is a placeholder to be used eventually, to not have to define each command twice, or four times if all caps versions are to be implemented.
22 | (args: any[], callback?: ResCallbackT): void;
23 | (...args: any[]): void;
24 | }
25 |
26 | interface ResCallbackT {
27 | (err: Error, res: R): void;
28 | }
29 |
30 | interface ServerInfo {
31 | redis_version: string;
32 | versions: number[];
33 | }
34 |
35 | interface ClientOpts {
36 | parser?: string;
37 | return_buffers?: boolean;
38 | detect_buffers?: boolean;
39 | socket_nodelay?: boolean;
40 | no_ready_check?: boolean;
41 | enable_offline_queue?: boolean;
42 | retry_max_delay?: number;
43 | connect_timeout?: number;
44 | max_attempts?: number;
45 | auth_pass?: string;
46 | }
47 |
48 | interface RedisClient extends NodeJS.EventEmitter {
49 | // event: connect
50 | // event: error
51 | // event: message
52 | // event: pmessage
53 | // event: subscribe
54 | // event: psubscribe
55 | // event: unsubscribe
56 | // event: punsubscribe
57 |
58 | connected: boolean;
59 | retry_delay: number;
60 | retry_backoff: number;
61 | command_queue: any[];
62 | offline_queue: any[];
63 | server_info: ServerInfo;
64 |
65 | end(): void;
66 |
67 | // Connection (http://redis.io/commands#connection)
68 | auth(password: string, callback?: ResCallbackT): void;
69 | ping(callback?: ResCallbackT): void;
70 |
71 | // Strings (http://redis.io/commands#strings)
72 | append(key: string, value: string, callback?: ResCallbackT): void;
73 | bitcount(key: string, callback?: ResCallbackT): void;
74 | bitcount(key: string, start: number, end: number, callback?: ResCallbackT): void;
75 | set(key: string, value: string, callback?: ResCallbackT): void;
76 | get(key: string, callback?: ResCallbackT): void;
77 | exists(key: string, value: string, callback?: ResCallbackT): void;
78 |
79 | publish(channel: string, value: any): void;
80 | subscribe(channel: string): void;
81 |
82 | /*
83 | commands = set_union([
84 | "get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr",
85 | "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex",
86 | "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore",
87 | "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore",
88 | "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx",
89 | "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx",
90 | "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave",
91 | "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl",
92 | "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster",
93 | "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require("./lib/commands"));
94 | */
95 |
96 | get(args: any[], callback?: ResCallbackT): void;
97 | get(...args: any[]): void;
98 | set(args: any[], callback?: ResCallbackT): void;
99 | set(...args: any[]): void;
100 | setnx(args: any[], callback?: ResCallbackT): void;
101 | setnx(...args: any[]): void;
102 | setex(args: any[], callback?: ResCallbackT): void;
103 | setex(...args: any[]): void;
104 | append(args: any[], callback?: ResCallbackT): void;
105 | append(...args: any[]): void;
106 | strlen(args: any[], callback?: ResCallbackT): void;
107 | strlen(...args: any[]): void;
108 | del(args: any[], callback?: ResCallbackT): void;
109 | del(...args: any[]): void;
110 | exists(args: any[], callback?: ResCallbackT): void;
111 | exists(...args: any[]): void;
112 | setbit(args: any[], callback?: ResCallbackT): void;
113 | setbit(...args: any[]): void;
114 | getbit(args: any[], callback?: ResCallbackT): void;
115 | getbit(...args: any[]): void;
116 | setrange(args: any[], callback?: ResCallbackT): void;
117 | setrange(...args: any[]): void;
118 | getrange(args: any[], callback?: ResCallbackT): void;
119 | getrange(...args: any[]): void;
120 | substr(args: any[], callback?: ResCallbackT): void;
121 | substr(...args: any[]): void;
122 | incr(args: any[], callback?: ResCallbackT): void;
123 | incr(...args: any[]): void;
124 | decr(args: any[], callback?: ResCallbackT): void;
125 | decr(...args: any[]): void;
126 | mget(args: any[], callback?: ResCallbackT): void;
127 | mget(...args: any[]): void;
128 | rpush(...args: any[]): void;
129 | lpush(args: any[], callback?: ResCallbackT): void;
130 | lpush(...args: any[]): void;
131 | rpushx(args: any[], callback?: ResCallbackT): void;
132 | rpushx(...args: any[]): void;
133 | lpushx(args: any[], callback?: ResCallbackT): void;
134 | lpushx(...args: any[]): void;
135 | linsert(args: any[], callback?: ResCallbackT): void;
136 | linsert(...args: any[]): void;
137 | rpop(args: any[], callback?: ResCallbackT): void;
138 | rpop(...args: any[]): void;
139 | lpop(args: any[], callback?: ResCallbackT): void;
140 | lpop(...args: any[]): void;
141 | brpop(args: any[], callback?: ResCallbackT): void;
142 | brpop(...args: any[]): void;
143 | brpoplpush(args: any[], callback?: ResCallbackT): void;
144 | brpoplpush(...args: any[]): void;
145 | blpop(args: any[], callback?: ResCallbackT): void;
146 | blpop(...args: any[]): void;
147 | llen(args: any[], callback?: ResCallbackT): void;
148 | llen(...args: any[]): void;
149 | lindex(args: any[], callback?: ResCallbackT): void;
150 | lindex(...args: any[]): void;
151 | lset(args: any[], callback?: ResCallbackT): void;
152 | lset(...args: any[]): void;
153 | lrange(args: any[], callback?: ResCallbackT): void;
154 | lrange(...args: any[]): void;
155 | ltrim(args: any[], callback?: ResCallbackT): void;
156 | ltrim(...args: any[]): void;
157 | lrem(args: any[], callback?: ResCallbackT): void;
158 | lrem(...args: any[]): void;
159 | rpoplpush(args: any[], callback?: ResCallbackT): void;
160 | rpoplpush(...args: any[]): void;
161 | sadd(args: any[], callback?: ResCallbackT): void;
162 | sadd(...args: any[]): void;
163 | srem(args: any[], callback?: ResCallbackT): void;
164 | srem(...args: any[]): void;
165 | smove(args: any[], callback?: ResCallbackT): void;
166 | smove(...args: any[]): void;
167 | sismember(args: any[], callback?: ResCallbackT): void;
168 | sismember(...args: any[]): void;
169 | scard(args: any[], callback?: ResCallbackT): void;
170 | scard(...args: any[]): void;
171 | spop(args: any[], callback?: ResCallbackT): void;
172 | spop(...args: any[]): void;
173 | srandmember(args: any[], callback?: ResCallbackT): void;
174 | srandmember(...args: any[]): void;
175 | sinter(args: any[], callback?: ResCallbackT): void;
176 | sinter(...args: any[]): void;
177 | sinterstore(args: any[], callback?: ResCallbackT): void;
178 | sinterstore(...args: any[]): void;
179 | sunion(args: any[], callback?: ResCallbackT): void;
180 | sunion(...args: any[]): void;
181 | sunionstore(args: any[], callback?: ResCallbackT): void;
182 | sunionstore(...args: any[]): void;
183 | sdiff(args: any[], callback?: ResCallbackT): void;
184 | sdiff(...args: any[]): void;
185 | sdiffstore(args: any[], callback?: ResCallbackT): void;
186 | sdiffstore(...args: any[]): void;
187 | smembers(args: any[], callback?: ResCallbackT): void;
188 | smembers(...args: any[]): void;
189 | zadd(args: any[], callback?: ResCallbackT): void;
190 | zadd(...args: any[]): void;
191 | zincrby(args: any[], callback?: ResCallbackT): void;
192 | zincrby(...args: any[]): void;
193 | zrem(args: any[], callback?: ResCallbackT): void;
194 | zrem(...args: any[]): void;
195 | zremrangebyscore(args: any[], callback?: ResCallbackT): void;
196 | zremrangebyscore(...args: any[]): void;
197 | zremrangebyrank(args: any[], callback?: ResCallbackT): void;
198 | zremrangebyrank(...args: any[]): void;
199 | zunionstore(args: any[], callback?: ResCallbackT): void;
200 | zunionstore(...args: any[]): void;
201 | zinterstore(args: any[], callback?: ResCallbackT): void;
202 | zinterstore(...args: any[]): void;
203 | zrange(args: any[], callback?: ResCallbackT): void;
204 | zrange(...args: any[]): void;
205 | zrangebyscore(args: any[], callback?: ResCallbackT): void;
206 | zrangebyscore(...args: any[]): void;
207 | zrevrangebyscore(args: any[], callback?: ResCallbackT): void;
208 | zrevrangebyscore(...args: any[]): void;
209 | zcount(args: any[], callback?: ResCallbackT): void;
210 | zcount(...args: any[]): void;
211 | zrevrange(args: any[], callback?: ResCallbackT): void;
212 | zrevrange(...args: any[]): void;
213 | zcard(args: any[], callback?: ResCallbackT): void;
214 | zcard(...args: any[]): void;
215 | zscore(args: any[], callback?: ResCallbackT): void;
216 | zscore(...args: any[]): void;
217 | zrank(args: any[], callback?: ResCallbackT): void;
218 | zrank(...args: any[]): void;
219 | zrevrank(args: any[], callback?: ResCallbackT): void;
220 | zrevrank(...args: any[]): void;
221 | hset(args: any[], callback?: ResCallbackT): void;
222 | hset(...args: any[]): void;
223 | hsetnx(args: any[], callback?: ResCallbackT): void;
224 | hsetnx(...args: any[]): void;
225 | hget(args: any[], callback?: ResCallbackT): void;
226 | hget(...args: any[]): void;
227 | hmset(args: any[], callback?: ResCallbackT): void;
228 | hmset(key: string, hash: any, callback?: ResCallbackT): void;
229 | hmset(...args: any[]): void;
230 | hmget(args: any[], callback?: ResCallbackT): void;
231 | hmget(...args: any[]): void;
232 | hincrby(args: any[], callback?: ResCallbackT): void;
233 | hincrby(...args: any[]): void;
234 | hdel(args: any[], callback?: ResCallbackT): void;
235 | hdel(...args: any[]): void;
236 | hlen(args: any[], callback?: ResCallbackT): void;
237 | hlen(...args: any[]): void;
238 | hkeys(args: any[], callback?: ResCallbackT): void;
239 | hkeys(...args: any[]): void;
240 | hvals(args: any[], callback?: ResCallbackT): void;
241 | hvals(...args: any[]): void;
242 | hgetall(args: any[], callback?: ResCallbackT): void;
243 | hgetall(...args: any[]): void;
244 | hgetall(key: string, callback?: ResCallbackT): void;
245 | hexists(args: any[], callback?: ResCallbackT): void;
246 | hexists(...args: any[]): void;
247 | incrby(args: any[], callback?: ResCallbackT): void;
248 | incrby(...args: any[]): void;
249 | decrby(args: any[], callback?: ResCallbackT): void;
250 | decrby(...args: any[]): void;
251 | getset(args: any[], callback?: ResCallbackT): void;
252 | getset(...args: any[]): void;
253 | mset(args: any[], callback?: ResCallbackT): void;
254 | mset(...args: any[]): void;
255 | msetnx(args: any[], callback?: ResCallbackT): void;
256 | msetnx(...args: any[]): void;
257 | randomkey(args: any[], callback?: ResCallbackT): void;
258 | randomkey(...args: any[]): void;
259 | select(args: any[], callback?: ResCallbackT): void;
260 | select(...args: any[]): void;
261 | move(args: any[], callback?: ResCallbackT): void;
262 | move(...args: any[]): void;
263 | rename(args: any[], callback?: ResCallbackT): void;
264 | rename(...args: any[]): void;
265 | renamenx(args: any[], callback?: ResCallbackT): void;
266 | renamenx(...args: any[]): void;
267 | expire(args: any[], callback?: ResCallbackT): void;
268 | expire(...args: any[]): void;
269 | expireat(args: any[], callback?: ResCallbackT): void;
270 | expireat(...args: any[]): void;
271 | keys(args: any[], callback?: ResCallbackT): void;
272 | keys(...args: any[]): void;
273 | dbsize(args: any[], callback?: ResCallbackT): void;
274 | dbsize(...args: any[]): void;
275 | auth(args: any[], callback?: ResCallbackT): void;
276 | auth(...args: any[]): void;
277 | ping(args: any[], callback?: ResCallbackT): void;
278 | ping(...args: any[]): void;
279 | echo(args: any[], callback?: ResCallbackT): void;
280 | echo(...args: any[]): void;
281 | save(args: any[], callback?: ResCallbackT): void;
282 | save(...args: any[]): void;
283 | bgsave(args: any[], callback?: ResCallbackT): void;
284 | bgsave(...args: any[]): void;
285 | bgrewriteaof(args: any[], callback?: ResCallbackT): void;
286 | bgrewriteaof(...args: any[]): void;
287 | shutdown(args: any[], callback?: ResCallbackT): void;
288 | shutdown(...args: any[]): void;
289 | lastsave(args: any[], callback?: ResCallbackT): void;
290 | lastsave(...args: any[]): void;
291 | type(args: any[], callback?: ResCallbackT): void;
292 | type(...args: any[]): void;
293 | multi(args: any[], callback?: ResCallbackT): void;
294 | multi(...args: any[]): void;
295 | exec(args: any[], callback?: ResCallbackT): void;
296 | exec(...args: any[]): void;
297 | discard(args: any[], callback?: ResCallbackT): void;
298 | discard(...args: any[]): void;
299 | sync(args: any[], callback?: ResCallbackT): void;
300 | sync(...args: any[]): void;
301 | flushdb(args: any[], callback?: ResCallbackT): void;
302 | flushdb(...args: any[]): void;
303 | flushall(args: any[], callback?: ResCallbackT): void;
304 | flushall(...args: any[]): void;
305 | sort(args: any[], callback?: ResCallbackT): void;
306 | sort(...args: any[]): void;
307 | info(args: any[], callback?: ResCallbackT): void;
308 | info(...args: any[]): void;
309 | monitor(args: any[], callback?: ResCallbackT): void;
310 | monitor(...args: any[]): void;
311 | ttl(args: any[], callback?: ResCallbackT): void;
312 | ttl(...args: any[]): void;
313 | persist(args: any[], callback?: ResCallbackT): void;
314 | persist(...args: any[]): void;
315 | slaveof(args: any[], callback?: ResCallbackT): void;
316 | slaveof(...args: any[]): void;
317 | debug(args: any[], callback?: ResCallbackT): void;
318 | debug(...args: any[]): void;
319 | config(args: any[], callback?: ResCallbackT): void;
320 | config(...args: any[]): void;
321 | subscribe(args: any[], callback?: ResCallbackT): void;
322 | subscribe(...args: any[]): void;
323 | unsubscribe(args: any[], callback?: ResCallbackT): void;
324 | unsubscribe(...args: any[]): void;
325 | psubscribe(args: any[], callback?: ResCallbackT): void;
326 | psubscribe(...args: any[]): void;
327 | punsubscribe(args: any[], callback?: ResCallbackT): void;
328 | punsubscribe(...args: any[]): void;
329 | publish(args: any[], callback?: ResCallbackT): void;
330 | publish(...args: any[]): void;
331 | watch(args: any[], callback?: ResCallbackT): void;
332 | watch(...args: any[]): void;
333 | unwatch(args: any[], callback?: ResCallbackT): void;
334 | unwatch(...args: any[]): void;
335 | cluster(args: any[], callback?: ResCallbackT): void;
336 | cluster(...args: any[]): void;
337 | restore(args: any[], callback?: ResCallbackT): void;
338 | restore(...args: any[]): void;
339 | migrate(args: any[], callback?: ResCallbackT): void;
340 | migrate(...args: any[]): void;
341 | dump(args: any[], callback?: ResCallbackT): void;
342 | dump(...args: any[]): void;
343 | object(args: any[], callback?: ResCallbackT): void;
344 | object(...args: any[]): void;
345 | client(args: any[], callback?: ResCallbackT): void;
346 | client(...args: any[]): void;
347 | eval(args: any[], callback?: ResCallbackT): void;
348 | eval(...args: any[]): void;
349 | evalsha(args: any[], callback?: ResCallbackT): void;
350 | evalsha(...args: any[]): void;
351 | quit(args: any[], callback?: ResCallbackT): void;
352 | quit(...args: any[]): void;
353 | }
354 | }
355 |
--------------------------------------------------------------------------------
/typings/request/request.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for request
2 | // Project: https://github.com/mikeal/request
3 | // Definitions by: Carlos Ballesteros Velasco , bonnici , Bart van der Schoor
4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped
5 |
6 | // Imported from: https://github.com/soywiz/typescript-node-definitions/d.ts
7 |
8 | ///
9 | ///
10 |
11 | declare module 'request' {
12 | import stream = require('stream');
13 | import http = require('http');
14 | import FormData = require('form-data');
15 |
16 | export = RequestAPI;
17 |
18 | function RequestAPI(uri: string, options?: RequestAPI.Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): RequestAPI.Request;
19 | function RequestAPI(uri: string, callback?: (error: any, response: http.IncomingMessage, body: any) => void): RequestAPI.Request;
20 | function RequestAPI(options: RequestAPI.Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): RequestAPI.Request;
21 |
22 | module RequestAPI {
23 | export function defaults(options: Options): typeof RequestAPI;
24 |
25 | export function request(uri: string, options?: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
26 | export function request(uri: string, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
27 | export function request(options?: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
28 |
29 | export function get(uri: string, options?: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
30 | export function get(uri: string, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
31 | export function get(options: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
32 |
33 | export function post(uri: string, options?: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
34 | export function post(uri: string, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
35 | export function post(options: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
36 |
37 | export function put(uri: string, options?: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
38 | export function put(uri: string, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
39 | export function put(options: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
40 |
41 | export function head(uri: string, options?: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
42 | export function head(uri: string, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
43 | export function head(options: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
44 |
45 | export function patch(uri: string, options?: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
46 | export function patch(uri: string, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
47 | export function patch(options: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
48 |
49 | export function del(uri: string, options?: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
50 | export function del(uri: string, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
51 | export function del(options: Options, callback?: (error: any, response: http.IncomingMessage, body: any) => void): Request;
52 |
53 | export function forever(agentOptions: any, optionsArg: any): Request;
54 | export function jar(): CookieJar;
55 | export function cookie(str: string): Cookie;
56 |
57 | export var initParams: any;
58 |
59 | export interface Options {
60 | url?: string;
61 | uri?: string;
62 | callback?: (error: any, response: http.IncomingMessage, body: any) => void;
63 | jar?: any; // CookieJar
64 | form?: any; // Object or string
65 | auth?: AuthOptions;
66 | oauth?: OAuthOptions;
67 | aws?: AWSOptions;
68 | hawk ?: HawkOptions;
69 | qs?: Object;
70 | json?: any;
71 | multipart?: RequestPart[];
72 | agentOptions?: any;
73 | agentClass?: any;
74 | forever?: any;
75 | host?: string;
76 | port?: number;
77 | method?: string;
78 | headers?: Headers;
79 | body?: any;
80 | followRedirect?: boolean;
81 | followAllRedirects?: boolean;
82 | maxRedirects?: number;
83 | encoding?: string;
84 | pool?: any;
85 | timeout?: number;
86 | proxy?: any;
87 | strictSSL?: boolean;
88 | }
89 |
90 | export interface RequestPart {
91 | headers?: Headers;
92 | body: any;
93 | }
94 |
95 | export interface Request extends stream.Stream {
96 | readable: boolean;
97 | writable: boolean;
98 |
99 | getAgent(): http.Agent;
100 | //start(): void;
101 | //abort(): void;
102 | pipeDest(dest: any): void;
103 | setHeader(name: string, value: string, clobber?: boolean): Request;
104 | setHeaders(headers: Headers): Request;
105 | qs(q: Object, clobber?: boolean): Request;
106 | form(): FormData.FormData;
107 | form(form: any): Request;
108 | multipart(multipart: RequestPart[]): Request;
109 | json(val: any): Request;
110 | aws(opts: AWSOptions, now?: boolean): Request;
111 | auth(username: string, password: string, sendInmediately?: boolean, bearer?: string): Request;
112 | oauth(oauth: OAuthOptions): Request;
113 | jar(jar: CookieJar): Request;
114 |
115 | on(event: string, listener: Function): Request;
116 |
117 | write(buffer: Buffer, cb?: Function): boolean;
118 | write(str: string, cb?: Function): boolean;
119 | write(str: string, encoding: string, cb?: Function): boolean;
120 | write(str: string, encoding?: string, fd?: string): boolean;
121 | end(): void;
122 | end(chunk: Buffer, cb?: Function): void;
123 | end(chunk: string, cb?: Function): void;
124 | end(chunk: string, encoding: string, cb?: Function): void;
125 | pause(): void;
126 | resume(): void;
127 | abort(): void;
128 | destroy(): void;
129 | toJSON(): string;
130 | }
131 |
132 | export interface Headers {
133 | [key: string]: any;
134 | }
135 |
136 | export interface AuthOptions {
137 | user?: string;
138 | username?: string;
139 | pass?: string;
140 | password?: string;
141 | sendImmediately?: boolean;
142 | }
143 |
144 | export interface OAuthOptions {
145 | callback?: string;
146 | consumer_key?: string;
147 | consumer_secret?: string;
148 | token?: string;
149 | token_secret?: string;
150 | verifier?: string;
151 | }
152 |
153 | export interface HawkOptions {
154 | credentials: any;
155 | }
156 |
157 | export interface AWSOptions {
158 | secret: string;
159 | bucket?: string;
160 | }
161 |
162 | export interface CookieJar {
163 | add(cookie: Cookie): void;
164 | get(req: Request): Cookie;
165 | cookieString(req: Request): string;
166 | }
167 |
168 | export interface CookieValue {
169 | name: string;
170 | value: any;
171 | httpOnly: boolean;
172 | }
173 |
174 | export interface Cookie extends Array {
175 | constructor(name: string, req: Request): void;
176 | str: string;
177 | expires: Date;
178 | path: string;
179 | toString(): string;
180 | }
181 | }
182 | }
183 |
--------------------------------------------------------------------------------
/typings/validator/validator.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for validator.js v3.22.1
2 | // Project: https://github.com/chriso/validator.js
3 | // Definitions by: tgfjt
4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped
5 |
6 | // options for #isURL
7 | interface IURLoptions {
8 | protocols?: string[]
9 | require_tld?: boolean
10 | require_protocol?: boolean
11 | allow_underscores?: boolean
12 | }
13 |
14 | // options for isFQDN
15 | interface IFQDNoptions {
16 | require_tld?: boolean
17 | allow_underscores?: boolean
18 | }
19 |
20 | // options for normalizeEmail
21 | interface IEmailoptions {
22 | lowercase?: boolean
23 | }
24 |
25 | // callback type for #extend
26 | interface IExtendCallback {
27 | (argv: string): any
28 | }
29 |
30 | // return function for #extend
31 | interface IExtendFunc {
32 | (argv: string): boolean
33 | }
34 |
35 | interface IValidatorStatic {
36 | // add your own validators
37 | extend(name: string, fn: IExtendCallback): IExtendFunc;
38 |
39 | // check if the string matches the comparison.
40 | equals(str: string, comparison: any): boolean;
41 |
42 | // check if the string contains the seed.
43 | contains(str: string, elem: any): boolean;
44 |
45 | // check if string matches the pattern.
46 | matches(str: string, pattern: any, modifiers?: string): boolean;
47 |
48 | // check if the string is an email.
49 | isEmail(str: string): boolean;
50 |
51 | // check if the string is an URL.
52 | isURL(str: string, options?: IURLoptions): boolean;
53 |
54 | // check if the string is a fully qualified domain name (e.g. domain.com).
55 | isFQDN(str: string, options?: IFQDNoptions): boolean;
56 |
57 | // check if the string is an IP (version 4 or 6).
58 | isIP(str: string, version?: number): boolean;
59 |
60 | // check if the string contains only letters (a-zA-Z).
61 | isAlpha(str: string): boolean;
62 |
63 | // check if the string contains only numbers.
64 | isNumeric(str: string): boolean;
65 |
66 | // check if the string contains only letters and numbers.
67 | isAlphanumeric(str: string): boolean;
68 |
69 | // check if a string is base64 encoded.
70 | isBase64(str: string): boolean;
71 |
72 | // check if the string is a hexadecimal number.
73 | isHexadecimal(str: string): boolean;
74 |
75 | // check if the string is a hexadecimal color.
76 | isHexColor(str: string): boolean;
77 |
78 | // check if the string is lowercase.
79 | isLowercase(str: string): boolean;
80 |
81 | // check if the string is uppercase.
82 | isUppercase(str: string): boolean;
83 |
84 | // check if the string is an integer.
85 | isInt(str: string): boolean;
86 |
87 | // check if the string is a float.
88 | isFloat(str: string): boolean;
89 |
90 | // check if the string is a number that's divisible by another.
91 | isDivisibleBy(str: string, number: number): boolean;
92 |
93 | // check if the string is null.
94 | isNull(str: string): boolean;
95 |
96 | // check if the string's length falls in a range. Note: this function takes into account surrogate pairs.
97 | isLength(str: string, min: number, max?: number): boolean;
98 |
99 | // check if the string's length (in bytes) falls in a range.
100 | isByteLength(str: string, min: number, max?: number): boolean;
101 |
102 | // check if the string is a UUID (version 3, 4 or 5).
103 | isUUID(str: string, version?: number): boolean;
104 |
105 | // check if the string is a date.
106 | isDate(str: string): boolean;
107 |
108 | // check if the string is a date that's after the specified date (defaults to now).
109 | isAfter(str: string, date?: Date): boolean;
110 |
111 | // check if the string is a date that's before the specified date.
112 | isBefore(str: string, date?: Date): boolean;
113 |
114 | // check if the string is in a array of allowed values.
115 | isIn(str: string, values: any[]): boolean;
116 |
117 | // check if the string is a credit card.
118 | isCreditCard(str: string): boolean;
119 |
120 | // check if the string is an ISBN (version 10 or 13).
121 | isISBN(str: string, version?: number): boolean;
122 |
123 | // check if the string is valid JSON (note: uses JSON.parse).
124 | isJSON(str: string): boolean;
125 |
126 | // check if the string contains one or more multibyte chars.
127 | isMultibyte(str: string): boolean;
128 |
129 | // check if the string contains ASCII chars only.
130 | isAscii(str: string): boolean;
131 |
132 | // check if the string contains any full-width chars.
133 | isFullWidth(str: string): boolean;
134 |
135 | // check if the string contains any half-width chars.
136 | isHalfWidth(str: string): boolean;
137 |
138 | // check if the string contains a mixture of full and half-width chars.
139 | isVariableWidth(str: string): boolean;
140 |
141 | // check if the string contains any surrogate pairs chars.
142 | isSurrogatePair(str: string): boolean;
143 |
144 | // check if the string is a valid hex-encoded representation of a MongoDB ObjectId.
145 | isMongoId(str: string): boolean;
146 |
147 | // convert the input to a string.
148 | toString(input: any): string;
149 |
150 | // convert the input to a date, or null if the input is not a date.
151 | toDate(input: any): any; // Date or null
152 |
153 | // convert the input to a float, or NaN if the input is not a float.
154 | toFloat(input:any): number; // number or NaN
155 |
156 | // convert the input to an integer, or NaN if the input is not an integer.
157 | toInt(input:any, radix?: number): number; // number or NaN
158 |
159 | // convert the input to a boolean.
160 | toBoolean(input:any, strict?: boolean): boolean;
161 |
162 | // trim characters (whitespace by default) from both sides of the input.
163 | trim(input: any, chars?: string): string;
164 |
165 | // trim characters from the left-side of the input.
166 | ltrim(input: any, chars?: string): string;
167 |
168 | // trim characters from the right-side of the input.
169 | rtrim(input: any, chars?: string): string;
170 |
171 | // replace <, >, &, ' and " with HTML entities.
172 | escape(input: string): string;
173 |
174 | // remove characters with a numerical value < 32 and 127
175 | stripLow(input: string, keep_new_lines?: boolean): string;
176 |
177 | // remove characters that do not appear in the whitelist.
178 | whitelist(input: string, chars: string): string;
179 |
180 | // remove characters that appear in the blacklist.
181 | blacklist(input: string, chars: string): string;
182 |
183 | // canonicalize an email address.
184 | normalizeEmail(email: string, options?: IEmailoptions): string;
185 | }
186 |
187 | declare module "validator" {
188 | var validator: IValidatorStatic;
189 | export = validator;
190 | }
191 |
--------------------------------------------------------------------------------