include node_modules so release .zip is deployable
This commit is contained in:
+16
@@ -0,0 +1,16 @@
|
||||
name: websocket-tests
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 10.x
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- run: npm install
|
||||
|
||||
- run: npm run test
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
{
|
||||
// JSHint Default Configuration File (as on JSHint website)
|
||||
// See http://jshint.com/docs/ for more details
|
||||
|
||||
"maxerr" : 50, // {int} Maximum error before stopping
|
||||
|
||||
// Enforcing
|
||||
"bitwise" : false, // true: Prohibit bitwise operators (&, |, ^, etc.)
|
||||
"camelcase" : false, // true: Identifiers must be in camelCase
|
||||
"curly" : true, // true: Require {} for every new block or scope
|
||||
"eqeqeq" : true, // true: Require triple equals (===) for comparison
|
||||
"freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc.
|
||||
"forin" : false, // true: Require filtering for..in loops with obj.hasOwnProperty()
|
||||
"immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());`
|
||||
"latedef" : "nofunc", // true: Require variables/functions to be defined before being used
|
||||
"newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()`
|
||||
"noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee`
|
||||
"noempty" : true, // true: Prohibit use of empty blocks
|
||||
"nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters.
|
||||
"nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment)
|
||||
"plusplus" : false, // true: Prohibit use of `++` & `--`
|
||||
"quotmark" : "single", // Quotation mark consistency:
|
||||
// false : do nothing (default)
|
||||
// true : ensure whatever is used is consistent
|
||||
// "single" : require single quotes
|
||||
// "double" : require double quotes
|
||||
"undef" : true, // true: Require all non-global variables to be declared (prevents global leaks)
|
||||
"unused" : "vars", // vars: Require all defined variables be used, ignore function params
|
||||
"strict" : false, // true: Requires all functions run in ES5 Strict Mode
|
||||
"maxparams" : false, // {int} Max number of formal params allowed per function
|
||||
"maxdepth" : false, // {int} Max depth of nested blocks (within functions)
|
||||
"maxstatements" : false, // {int} Max number statements per function
|
||||
"maxcomplexity" : false, // {int} Max cyclomatic complexity per function
|
||||
"maxlen" : false, // {int} Max number of characters per line
|
||||
|
||||
// Relaxing
|
||||
"asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons)
|
||||
"boss" : false, // true: Tolerate assignments where comparisons would be expected
|
||||
"debug" : false, // true: Allow debugger statements e.g. browser breakpoints.
|
||||
"eqnull" : false, // true: Tolerate use of `== null`
|
||||
"es5" : false, // true: Allow ES5 syntax (ex: getters and setters)
|
||||
"esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`)
|
||||
"moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features)
|
||||
// (ex: `for each`, multiple try/catch, function expression…)
|
||||
"evil" : false, // true: Tolerate use of `eval` and `new Function()`
|
||||
"expr" : false, // true: Tolerate `ExpressionStatement` as Programs
|
||||
"funcscope" : false, // true: Tolerate defining variables inside control statements
|
||||
"globalstrict" : false, // true: Allow global "use strict" (also enables 'strict')
|
||||
"iterator" : false, // true: Tolerate using the `__iterator__` property
|
||||
"lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block
|
||||
"laxbreak" : false, // true: Tolerate possibly unsafe line breakings
|
||||
"laxcomma" : false, // true: Tolerate comma-first style coding
|
||||
"loopfunc" : false, // true: Tolerate functions being defined in loops
|
||||
"multistr" : false, // true: Tolerate multi-line strings
|
||||
"noyield" : false, // true: Tolerate generator functions with no yield statement in them.
|
||||
"notypeof" : false, // true: Tolerate invalid typeof operator values
|
||||
"proto" : false, // true: Tolerate using the `__proto__` property
|
||||
"scripturl" : false, // true: Tolerate script-targeted URLs
|
||||
"shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;`
|
||||
"sub" : true, // true: Tolerate using `[]` notation when it can still be expressed in dot notation
|
||||
"supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;`
|
||||
"validthis" : false, // true: Tolerate using this in a non-constructor function
|
||||
|
||||
// Environments
|
||||
"browser" : true, // Web Browser (window, document, etc)
|
||||
"browserify" : true, // Browserify (node.js code in the browser)
|
||||
"couch" : false, // CouchDB
|
||||
"devel" : true, // Development/debugging (alert, confirm, etc)
|
||||
"dojo" : false, // Dojo Toolkit
|
||||
"jasmine" : false, // Jasmine
|
||||
"jquery" : false, // jQuery
|
||||
"mocha" : false, // Mocha
|
||||
"mootools" : false, // MooTools
|
||||
"node" : true, // Node.js
|
||||
"nonstandard" : false, // Widely adopted globals (escape, unescape, etc)
|
||||
"prototypejs" : false, // Prototype and Scriptaculous
|
||||
"qunit" : false, // QUnit
|
||||
"rhino" : false, // Rhino
|
||||
"shelljs" : false, // ShellJS
|
||||
"worker" : false, // Web Workers
|
||||
"wsh" : false, // Windows Scripting Host
|
||||
"yui" : false, // Yahoo User Interface
|
||||
|
||||
// Custom Globals
|
||||
"globals" : { // additional predefined global variables
|
||||
"WebSocket": true
|
||||
}
|
||||
}
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
Changelog
|
||||
=========
|
||||
|
||||
Version 1.0.34
|
||||
--------------
|
||||
*Released 2021-04-14*
|
||||
|
||||
* Updated browser shim to use the native `globalThis` property when available. See [this MDN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) for context. Resolves [#415](https://github.com/theturtle32/WebSocket-Node/issues/415)
|
||||
|
||||
Version 1.0.33
|
||||
--------------
|
||||
*Released 2020-12-08*
|
||||
|
||||
* Added new configuration options to WebSocketServer allowing implementors to bypass parsing WebSocket extensions and HTTP Cookies if they are not needed. (Thanks, [@aetheon](https://github.com/aetheon))
|
||||
* Added new `upgradeError` event to WebSocketServer to allow for visibility into and logging of any parsing errors that might occur during the HTTP Upgrade phase. (Thanks, [@aetheon](https://github.com/aetheon))
|
||||
|
||||
Version 1.0.32
|
||||
--------------
|
||||
*Released 2020-08-28*
|
||||
|
||||
* Refactor to use [N-API modules](https://nodejs.org/api/n-api.html) from [ws project](https://github.com/websockets). (Thanks, [@andreek](https://github.com/andreek))
|
||||
* Specifically:
|
||||
* [utf-8-validate](https://github.com/websockets/utf-8-validate)
|
||||
* [bufferutil](https://github.com/websockets/bufferutil)
|
||||
* Removed some documentation notations about very old browsers and very old Websocket protocol drafts that are no longer relevant today in 2020.
|
||||
* Removed outdated notations and instructions about building native extensions, since those functions are now delegated to dependencies.
|
||||
* Add automated unit test executionn via Github Actions (Thanks, [@nebojsa94](https://github.com/nebojsa94))
|
||||
* Accept new connection close code `1015` ("TLS Handshake"). (More information at the [WebSocket Close Code Number Registry](https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number))
|
||||
|
||||
Version 1.0.31
|
||||
--------------
|
||||
*Released 2019-12-06*
|
||||
|
||||
* Fix [infinite loop in error handling](https://github.com/theturtle32/WebSocket-Node/issues/329) (Thanks, [@apirila](https://github.com/apirila))
|
||||
* Fix [memory leak with multiple WebSocket servers on the same HTTP server](https://github.com/theturtle32/WebSocket-Node/pull/339) (Thanks, [@nazar-pc](https://github.com/nazar-pc))
|
||||
* [Use es5-ext/global as a more robust way to resolve browser's window object](https://github.com/theturtle32/WebSocket-Node/pull/362) (Thanks, [@michaelsbradleyjr](https://github.com/michaelsbradleyjr))
|
||||
* [adding compatibility with V8 release greater than v7.6 (node and electron engines)](https://github.com/theturtle32/WebSocket-Node/pull/376) (Thanks, [@artynet](https://github.com/artynet))
|
||||
|
||||
Version 1.0.30
|
||||
--------------
|
||||
*Released 2019-09-12*
|
||||
|
||||
* Moved gulp back to devDependencies
|
||||
|
||||
Version 1.0.29
|
||||
--------------
|
||||
*Released 2019-07-03*
|
||||
|
||||
* Updated some dependencies and updated the .gitignore and .npmignore files
|
||||
|
||||
Version 1.0.28
|
||||
--------------
|
||||
*Released 2018-09-19*
|
||||
|
||||
* Updated to latest version of [nan](https://github.com/nodejs/nan)
|
||||
|
||||
Version 1.0.27
|
||||
--------------
|
||||
*Released 2018-09-19*
|
||||
|
||||
* Allowing additional request `headers` to be specified in the `tlsOptions` config parameter for WebSocketClient. See pull request #323
|
||||
* Resolving deprecation warnings relating to usage of `new Buffer`
|
||||
|
||||
Version 1.0.26
|
||||
--------------
|
||||
*Released 2018-04-27*
|
||||
|
||||
* No longer using the deprecated `noAssert` parameter for functions reading and writing binary numeric data. (Thanks, [@BridgeAR](https://github.com/BridgeAR))
|
||||
|
||||
Version 1.0.25
|
||||
--------------
|
||||
*Released 2017-10-18*
|
||||
|
||||
* Bumping minimum supported node version specified in package.json to v0.10.x because some upstream libraries no longer install on v0.8.x
|
||||
* [Allowing use of close codes 1012, 1013, 1014](https://www.iana.org/assignments/websocket/websocket.xml)
|
||||
* [Allowing the `Host` header to be overridden.](https://github.com/theturtle32/WebSocket-Node/pull/291) (Thanks, [@Juneil](https://github.com/Juneil))
|
||||
* [Mitigating infinite loop for broken connections](https://github.com/theturtle32/WebSocket-Node/pull/289) (Thanks, [@tvkit](https://github.com/tvkit))
|
||||
* [Fixed Markdown Typos](https://github.com/theturtle32/WebSocket-Node/pull/281) (Thanks, [@teramotodaiki](https://github.com/teramotodaiki))
|
||||
* [Adding old readyState constants for W3CWebSocket interface](https://github.com/theturtle32/WebSocket-Node/pull/282) (Thanks, [@thechriswalker](https://github.com/thechriswalker))
|
||||
|
||||
|
||||
Version 1.0.24
|
||||
--------------
|
||||
*Released 2016-12-28*
|
||||
|
||||
* Fixed a bug when using native keepalive on Node >= 6.0. (Thanks, [@prossin](https://github.com/prossin))
|
||||
* Upgrading outdated dependencies
|
||||
|
||||
Version 1.0.23
|
||||
--------------
|
||||
*Released 2016-05-18*
|
||||
|
||||
* Official support for Node 6.x
|
||||
* Updating dependencies. Specifically, updating nan to ^2.3.3
|
||||
|
||||
Version 1.0.22
|
||||
--------------
|
||||
*Released 2015-09-28*
|
||||
|
||||
* Updating to work with nan 2.x
|
||||
|
||||
Version 1.0.21
|
||||
--------------
|
||||
*Released 2015-07-22*
|
||||
|
||||
* Incremented and re-published to work around an aborted npm publish of v1.0.20.
|
||||
|
||||
Version 1.0.20
|
||||
--------------
|
||||
*Released 2015-07-22*
|
||||
|
||||
* Added EventTarget to the W3CWebSocket interface (Thanks, [@ibc](https://github.com/ibc)!)
|
||||
* Corrected an inaccurate error message. (Thanks, [@lekoaf](https://github.com/lekoaf)!)
|
||||
|
||||
Version 1.0.19
|
||||
--------------
|
||||
*Released 2015-05-28*
|
||||
|
||||
* Updated to nan v1.8.x (tested with v1.8.4)
|
||||
* Added `"license": "Apache-2.0"` to package.json via [pull request #199](https://github.com/theturtle32/WebSocket-Node/pull/199) by [@pgilad](https://github.com/pgilad). See [npm1k.org](http://npm1k.org/).
|
||||
|
||||
|
||||
Version 1.0.18
|
||||
--------------
|
||||
*Released 2015-03-19*
|
||||
|
||||
* Resolves [issue #195](https://github.com/theturtle32/WebSocket-Node/pull/179) - passing number to connection.send() causes crash
|
||||
* [Added close code/reason arguments to W3CWebSocket#close()](https://github.com/theturtle32/WebSocket-Node/issues/184)
|
||||
|
||||
|
||||
Version 1.0.17
|
||||
--------------
|
||||
*Released 2015-01-17*
|
||||
|
||||
* Resolves [issue #179](https://github.com/theturtle32/WebSocket-Node/pull/179) - Allow toBuffer to work with empty data
|
||||
|
||||
|
||||
Version 1.0.16
|
||||
--------------
|
||||
*Released 2015-01-16*
|
||||
|
||||
* Resolves [issue #178](https://github.com/theturtle32/WebSocket-Node/issues/178) - Ping Frames with no data
|
||||
|
||||
|
||||
Version 1.0.15
|
||||
--------------
|
||||
*Released 2015-01-13*
|
||||
|
||||
* Resolves [issue #177](https://github.com/theturtle32/WebSocket-Node/issues/177) - WebSocketClient ignores options unless it has a tlsOptions property
|
||||
|
||||
|
||||
Version 1.0.14
|
||||
--------------
|
||||
*Released 2014-12-03*
|
||||
|
||||
* Resolves [issue #173](https://github.com/theturtle32/WebSocket-Node/issues/173) - To allow the W3CWebSocket interface to accept an optional non-standard configuration object as its third parameter, which will be ignored when running in a browser context.
|
||||
|
||||
|
||||
Version 1.0.13
|
||||
--------------
|
||||
*Released 2014-11-29*
|
||||
|
||||
* Fixes [issue #171](https://github.com/theturtle32/WebSocket-Node/issues/171) - Code to prevent calling req.accept/req.reject multiple times breaks sanity checks in req.accept
|
||||
|
||||
|
||||
Version 1.0.12
|
||||
--------------
|
||||
*Released 2014-11-28*
|
||||
|
||||
* Fixes [issue #170](https://github.com/theturtle32/WebSocket-Node/issues/170) - Non-native XOR implementation broken after making JSHint happy
|
||||
|
||||
|
||||
Version 1.0.11
|
||||
--------------
|
||||
*Released 2014-11-25*
|
||||
|
||||
* Fixes some undefined behavior surrounding closing WebSocket connections and more reliably handles edge cases.
|
||||
* Adds an implementation of the W3C WebSocket API for browsers to facilitate sharing code between client and server via browserify. (Thanks, [@ibc](https://github.com/ibc)!)
|
||||
* `WebSocketConnection.prototype.close` now accepts optional `reasonCode` and `description` parameters.
|
||||
* Calling `accept` or `reject` more than once on a `WebSocketRequest` will now throw an error. [Issue #149](https://github.com/theturtle32/WebSocket-Node/issues/149)
|
||||
* Handling connections dropped by client before accepted by server [Issue #167](https://github.com/theturtle32/WebSocket-Node/issues/167)
|
||||
* Integrating Gulp and JSHint (Thanks, [@ibc](https://github.com/ibc)!)
|
||||
* Starting to add individual unit tests (using substack's [tape](github.com/substack/tape) and [faucet](github.com/substack/faucet))
|
||||
|
||||
|
||||
Version 1.0.10
|
||||
--------------
|
||||
*Released 2014-10-22*
|
||||
|
||||
* Fixed Issue [#146](https://github.com/theturtle32/WebSocket-Node/issues/146) that was causing WebSocketClient to throw errors when instantiated if passed `tlsOptions`.
|
||||
|
||||
Version 1.0.9
|
||||
-------------
|
||||
*Released 2014-10-20*
|
||||
|
||||
* Fixing an insidious corner-case bug that prevented `WebSocketConnection` from firing the `close` event in certain cases when there was an error on the underlying `Socket`, leading to connections sticking around forever, stuck erroneously in the `connected` state. These "ghost" connections would cause an error event when trying to write to them.
|
||||
* Removed deprecated `websocketVersion` property. Use `webSocketVersion` instead (case difference).
|
||||
* Allowing user to specify all properties for `tlsOptions` in WebSocketClient, not just a few whitelisted properties. This keeps us from having to constantly add new config properties for new versions of Node. (Thanks, [jesusprubio](https://github.com/jesusprubio))
|
||||
* Removing support for Node 0.4.x and 0.6.x.
|
||||
* Adding `fuzzingclient.json` spec file for the Autobahn Test Suite.
|
||||
* Now more fairly emitting `message` events from the `WebSocketConnection`. Previously, all buffered frames for a connection would be processed and all `message` events emitted before moving on to processing the next connection with available data. Now We process one frame per connection (most of the time) in a more fair round-robin fashion.
|
||||
* Now correctly calling the `EventEmitter` superclass constructor during class instance initialization.
|
||||
* `WebSocketClient.prototype.connect` now accepts the empty string (`''`) to mean "no subprotocol requested." Previously either `null` or an empty array (`[]`) was required.
|
||||
* Fixing a `TypeError` bug in `WebSocketRouter` (Thanks, [a0000778](https://github.com/a0000778))
|
||||
* Fixing a potential race condition when attaching event listeners to the underlying `Socket`. (Thanks [RichardBsolut](https://github.com/RichardBsolut))
|
||||
* `WebSocketClient` now accepts an optional options hash to be passed to `(http|https).request`. (Thanks [mildred](https://github.com/mildred) and [aus](https://github.com/aus)) This enables the following new abilities, amongst others:
|
||||
* Use WebSocket-Node from behind HTTP/HTTPS proxy servers using [koichik/node-tunnel](https://github.com/koichik/node-tunnel) or similar.
|
||||
* Specify the local port and local address to bind the outgoing request socket to.
|
||||
* Adding option to ignore `X-Forwarded-For` headers when accepting connections from untrusted clients.
|
||||
* Adding ability to mount a `WebSocketServer` instance to an arbitrary number of Node http/https servers.
|
||||
* Adding browser shim so Browserify won't blow up when trying to package up code that uses WebSocket-Node. The shim is a no-op, it ***does not implement a wrapper*** providing the WebSocket-Node API in the browser.
|
||||
* Incorporating upstream enhancements for the native C++ UTF-8 validation and xor masking functions. (Thanks [einaros](https://github.com/einaros) and [kkoopa](https://github.com/kkoopa))
|
||||
|
||||
|
||||
Version 1.0.8
|
||||
-------------
|
||||
*Released 2012-12-26*
|
||||
|
||||
* Fixed remaining naming inconsistency of "websocketVersion" as opposed to "webSocketVersion" throughout the code, and added deprecation warnings for use of the old casing throughout.
|
||||
* Fixed an issue with our case-insensitive handling of WebSocket subprotocols. Clients that requested a mixed-case subprotocol would end up failing the connection when the server accepted the connection, returning a lower-case version of the subprotocol name. Now we return the subprotocol name in the exact casing that was requested by the client, while still maintaining the case-insensitive verification logic for convenience and practicality.
|
||||
* Making sure that any socket-level activity timeout that may have been set on a TCP socket is removed when initializing a connection.
|
||||
* Added support for native TCP Keep-Alive instead of using the WebSocket ping/pong packets to serve that function.
|
||||
* Fixed cookie parsing to be compliant with RFC 2109
|
||||
|
||||
Version 1.0.7
|
||||
-------------
|
||||
*Released 2012-08-12*
|
||||
|
||||
* ***Native modules are now optional!*** If they fail to compile, WebSocket-Node will still work but will not verify that received UTF-8 data is valid, and xor masking/unmasking of payload data for security purposes will not be as efficient as it is performed in JavaScript instead of native code.
|
||||
* Reduced Node.JS version requirement back to v0.6.10
|
||||
|
||||
Version 1.0.6
|
||||
-------------
|
||||
*Released 2012-05-22*
|
||||
|
||||
* Now requires Node v0.6.13 since that's the first version that I can manage to successfully build the native UTF-8 validator with node-gyp through npm.
|
||||
|
||||
Version 1.0.5
|
||||
-------------
|
||||
*Released 2012-05-21*
|
||||
|
||||
* Fixes the issues that users were having building the native UTF-8 validator on Windows platforms. Special Thanks to:
|
||||
* [zerodivisi0n](https://github.com/zerodivisi0n)
|
||||
* [andreasbotsikas](https://github.com/andreasbotsikas)
|
||||
* Fixed accidental global variable usage (Thanks, [hakobera](https://github.com/hakobera)!)
|
||||
* Added callbacks to the send* methods that provide notification of messages being sent on the wire and any socket errors that may occur when sending a message. (Thanks, [zerodivisi0n](https://github.com/zerodivisi0n)!)
|
||||
* Added option to disable logging in the echo-server in the test folder (Thanks, [oberstet](https://github.com/oberstet)!)
|
||||
|
||||
|
||||
Version 1.0.4
|
||||
-------------
|
||||
*Released 2011-12-18*
|
||||
|
||||
* Now validates that incoming UTF-8 messages do, in fact, contain valid UTF-8 data. The connection is dropped with prejudice if invalid data is received. This strict behavior conforms to the WebSocket RFC and is verified by the Autobahn Test Suite. This is accomplished in a performant way by using a native C++ Node module created by [einaros](https://github.com/einaros).
|
||||
* Updated handling of connection closure to pass more of the Autobahn Test Suite.
|
||||
|
||||
Version 1.0.3
|
||||
-------------
|
||||
*Released 2011-12-18*
|
||||
|
||||
* Substantial speed increase (~150% on my machine, depending on the circumstances) due to an optimization in FastBufferList.js that drastically reduces the number of memory alloctions and buffer copying. ([kazuyukitanimura](https://github.com/kazuyukitanimura))
|
||||
|
||||
|
||||
Version 1.0.2
|
||||
-------------
|
||||
*Released 2011-11-28*
|
||||
|
||||
* Fixing whiteboard example to work under Node 0.6.x ([theturtle32](https://github.com/theturtle32))
|
||||
* Now correctly emitting a `close` event with a 1006 error code if there is a TCP error while writing to the socket during the handshake. ([theturtle32](https://github.com/theturtle32))
|
||||
* Catching errors when writing to the TCP socket during the handshake. ([justoneplanet](https://github.com/justoneplanet))
|
||||
* No longer outputting console.warn messages when there is an error writing to the TCP socket ([justoneplanet](https://github.com/justoneplanet))
|
||||
* Fixing some formatting errors, commas, semicolons, etc. ([kaisellgren](https://github.com/kaisellgren))
|
||||
|
||||
|
||||
Version 1.0.1
|
||||
-------------
|
||||
*Released 2011-11-21*
|
||||
|
||||
* Now works with Node 0.6.2 as well as 0.4.12
|
||||
* Support TLS in WebSocketClient
|
||||
* Added support for setting and reading cookies
|
||||
* Added WebSocketServer.prototype.broadcast(data) convenience method
|
||||
* Added `resourceURL` property to WebSocketRequest objects. It is a Node URL object with the `resource` and any query string params already parsed.
|
||||
* The WebSocket request router no longer includes the entire query string when trying to match the path name of the request.
|
||||
* WebSocketRouterRequest objects now include all the properties and events of WebSocketRequest objects.
|
||||
* Removed more console.log statements. Please rely on the various events emitted to be notified of error conditions. I decided that it is not a library's place to spew information to the console.
|
||||
* Renamed the `websocketVersion` property to `webSocketVersion` throughout the code to fix inconsistent capitalization. `websocketVersion` has been kept for compatibility but is deprecated and may be removed in the future.
|
||||
* Now outputting the sanitized version of custom header names rather than the raw value. This prevents invalid HTTP from being put onto the wire if given an illegal header name.
|
||||
|
||||
|
||||
I decided it's time to start maintaining a changelog now, starting with version 1.0.1.
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
autobahn:
|
||||
@NODE_PATH=lib node test/autobahn-test-client.js --host=127.0.0.1 --port=9000
|
||||
|
||||
autobahn-server:
|
||||
@NODE_PATH=lib node test/echo-server.js
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
WebSocket Client & Server Implementation for Node
|
||||
=================================================
|
||||
|
||||
[](http://badge.fury.io/js/websocket)
|
||||
|
||||
[](https://www.npmjs.com/package/websocket)
|
||||
|
||||
[ ](https://codeship.com/projects/61106)
|
||||
|
||||
Overview
|
||||
--------
|
||||
This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder.
|
||||
|
||||
|
||||
Documentation
|
||||
=============
|
||||
|
||||
[You can read the full API documentation in the docs folder.](docs/index.md)
|
||||
|
||||
|
||||
Changelog
|
||||
---------
|
||||
|
||||
***Current Version: 1.0.34*** - Release 2021-04-14
|
||||
|
||||
* Updated browser shim to use the native `globalThis` property when available. See [this MDN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) for context. Resolves [#415](https://github.com/theturtle32/WebSocket-Node/issues/415)
|
||||
|
||||
[View the full changelog](CHANGELOG.md)
|
||||
|
||||
Browser Support
|
||||
---------------
|
||||
|
||||
All current browsers are fully supported.
|
||||
|
||||
* Firefox 7-9 (Old) (Protocol Version 8)
|
||||
* Firefox 10+ (Protocol Version 13)
|
||||
* Chrome 14,15 (Old) (Protocol Version 8)
|
||||
* Chrome 16+ (Protocol Version 13)
|
||||
* Internet Explorer 10+ (Protocol Version 13)
|
||||
* Safari 6+ (Protocol Version 13)
|
||||
|
||||
Benchmarks
|
||||
----------
|
||||
There are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://theturtle32.github.com/WebSocket-Node/benchmarks/) that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4.
|
||||
|
||||
(These benchmarks are quite a bit outdated at this point, so take them with a grain of salt. Anyone up for running new benchmarks? I'll link to your report.)
|
||||
|
||||
Autobahn Tests
|
||||
--------------
|
||||
The very complete [Autobahn Test Suite](http://autobahn.ws/testsuite/) is used by most WebSocket implementations to test spec compliance and interoperability.
|
||||
|
||||
- [View Server Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/servers/)
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
In your project root:
|
||||
|
||||
$ npm install websocket
|
||||
|
||||
Then in your code:
|
||||
|
||||
```javascript
|
||||
var WebSocketServer = require('websocket').server;
|
||||
var WebSocketClient = require('websocket').client;
|
||||
var WebSocketFrame = require('websocket').frame;
|
||||
var WebSocketRouter = require('websocket').router;
|
||||
var W3CWebSocket = require('websocket').w3cwebsocket;
|
||||
```
|
||||
|
||||
Current Features:
|
||||
-----------------
|
||||
- Licensed under the Apache License, Version 2.0
|
||||
- Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake
|
||||
- Can handle/aggregate received fragmented messages
|
||||
- Can fragment outgoing messages
|
||||
- Router to mount multiple applications to various path and protocol combinations
|
||||
- TLS supported for outbound connections via WebSocketClient
|
||||
- TLS supported for server connections (use https.createServer instead of http.createServer)
|
||||
- Thanks to [pors](https://github.com/pors) for confirming this!
|
||||
- Cookie setting and parsing
|
||||
- Tunable settings
|
||||
- Max Receivable Frame Size
|
||||
- Max Aggregate ReceivedMessage Size
|
||||
- Whether to fragment outgoing messages
|
||||
- Fragmentation chunk size for outgoing messages
|
||||
- Whether to automatically send ping frames for the purposes of keepalive
|
||||
- Keep-alive ping interval
|
||||
- Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)
|
||||
- How long to wait after sending a close frame for acknowledgment before closing the socket.
|
||||
- [W3C WebSocket API](http://www.w3.org/TR/websockets/) for applications running on both Node and browsers (via the `W3CWebSocket` class).
|
||||
|
||||
|
||||
Known Issues/Missing Features:
|
||||
------------------------------
|
||||
- No API for user-provided protocol extensions.
|
||||
|
||||
|
||||
Usage Examples
|
||||
==============
|
||||
|
||||
Server Example
|
||||
--------------
|
||||
|
||||
Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
|
||||
|
||||
```javascript
|
||||
#!/usr/bin/env node
|
||||
var WebSocketServer = require('websocket').server;
|
||||
var http = require('http');
|
||||
|
||||
var server = http.createServer(function(request, response) {
|
||||
console.log((new Date()) + ' Received request for ' + request.url);
|
||||
response.writeHead(404);
|
||||
response.end();
|
||||
});
|
||||
server.listen(8080, function() {
|
||||
console.log((new Date()) + ' Server is listening on port 8080');
|
||||
});
|
||||
|
||||
wsServer = new WebSocketServer({
|
||||
httpServer: server,
|
||||
// You should not use autoAcceptConnections for production
|
||||
// applications, as it defeats all standard cross-origin protection
|
||||
// facilities built into the protocol and the browser. You should
|
||||
// *always* verify the connection's origin and decide whether or not
|
||||
// to accept it.
|
||||
autoAcceptConnections: false
|
||||
});
|
||||
|
||||
function originIsAllowed(origin) {
|
||||
// put logic here to detect whether the specified origin is allowed.
|
||||
return true;
|
||||
}
|
||||
|
||||
wsServer.on('request', function(request) {
|
||||
if (!originIsAllowed(request.origin)) {
|
||||
// Make sure we only accept requests from an allowed origin
|
||||
request.reject();
|
||||
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
|
||||
return;
|
||||
}
|
||||
|
||||
var connection = request.accept('echo-protocol', request.origin);
|
||||
console.log((new Date()) + ' Connection accepted.');
|
||||
connection.on('message', function(message) {
|
||||
if (message.type === 'utf8') {
|
||||
console.log('Received Message: ' + message.utf8Data);
|
||||
connection.sendUTF(message.utf8Data);
|
||||
}
|
||||
else if (message.type === 'binary') {
|
||||
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
|
||||
connection.sendBytes(message.binaryData);
|
||||
}
|
||||
});
|
||||
connection.on('close', function(reasonCode, description) {
|
||||
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Client Example
|
||||
--------------
|
||||
|
||||
This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.
|
||||
|
||||
*This code demonstrates a client in Node.js, not in the browser*
|
||||
|
||||
```javascript
|
||||
#!/usr/bin/env node
|
||||
var WebSocketClient = require('websocket').client;
|
||||
|
||||
var client = new WebSocketClient();
|
||||
|
||||
client.on('connectFailed', function(error) {
|
||||
console.log('Connect Error: ' + error.toString());
|
||||
});
|
||||
|
||||
client.on('connect', function(connection) {
|
||||
console.log('WebSocket Client Connected');
|
||||
connection.on('error', function(error) {
|
||||
console.log("Connection Error: " + error.toString());
|
||||
});
|
||||
connection.on('close', function() {
|
||||
console.log('echo-protocol Connection Closed');
|
||||
});
|
||||
connection.on('message', function(message) {
|
||||
if (message.type === 'utf8') {
|
||||
console.log("Received: '" + message.utf8Data + "'");
|
||||
}
|
||||
});
|
||||
|
||||
function sendNumber() {
|
||||
if (connection.connected) {
|
||||
var number = Math.round(Math.random() * 0xFFFFFF);
|
||||
connection.sendUTF(number.toString());
|
||||
setTimeout(sendNumber, 1000);
|
||||
}
|
||||
}
|
||||
sendNumber();
|
||||
});
|
||||
|
||||
client.connect('ws://localhost:8080/', 'echo-protocol');
|
||||
```
|
||||
|
||||
Client Example using the *W3C WebSocket API*
|
||||
--------------------------------------------
|
||||
|
||||
Same example as above but using the [W3C WebSocket API](http://www.w3.org/TR/websockets/).
|
||||
|
||||
```javascript
|
||||
var W3CWebSocket = require('websocket').w3cwebsocket;
|
||||
|
||||
var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');
|
||||
|
||||
client.onerror = function() {
|
||||
console.log('Connection Error');
|
||||
};
|
||||
|
||||
client.onopen = function() {
|
||||
console.log('WebSocket Client Connected');
|
||||
|
||||
function sendNumber() {
|
||||
if (client.readyState === client.OPEN) {
|
||||
var number = Math.round(Math.random() * 0xFFFFFF);
|
||||
client.send(number.toString());
|
||||
setTimeout(sendNumber, 1000);
|
||||
}
|
||||
}
|
||||
sendNumber();
|
||||
};
|
||||
|
||||
client.onclose = function() {
|
||||
console.log('echo-protocol Client Closed');
|
||||
};
|
||||
|
||||
client.onmessage = function(e) {
|
||||
if (typeof e.data === 'string') {
|
||||
console.log("Received: '" + e.data + "'");
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Request Router Example
|
||||
----------------------
|
||||
|
||||
For an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder.
|
||||
|
||||
|
||||
Resources
|
||||
---------
|
||||
|
||||
A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. [WebSockets: The Real-Time Web, Delivered](http://www.scribd.com/doc/60898569/WebSockets-The-Real-Time-Web-Delivered)
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Dependencies.
|
||||
*/
|
||||
var gulp = require('gulp');
|
||||
var jshint = require('gulp-jshint');
|
||||
|
||||
gulp.task('lint', function() {
|
||||
return gulp.src(['gulpfile.js', 'lib/**/*.js', 'test/**/*.js'])
|
||||
.pipe(jshint('.jshintrc'))
|
||||
.pipe(jshint.reporter('jshint-stylish', {verbose: true}))
|
||||
.pipe(jshint.reporter('fail'));
|
||||
});
|
||||
|
||||
gulp.task('default', gulp.series('lint'));
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require('./lib/websocket');
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var Deprecation = {
|
||||
disableWarnings: false,
|
||||
|
||||
deprecationWarningMap: {
|
||||
|
||||
},
|
||||
|
||||
warn: function(deprecationName) {
|
||||
if (!this.disableWarnings && this.deprecationWarningMap[deprecationName]) {
|
||||
console.warn('DEPRECATION WARNING: ' + this.deprecationWarningMap[deprecationName]);
|
||||
this.deprecationWarningMap[deprecationName] = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = Deprecation;
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var WebSocketClient = require('./WebSocketClient');
|
||||
var toBuffer = require('typedarray-to-buffer');
|
||||
var yaeti = require('yaeti');
|
||||
|
||||
|
||||
const CONNECTING = 0;
|
||||
const OPEN = 1;
|
||||
const CLOSING = 2;
|
||||
const CLOSED = 3;
|
||||
|
||||
|
||||
module.exports = W3CWebSocket;
|
||||
|
||||
|
||||
function W3CWebSocket(url, protocols, origin, headers, requestOptions, clientConfig) {
|
||||
// Make this an EventTarget.
|
||||
yaeti.EventTarget.call(this);
|
||||
|
||||
// Sanitize clientConfig.
|
||||
clientConfig = clientConfig || {};
|
||||
clientConfig.assembleFragments = true; // Required in the W3C API.
|
||||
|
||||
var self = this;
|
||||
|
||||
this._url = url;
|
||||
this._readyState = CONNECTING;
|
||||
this._protocol = undefined;
|
||||
this._extensions = '';
|
||||
this._bufferedAmount = 0; // Hack, always 0.
|
||||
this._binaryType = 'arraybuffer'; // TODO: Should be 'blob' by default, but Node has no Blob.
|
||||
|
||||
// The WebSocketConnection instance.
|
||||
this._connection = undefined;
|
||||
|
||||
// WebSocketClient instance.
|
||||
this._client = new WebSocketClient(clientConfig);
|
||||
|
||||
this._client.on('connect', function(connection) {
|
||||
onConnect.call(self, connection);
|
||||
});
|
||||
|
||||
this._client.on('connectFailed', function() {
|
||||
onConnectFailed.call(self);
|
||||
});
|
||||
|
||||
this._client.connect(url, protocols, origin, headers, requestOptions);
|
||||
}
|
||||
|
||||
|
||||
// Expose W3C read only attributes.
|
||||
Object.defineProperties(W3CWebSocket.prototype, {
|
||||
url: { get: function() { return this._url; } },
|
||||
readyState: { get: function() { return this._readyState; } },
|
||||
protocol: { get: function() { return this._protocol; } },
|
||||
extensions: { get: function() { return this._extensions; } },
|
||||
bufferedAmount: { get: function() { return this._bufferedAmount; } }
|
||||
});
|
||||
|
||||
|
||||
// Expose W3C write/read attributes.
|
||||
Object.defineProperties(W3CWebSocket.prototype, {
|
||||
binaryType: {
|
||||
get: function() {
|
||||
return this._binaryType;
|
||||
},
|
||||
set: function(type) {
|
||||
// TODO: Just 'arraybuffer' supported.
|
||||
if (type !== 'arraybuffer') {
|
||||
throw new SyntaxError('just "arraybuffer" type allowed for "binaryType" attribute');
|
||||
}
|
||||
this._binaryType = type;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Expose W3C readyState constants into the WebSocket instance as W3C states.
|
||||
[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) {
|
||||
Object.defineProperty(W3CWebSocket.prototype, property[0], {
|
||||
get: function() { return property[1]; }
|
||||
});
|
||||
});
|
||||
|
||||
// Also expose W3C readyState constants into the WebSocket class (not defined by the W3C,
|
||||
// but there are so many libs relying on them).
|
||||
[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) {
|
||||
Object.defineProperty(W3CWebSocket, property[0], {
|
||||
get: function() { return property[1]; }
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
W3CWebSocket.prototype.send = function(data) {
|
||||
if (this._readyState !== OPEN) {
|
||||
throw new Error('cannot call send() while not connected');
|
||||
}
|
||||
|
||||
// Text.
|
||||
if (typeof data === 'string' || data instanceof String) {
|
||||
this._connection.sendUTF(data);
|
||||
}
|
||||
// Binary.
|
||||
else {
|
||||
// Node Buffer.
|
||||
if (data instanceof Buffer) {
|
||||
this._connection.sendBytes(data);
|
||||
}
|
||||
// If ArrayBuffer or ArrayBufferView convert it to Node Buffer.
|
||||
else if (data.byteLength || data.byteLength === 0) {
|
||||
data = toBuffer(data);
|
||||
this._connection.sendBytes(data);
|
||||
}
|
||||
else {
|
||||
throw new Error('unknown binary data:', data);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
W3CWebSocket.prototype.close = function(code, reason) {
|
||||
switch(this._readyState) {
|
||||
case CONNECTING:
|
||||
// NOTE: We don't have the WebSocketConnection instance yet so no
|
||||
// way to close the TCP connection.
|
||||
// Artificially invoke the onConnectFailed event.
|
||||
onConnectFailed.call(this);
|
||||
// And close if it connects after a while.
|
||||
this._client.on('connect', function(connection) {
|
||||
if (code) {
|
||||
connection.close(code, reason);
|
||||
} else {
|
||||
connection.close();
|
||||
}
|
||||
});
|
||||
break;
|
||||
case OPEN:
|
||||
this._readyState = CLOSING;
|
||||
if (code) {
|
||||
this._connection.close(code, reason);
|
||||
} else {
|
||||
this._connection.close();
|
||||
}
|
||||
break;
|
||||
case CLOSING:
|
||||
case CLOSED:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Private API.
|
||||
*/
|
||||
|
||||
|
||||
function createCloseEvent(code, reason) {
|
||||
var event = new yaeti.Event('close');
|
||||
|
||||
event.code = code;
|
||||
event.reason = reason;
|
||||
event.wasClean = (typeof code === 'undefined' || code === 1000);
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
|
||||
function createMessageEvent(data) {
|
||||
var event = new yaeti.Event('message');
|
||||
|
||||
event.data = data;
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
|
||||
function onConnect(connection) {
|
||||
var self = this;
|
||||
|
||||
this._readyState = OPEN;
|
||||
this._connection = connection;
|
||||
this._protocol = connection.protocol;
|
||||
this._extensions = connection.extensions;
|
||||
|
||||
this._connection.on('close', function(code, reason) {
|
||||
onClose.call(self, code, reason);
|
||||
});
|
||||
|
||||
this._connection.on('message', function(msg) {
|
||||
onMessage.call(self, msg);
|
||||
});
|
||||
|
||||
this.dispatchEvent(new yaeti.Event('open'));
|
||||
}
|
||||
|
||||
|
||||
function onConnectFailed() {
|
||||
destroy.call(this);
|
||||
this._readyState = CLOSED;
|
||||
|
||||
try {
|
||||
this.dispatchEvent(new yaeti.Event('error'));
|
||||
} finally {
|
||||
this.dispatchEvent(createCloseEvent(1006, 'connection failed'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function onClose(code, reason) {
|
||||
destroy.call(this);
|
||||
this._readyState = CLOSED;
|
||||
|
||||
this.dispatchEvent(createCloseEvent(code, reason || ''));
|
||||
}
|
||||
|
||||
|
||||
function onMessage(message) {
|
||||
if (message.utf8Data) {
|
||||
this.dispatchEvent(createMessageEvent(message.utf8Data));
|
||||
}
|
||||
else if (message.binaryData) {
|
||||
// Must convert from Node Buffer to ArrayBuffer.
|
||||
// TODO: or to a Blob (which does not exist in Node!).
|
||||
if (this.binaryType === 'arraybuffer') {
|
||||
var buffer = message.binaryData;
|
||||
var arraybuffer = new ArrayBuffer(buffer.length);
|
||||
var view = new Uint8Array(arraybuffer);
|
||||
for (var i=0, len=buffer.length; i<len; ++i) {
|
||||
view[i] = buffer[i];
|
||||
}
|
||||
this.dispatchEvent(createMessageEvent(arraybuffer));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function destroy() {
|
||||
this._client.removeAllListeners();
|
||||
if (this._connection) {
|
||||
this._connection.removeAllListeners();
|
||||
}
|
||||
}
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var utils = require('./utils');
|
||||
var extend = utils.extend;
|
||||
var util = require('util');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var http = require('http');
|
||||
var https = require('https');
|
||||
var url = require('url');
|
||||
var crypto = require('crypto');
|
||||
var WebSocketConnection = require('./WebSocketConnection');
|
||||
var bufferAllocUnsafe = utils.bufferAllocUnsafe;
|
||||
|
||||
var protocolSeparators = [
|
||||
'(', ')', '<', '>', '@',
|
||||
',', ';', ':', '\\', '\"',
|
||||
'/', '[', ']', '?', '=',
|
||||
'{', '}', ' ', String.fromCharCode(9)
|
||||
];
|
||||
|
||||
var excludedTlsOptions = ['hostname','port','method','path','headers'];
|
||||
|
||||
function WebSocketClient(config) {
|
||||
// Superclass Constructor
|
||||
EventEmitter.call(this);
|
||||
|
||||
// TODO: Implement extensions
|
||||
|
||||
this.config = {
|
||||
// 1MiB max frame size.
|
||||
maxReceivedFrameSize: 0x100000,
|
||||
|
||||
// 8MiB max message size, only applicable if
|
||||
// assembleFragments is true
|
||||
maxReceivedMessageSize: 0x800000,
|
||||
|
||||
// Outgoing messages larger than fragmentationThreshold will be
|
||||
// split into multiple fragments.
|
||||
fragmentOutgoingMessages: true,
|
||||
|
||||
// Outgoing frames are fragmented if they exceed this threshold.
|
||||
// Default is 16KiB
|
||||
fragmentationThreshold: 0x4000,
|
||||
|
||||
// Which version of the protocol to use for this session. This
|
||||
// option will be removed once the protocol is finalized by the IETF
|
||||
// It is only available to ease the transition through the
|
||||
// intermediate draft protocol versions.
|
||||
// At present, it only affects the name of the Origin header.
|
||||
webSocketVersion: 13,
|
||||
|
||||
// If true, fragmented messages will be automatically assembled
|
||||
// and the full message will be emitted via a 'message' event.
|
||||
// If false, each frame will be emitted via a 'frame' event and
|
||||
// the application will be responsible for aggregating multiple
|
||||
// fragmented frames. Single-frame messages will emit a 'message'
|
||||
// event in addition to the 'frame' event.
|
||||
// Most users will want to leave this set to 'true'
|
||||
assembleFragments: true,
|
||||
|
||||
// The Nagle Algorithm makes more efficient use of network resources
|
||||
// by introducing a small delay before sending small packets so that
|
||||
// multiple messages can be batched together before going onto the
|
||||
// wire. This however comes at the cost of latency, so the default
|
||||
// is to disable it. If you don't need low latency and are streaming
|
||||
// lots of small messages, you can change this to 'false'
|
||||
disableNagleAlgorithm: true,
|
||||
|
||||
// The number of milliseconds to wait after sending a close frame
|
||||
// for an acknowledgement to come back before giving up and just
|
||||
// closing the socket.
|
||||
closeTimeout: 5000,
|
||||
|
||||
// Options to pass to https.connect if connecting via TLS
|
||||
tlsOptions: {}
|
||||
};
|
||||
|
||||
if (config) {
|
||||
var tlsOptions;
|
||||
if (config.tlsOptions) {
|
||||
tlsOptions = config.tlsOptions;
|
||||
delete config.tlsOptions;
|
||||
}
|
||||
else {
|
||||
tlsOptions = {};
|
||||
}
|
||||
extend(this.config, config);
|
||||
extend(this.config.tlsOptions, tlsOptions);
|
||||
}
|
||||
|
||||
this._req = null;
|
||||
|
||||
switch (this.config.webSocketVersion) {
|
||||
case 8:
|
||||
case 13:
|
||||
break;
|
||||
default:
|
||||
throw new Error('Requested webSocketVersion is not supported. Allowed values are 8 and 13.');
|
||||
}
|
||||
}
|
||||
|
||||
util.inherits(WebSocketClient, EventEmitter);
|
||||
|
||||
WebSocketClient.prototype.connect = function(requestUrl, protocols, origin, headers, extraRequestOptions) {
|
||||
var self = this;
|
||||
|
||||
if (typeof(protocols) === 'string') {
|
||||
if (protocols.length > 0) {
|
||||
protocols = [protocols];
|
||||
}
|
||||
else {
|
||||
protocols = [];
|
||||
}
|
||||
}
|
||||
if (!(protocols instanceof Array)) {
|
||||
protocols = [];
|
||||
}
|
||||
this.protocols = protocols;
|
||||
this.origin = origin;
|
||||
|
||||
if (typeof(requestUrl) === 'string') {
|
||||
this.url = url.parse(requestUrl);
|
||||
}
|
||||
else {
|
||||
this.url = requestUrl; // in case an already parsed url is passed in.
|
||||
}
|
||||
if (!this.url.protocol) {
|
||||
throw new Error('You must specify a full WebSocket URL, including protocol.');
|
||||
}
|
||||
if (!this.url.host) {
|
||||
throw new Error('You must specify a full WebSocket URL, including hostname. Relative URLs are not supported.');
|
||||
}
|
||||
|
||||
this.secure = (this.url.protocol === 'wss:');
|
||||
|
||||
// validate protocol characters:
|
||||
this.protocols.forEach(function(protocol) {
|
||||
for (var i=0; i < protocol.length; i ++) {
|
||||
var charCode = protocol.charCodeAt(i);
|
||||
var character = protocol.charAt(i);
|
||||
if (charCode < 0x0021 || charCode > 0x007E || protocolSeparators.indexOf(character) !== -1) {
|
||||
throw new Error('Protocol list contains invalid character "' + String.fromCharCode(charCode) + '"');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var defaultPorts = {
|
||||
'ws:': '80',
|
||||
'wss:': '443'
|
||||
};
|
||||
|
||||
if (!this.url.port) {
|
||||
this.url.port = defaultPorts[this.url.protocol];
|
||||
}
|
||||
|
||||
var nonce = bufferAllocUnsafe(16);
|
||||
for (var i=0; i < 16; i++) {
|
||||
nonce[i] = Math.round(Math.random()*0xFF);
|
||||
}
|
||||
this.base64nonce = nonce.toString('base64');
|
||||
|
||||
var hostHeaderValue = this.url.hostname;
|
||||
if ((this.url.protocol === 'ws:' && this.url.port !== '80') ||
|
||||
(this.url.protocol === 'wss:' && this.url.port !== '443')) {
|
||||
hostHeaderValue += (':' + this.url.port);
|
||||
}
|
||||
|
||||
var reqHeaders = {};
|
||||
if (this.secure && this.config.tlsOptions.hasOwnProperty('headers')) {
|
||||
// Allow for additional headers to be provided when connecting via HTTPS
|
||||
extend(reqHeaders, this.config.tlsOptions.headers);
|
||||
}
|
||||
if (headers) {
|
||||
// Explicitly provided headers take priority over any from tlsOptions
|
||||
extend(reqHeaders, headers);
|
||||
}
|
||||
extend(reqHeaders, {
|
||||
'Upgrade': 'websocket',
|
||||
'Connection': 'Upgrade',
|
||||
'Sec-WebSocket-Version': this.config.webSocketVersion.toString(10),
|
||||
'Sec-WebSocket-Key': this.base64nonce,
|
||||
'Host': reqHeaders.Host || hostHeaderValue
|
||||
});
|
||||
|
||||
if (this.protocols.length > 0) {
|
||||
reqHeaders['Sec-WebSocket-Protocol'] = this.protocols.join(', ');
|
||||
}
|
||||
if (this.origin) {
|
||||
if (this.config.webSocketVersion === 13) {
|
||||
reqHeaders['Origin'] = this.origin;
|
||||
}
|
||||
else if (this.config.webSocketVersion === 8) {
|
||||
reqHeaders['Sec-WebSocket-Origin'] = this.origin;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Implement extensions
|
||||
|
||||
var pathAndQuery;
|
||||
// Ensure it begins with '/'.
|
||||
if (this.url.pathname) {
|
||||
pathAndQuery = this.url.path;
|
||||
}
|
||||
else if (this.url.path) {
|
||||
pathAndQuery = '/' + this.url.path;
|
||||
}
|
||||
else {
|
||||
pathAndQuery = '/';
|
||||
}
|
||||
|
||||
function handleRequestError(error) {
|
||||
self._req = null;
|
||||
self.emit('connectFailed', error);
|
||||
}
|
||||
|
||||
var requestOptions = {
|
||||
agent: false
|
||||
};
|
||||
if (extraRequestOptions) {
|
||||
extend(requestOptions, extraRequestOptions);
|
||||
}
|
||||
// These options are always overridden by the library. The user is not
|
||||
// allowed to specify these directly.
|
||||
extend(requestOptions, {
|
||||
hostname: this.url.hostname,
|
||||
port: this.url.port,
|
||||
method: 'GET',
|
||||
path: pathAndQuery,
|
||||
headers: reqHeaders
|
||||
});
|
||||
if (this.secure) {
|
||||
var tlsOptions = this.config.tlsOptions;
|
||||
for (var key in tlsOptions) {
|
||||
if (tlsOptions.hasOwnProperty(key) && excludedTlsOptions.indexOf(key) === -1) {
|
||||
requestOptions[key] = tlsOptions[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var req = this._req = (this.secure ? https : http).request(requestOptions);
|
||||
req.on('upgrade', function handleRequestUpgrade(response, socket, head) {
|
||||
self._req = null;
|
||||
req.removeListener('error', handleRequestError);
|
||||
self.socket = socket;
|
||||
self.response = response;
|
||||
self.firstDataChunk = head;
|
||||
self.validateHandshake();
|
||||
});
|
||||
req.on('error', handleRequestError);
|
||||
|
||||
req.on('response', function(response) {
|
||||
self._req = null;
|
||||
if (utils.eventEmitterListenerCount(self, 'httpResponse') > 0) {
|
||||
self.emit('httpResponse', response, self);
|
||||
if (response.socket) {
|
||||
response.socket.end();
|
||||
}
|
||||
}
|
||||
else {
|
||||
var headerDumpParts = [];
|
||||
for (var headerName in response.headers) {
|
||||
headerDumpParts.push(headerName + ': ' + response.headers[headerName]);
|
||||
}
|
||||
self.failHandshake(
|
||||
'Server responded with a non-101 status: ' +
|
||||
response.statusCode + ' ' + response.statusMessage +
|
||||
'\nResponse Headers Follow:\n' +
|
||||
headerDumpParts.join('\n') + '\n'
|
||||
);
|
||||
}
|
||||
});
|
||||
req.end();
|
||||
};
|
||||
|
||||
WebSocketClient.prototype.validateHandshake = function() {
|
||||
var headers = this.response.headers;
|
||||
|
||||
if (this.protocols.length > 0) {
|
||||
this.protocol = headers['sec-websocket-protocol'];
|
||||
if (this.protocol) {
|
||||
if (this.protocols.indexOf(this.protocol) === -1) {
|
||||
this.failHandshake('Server did not respond with a requested protocol.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.failHandshake('Expected a Sec-WebSocket-Protocol header.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!(headers['connection'] && headers['connection'].toLocaleLowerCase() === 'upgrade')) {
|
||||
this.failHandshake('Expected a Connection: Upgrade header from the server');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(headers['upgrade'] && headers['upgrade'].toLocaleLowerCase() === 'websocket')) {
|
||||
this.failHandshake('Expected an Upgrade: websocket header from the server');
|
||||
return;
|
||||
}
|
||||
|
||||
var sha1 = crypto.createHash('sha1');
|
||||
sha1.update(this.base64nonce + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
|
||||
var expectedKey = sha1.digest('base64');
|
||||
|
||||
if (!headers['sec-websocket-accept']) {
|
||||
this.failHandshake('Expected Sec-WebSocket-Accept header from server');
|
||||
return;
|
||||
}
|
||||
|
||||
if (headers['sec-websocket-accept'] !== expectedKey) {
|
||||
this.failHandshake('Sec-WebSocket-Accept header from server didn\'t match expected value of ' + expectedKey);
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: Support extensions
|
||||
|
||||
this.succeedHandshake();
|
||||
};
|
||||
|
||||
WebSocketClient.prototype.failHandshake = function(errorDescription) {
|
||||
if (this.socket && this.socket.writable) {
|
||||
this.socket.end();
|
||||
}
|
||||
this.emit('connectFailed', new Error(errorDescription));
|
||||
};
|
||||
|
||||
WebSocketClient.prototype.succeedHandshake = function() {
|
||||
var connection = new WebSocketConnection(this.socket, [], this.protocol, true, this.config);
|
||||
|
||||
connection.webSocketVersion = this.config.webSocketVersion;
|
||||
connection._addSocketEventListeners();
|
||||
|
||||
this.emit('connect', connection);
|
||||
if (this.firstDataChunk.length > 0) {
|
||||
connection.handleSocketData(this.firstDataChunk);
|
||||
}
|
||||
this.firstDataChunk = null;
|
||||
};
|
||||
|
||||
WebSocketClient.prototype.abort = function() {
|
||||
if (this._req) {
|
||||
this._req.abort();
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = WebSocketClient;
|
||||
+896
@@ -0,0 +1,896 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var util = require('util');
|
||||
var utils = require('./utils');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var WebSocketFrame = require('./WebSocketFrame');
|
||||
var BufferList = require('../vendor/FastBufferList');
|
||||
var isValidUTF8 = require('utf-8-validate');
|
||||
var bufferAllocUnsafe = utils.bufferAllocUnsafe;
|
||||
var bufferFromString = utils.bufferFromString;
|
||||
|
||||
// Connected, fully-open, ready to send and receive frames
|
||||
const STATE_OPEN = 'open';
|
||||
// Received a close frame from the remote peer
|
||||
const STATE_PEER_REQUESTED_CLOSE = 'peer_requested_close';
|
||||
// Sent close frame to remote peer. No further data can be sent.
|
||||
const STATE_ENDING = 'ending';
|
||||
// Connection is fully closed. No further data can be sent or received.
|
||||
const STATE_CLOSED = 'closed';
|
||||
|
||||
var setImmediateImpl = ('setImmediate' in global) ?
|
||||
global.setImmediate.bind(global) :
|
||||
process.nextTick.bind(process);
|
||||
|
||||
var idCounter = 0;
|
||||
|
||||
function WebSocketConnection(socket, extensions, protocol, maskOutgoingPackets, config) {
|
||||
this._debug = utils.BufferingLogger('websocket:connection', ++idCounter);
|
||||
this._debug('constructor');
|
||||
|
||||
if (this._debug.enabled) {
|
||||
instrumentSocketForDebugging(this, socket);
|
||||
}
|
||||
|
||||
// Superclass Constructor
|
||||
EventEmitter.call(this);
|
||||
|
||||
this._pingListenerCount = 0;
|
||||
this.on('newListener', function(ev) {
|
||||
if (ev === 'ping'){
|
||||
this._pingListenerCount++;
|
||||
}
|
||||
}).on('removeListener', function(ev) {
|
||||
if (ev === 'ping') {
|
||||
this._pingListenerCount--;
|
||||
}
|
||||
});
|
||||
|
||||
this.config = config;
|
||||
this.socket = socket;
|
||||
this.protocol = protocol;
|
||||
this.extensions = extensions;
|
||||
this.remoteAddress = socket.remoteAddress;
|
||||
this.closeReasonCode = -1;
|
||||
this.closeDescription = null;
|
||||
this.closeEventEmitted = false;
|
||||
|
||||
// We have to mask outgoing packets if we're acting as a WebSocket client.
|
||||
this.maskOutgoingPackets = maskOutgoingPackets;
|
||||
|
||||
// We re-use the same buffers for the mask and frame header for all frames
|
||||
// received on each connection to avoid a small memory allocation for each
|
||||
// frame.
|
||||
this.maskBytes = bufferAllocUnsafe(4);
|
||||
this.frameHeader = bufferAllocUnsafe(10);
|
||||
|
||||
// the BufferList will handle the data streaming in
|
||||
this.bufferList = new BufferList();
|
||||
|
||||
// Prepare for receiving first frame
|
||||
this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
|
||||
this.fragmentationSize = 0; // data received so far...
|
||||
this.frameQueue = [];
|
||||
|
||||
// Various bits of connection state
|
||||
this.connected = true;
|
||||
this.state = STATE_OPEN;
|
||||
this.waitingForCloseResponse = false;
|
||||
// Received TCP FIN, socket's readable stream is finished.
|
||||
this.receivedEnd = false;
|
||||
|
||||
this.closeTimeout = this.config.closeTimeout;
|
||||
this.assembleFragments = this.config.assembleFragments;
|
||||
this.maxReceivedMessageSize = this.config.maxReceivedMessageSize;
|
||||
|
||||
this.outputBufferFull = false;
|
||||
this.inputPaused = false;
|
||||
this.receivedDataHandler = this.processReceivedData.bind(this);
|
||||
this._closeTimerHandler = this.handleCloseTimer.bind(this);
|
||||
|
||||
// Disable nagle algorithm?
|
||||
this.socket.setNoDelay(this.config.disableNagleAlgorithm);
|
||||
|
||||
// Make sure there is no socket inactivity timeout
|
||||
this.socket.setTimeout(0);
|
||||
|
||||
if (this.config.keepalive && !this.config.useNativeKeepalive) {
|
||||
if (typeof(this.config.keepaliveInterval) !== 'number') {
|
||||
throw new Error('keepaliveInterval must be specified and numeric ' +
|
||||
'if keepalive is true.');
|
||||
}
|
||||
this._keepaliveTimerHandler = this.handleKeepaliveTimer.bind(this);
|
||||
this.setKeepaliveTimer();
|
||||
|
||||
if (this.config.dropConnectionOnKeepaliveTimeout) {
|
||||
if (typeof(this.config.keepaliveGracePeriod) !== 'number') {
|
||||
throw new Error('keepaliveGracePeriod must be specified and ' +
|
||||
'numeric if dropConnectionOnKeepaliveTimeout ' +
|
||||
'is true.');
|
||||
}
|
||||
this._gracePeriodTimerHandler = this.handleGracePeriodTimer.bind(this);
|
||||
}
|
||||
}
|
||||
else if (this.config.keepalive && this.config.useNativeKeepalive) {
|
||||
if (!('setKeepAlive' in this.socket)) {
|
||||
throw new Error('Unable to use native keepalive: unsupported by ' +
|
||||
'this version of Node.');
|
||||
}
|
||||
this.socket.setKeepAlive(true, this.config.keepaliveInterval);
|
||||
}
|
||||
|
||||
// The HTTP Client seems to subscribe to socket error events
|
||||
// and re-dispatch them in such a way that doesn't make sense
|
||||
// for users of our client, so we want to make sure nobody
|
||||
// else is listening for error events on the socket besides us.
|
||||
this.socket.removeAllListeners('error');
|
||||
}
|
||||
|
||||
WebSocketConnection.CLOSE_REASON_NORMAL = 1000;
|
||||
WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001;
|
||||
WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002;
|
||||
WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003;
|
||||
WebSocketConnection.CLOSE_REASON_RESERVED = 1004; // Reserved value. Undefined meaning.
|
||||
WebSocketConnection.CLOSE_REASON_NOT_PROVIDED = 1005; // Not to be used on the wire
|
||||
WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006; // Not to be used on the wire
|
||||
WebSocketConnection.CLOSE_REASON_INVALID_DATA = 1007;
|
||||
WebSocketConnection.CLOSE_REASON_POLICY_VIOLATION = 1008;
|
||||
WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG = 1009;
|
||||
WebSocketConnection.CLOSE_REASON_EXTENSION_REQUIRED = 1010;
|
||||
WebSocketConnection.CLOSE_REASON_INTERNAL_SERVER_ERROR = 1011;
|
||||
WebSocketConnection.CLOSE_REASON_TLS_HANDSHAKE_FAILED = 1015; // Not to be used on the wire
|
||||
|
||||
WebSocketConnection.CLOSE_DESCRIPTIONS = {
|
||||
1000: 'Normal connection closure',
|
||||
1001: 'Remote peer is going away',
|
||||
1002: 'Protocol error',
|
||||
1003: 'Unprocessable input',
|
||||
1004: 'Reserved',
|
||||
1005: 'Reason not provided',
|
||||
1006: 'Abnormal closure, no further detail available',
|
||||
1007: 'Invalid data received',
|
||||
1008: 'Policy violation',
|
||||
1009: 'Message too big',
|
||||
1010: 'Extension requested by client is required',
|
||||
1011: 'Internal Server Error',
|
||||
1015: 'TLS Handshake Failed'
|
||||
};
|
||||
|
||||
function validateCloseReason(code) {
|
||||
if (code < 1000) {
|
||||
// Status codes in the range 0-999 are not used
|
||||
return false;
|
||||
}
|
||||
if (code >= 1000 && code <= 2999) {
|
||||
// Codes from 1000 - 2999 are reserved for use by the protocol. Only
|
||||
// a few codes are defined, all others are currently illegal.
|
||||
return [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015].indexOf(code) !== -1;
|
||||
}
|
||||
if (code >= 3000 && code <= 3999) {
|
||||
// Reserved for use by libraries, frameworks, and applications.
|
||||
// Should be registered with IANA. Interpretation of these codes is
|
||||
// undefined by the WebSocket protocol.
|
||||
return true;
|
||||
}
|
||||
if (code >= 4000 && code <= 4999) {
|
||||
// Reserved for private use. Interpretation of these codes is
|
||||
// undefined by the WebSocket protocol.
|
||||
return true;
|
||||
}
|
||||
if (code >= 5000) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
util.inherits(WebSocketConnection, EventEmitter);
|
||||
|
||||
WebSocketConnection.prototype._addSocketEventListeners = function() {
|
||||
this.socket.on('error', this.handleSocketError.bind(this));
|
||||
this.socket.on('end', this.handleSocketEnd.bind(this));
|
||||
this.socket.on('close', this.handleSocketClose.bind(this));
|
||||
this.socket.on('drain', this.handleSocketDrain.bind(this));
|
||||
this.socket.on('pause', this.handleSocketPause.bind(this));
|
||||
this.socket.on('resume', this.handleSocketResume.bind(this));
|
||||
this.socket.on('data', this.handleSocketData.bind(this));
|
||||
};
|
||||
|
||||
// set or reset the keepalive timer when data is received.
|
||||
WebSocketConnection.prototype.setKeepaliveTimer = function() {
|
||||
this._debug('setKeepaliveTimer');
|
||||
if (!this.config.keepalive || this.config.useNativeKeepalive) { return; }
|
||||
this.clearKeepaliveTimer();
|
||||
this.clearGracePeriodTimer();
|
||||
this._keepaliveTimeoutID = setTimeout(this._keepaliveTimerHandler, this.config.keepaliveInterval);
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.clearKeepaliveTimer = function() {
|
||||
if (this._keepaliveTimeoutID) {
|
||||
clearTimeout(this._keepaliveTimeoutID);
|
||||
}
|
||||
};
|
||||
|
||||
// No data has been received within config.keepaliveTimeout ms.
|
||||
WebSocketConnection.prototype.handleKeepaliveTimer = function() {
|
||||
this._debug('handleKeepaliveTimer');
|
||||
this._keepaliveTimeoutID = null;
|
||||
this.ping();
|
||||
|
||||
// If we are configured to drop connections if the client doesn't respond
|
||||
// then set the grace period timer.
|
||||
if (this.config.dropConnectionOnKeepaliveTimeout) {
|
||||
this.setGracePeriodTimer();
|
||||
}
|
||||
else {
|
||||
// Otherwise reset the keepalive timer to send the next ping.
|
||||
this.setKeepaliveTimer();
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.setGracePeriodTimer = function() {
|
||||
this._debug('setGracePeriodTimer');
|
||||
this.clearGracePeriodTimer();
|
||||
this._gracePeriodTimeoutID = setTimeout(this._gracePeriodTimerHandler, this.config.keepaliveGracePeriod);
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.clearGracePeriodTimer = function() {
|
||||
if (this._gracePeriodTimeoutID) {
|
||||
clearTimeout(this._gracePeriodTimeoutID);
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleGracePeriodTimer = function() {
|
||||
this._debug('handleGracePeriodTimer');
|
||||
// If this is called, the client has not responded and is assumed dead.
|
||||
this._gracePeriodTimeoutID = null;
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_ABNORMAL, 'Peer not responding.', true);
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleSocketData = function(data) {
|
||||
this._debug('handleSocketData');
|
||||
// Reset the keepalive timer when receiving data of any kind.
|
||||
this.setKeepaliveTimer();
|
||||
|
||||
// Add received data to our bufferList, which efficiently holds received
|
||||
// data chunks in a linked list of Buffer objects.
|
||||
this.bufferList.write(data);
|
||||
|
||||
this.processReceivedData();
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.processReceivedData = function() {
|
||||
this._debug('processReceivedData');
|
||||
// If we're not connected, we should ignore any data remaining on the buffer.
|
||||
if (!this.connected) { return; }
|
||||
|
||||
// Receiving/parsing is expected to be halted when paused.
|
||||
if (this.inputPaused) { return; }
|
||||
|
||||
var frame = this.currentFrame;
|
||||
|
||||
// WebSocketFrame.prototype.addData returns true if all data necessary to
|
||||
// parse the frame was available. It returns false if we are waiting for
|
||||
// more data to come in on the wire.
|
||||
if (!frame.addData(this.bufferList)) { this._debug('-- insufficient data for frame'); return; }
|
||||
|
||||
var self = this;
|
||||
|
||||
// Handle possible parsing errors
|
||||
if (frame.protocolError) {
|
||||
// Something bad happened.. get rid of this client.
|
||||
this._debug('-- protocol error');
|
||||
process.nextTick(function() {
|
||||
self.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, frame.dropReason);
|
||||
});
|
||||
return;
|
||||
}
|
||||
else if (frame.frameTooLarge) {
|
||||
this._debug('-- frame too large');
|
||||
process.nextTick(function() {
|
||||
self.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG, frame.dropReason);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// For now since we don't support extensions, all RSV bits are illegal
|
||||
if (frame.rsv1 || frame.rsv2 || frame.rsv3) {
|
||||
this._debug('-- illegal rsv flag');
|
||||
process.nextTick(function() {
|
||||
self.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
|
||||
'Unsupported usage of rsv bits without negotiated extension.');
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.assembleFragments) {
|
||||
this._debug('-- emitting frame');
|
||||
process.nextTick(function() { self.emit('frame', frame); });
|
||||
}
|
||||
|
||||
process.nextTick(function() { self.processFrame(frame); });
|
||||
|
||||
this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
|
||||
|
||||
// If there's data remaining, schedule additional processing, but yield
|
||||
// for now so that other connections have a chance to have their data
|
||||
// processed. We use setImmediate here instead of process.nextTick to
|
||||
// explicitly indicate that we wish for other I/O to be handled first.
|
||||
if (this.bufferList.length > 0) {
|
||||
setImmediateImpl(this.receivedDataHandler);
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleSocketError = function(error) {
|
||||
this._debug('handleSocketError: %j', error);
|
||||
if (this.state === STATE_CLOSED) {
|
||||
// See https://github.com/theturtle32/WebSocket-Node/issues/288
|
||||
this._debug(' --- Socket \'error\' after \'close\'');
|
||||
return;
|
||||
}
|
||||
this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL;
|
||||
this.closeDescription = 'Socket Error: ' + error.syscall + ' ' + error.code;
|
||||
this.connected = false;
|
||||
this.state = STATE_CLOSED;
|
||||
this.fragmentationSize = 0;
|
||||
if (utils.eventEmitterListenerCount(this, 'error') > 0) {
|
||||
this.emit('error', error);
|
||||
}
|
||||
this.socket.destroy();
|
||||
this._debug.printOutput();
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleSocketEnd = function() {
|
||||
this._debug('handleSocketEnd: received socket end. state = %s', this.state);
|
||||
this.receivedEnd = true;
|
||||
if (this.state === STATE_CLOSED) {
|
||||
// When using the TLS module, sometimes the socket will emit 'end'
|
||||
// after it emits 'close'. I don't think that's correct behavior,
|
||||
// but we should deal with it gracefully by ignoring it.
|
||||
this._debug(' --- Socket \'end\' after \'close\'');
|
||||
return;
|
||||
}
|
||||
if (this.state !== STATE_PEER_REQUESTED_CLOSE &&
|
||||
this.state !== STATE_ENDING) {
|
||||
this._debug(' --- UNEXPECTED socket end.');
|
||||
this.socket.end();
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleSocketClose = function(hadError) {
|
||||
this._debug('handleSocketClose: received socket close');
|
||||
this.socketHadError = hadError;
|
||||
this.connected = false;
|
||||
this.state = STATE_CLOSED;
|
||||
// If closeReasonCode is still set to -1 at this point then we must
|
||||
// not have received a close frame!!
|
||||
if (this.closeReasonCode === -1) {
|
||||
this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL;
|
||||
this.closeDescription = 'Connection dropped by remote peer.';
|
||||
}
|
||||
this.clearCloseTimer();
|
||||
this.clearKeepaliveTimer();
|
||||
this.clearGracePeriodTimer();
|
||||
if (!this.closeEventEmitted) {
|
||||
this.closeEventEmitted = true;
|
||||
this._debug('-- Emitting WebSocketConnection close event');
|
||||
this.emit('close', this.closeReasonCode, this.closeDescription);
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleSocketDrain = function() {
|
||||
this._debug('handleSocketDrain: socket drain event');
|
||||
this.outputBufferFull = false;
|
||||
this.emit('drain');
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleSocketPause = function() {
|
||||
this._debug('handleSocketPause: socket pause event');
|
||||
this.inputPaused = true;
|
||||
this.emit('pause');
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleSocketResume = function() {
|
||||
this._debug('handleSocketResume: socket resume event');
|
||||
this.inputPaused = false;
|
||||
this.emit('resume');
|
||||
this.processReceivedData();
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.pause = function() {
|
||||
this._debug('pause: pause requested');
|
||||
this.socket.pause();
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.resume = function() {
|
||||
this._debug('resume: resume requested');
|
||||
this.socket.resume();
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.close = function(reasonCode, description) {
|
||||
if (this.connected) {
|
||||
this._debug('close: Initating clean WebSocket close sequence.');
|
||||
if ('number' !== typeof reasonCode) {
|
||||
reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL;
|
||||
}
|
||||
if (!validateCloseReason(reasonCode)) {
|
||||
throw new Error('Close code ' + reasonCode + ' is not valid.');
|
||||
}
|
||||
if ('string' !== typeof description) {
|
||||
description = WebSocketConnection.CLOSE_DESCRIPTIONS[reasonCode];
|
||||
}
|
||||
this.closeReasonCode = reasonCode;
|
||||
this.closeDescription = description;
|
||||
this.setCloseTimer();
|
||||
this.sendCloseFrame(this.closeReasonCode, this.closeDescription);
|
||||
this.state = STATE_ENDING;
|
||||
this.connected = false;
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.drop = function(reasonCode, description, skipCloseFrame) {
|
||||
this._debug('drop');
|
||||
if (typeof(reasonCode) !== 'number') {
|
||||
reasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR;
|
||||
}
|
||||
|
||||
if (typeof(description) !== 'string') {
|
||||
// If no description is provided, try to look one up based on the
|
||||
// specified reasonCode.
|
||||
description = WebSocketConnection.CLOSE_DESCRIPTIONS[reasonCode];
|
||||
}
|
||||
|
||||
this._debug('Forcefully dropping connection. skipCloseFrame: %s, code: %d, description: %s',
|
||||
skipCloseFrame, reasonCode, description
|
||||
);
|
||||
|
||||
this.closeReasonCode = reasonCode;
|
||||
this.closeDescription = description;
|
||||
this.frameQueue = [];
|
||||
this.fragmentationSize = 0;
|
||||
if (!skipCloseFrame) {
|
||||
this.sendCloseFrame(reasonCode, description);
|
||||
}
|
||||
this.connected = false;
|
||||
this.state = STATE_CLOSED;
|
||||
this.clearCloseTimer();
|
||||
this.clearKeepaliveTimer();
|
||||
this.clearGracePeriodTimer();
|
||||
|
||||
if (!this.closeEventEmitted) {
|
||||
this.closeEventEmitted = true;
|
||||
this._debug('Emitting WebSocketConnection close event');
|
||||
this.emit('close', this.closeReasonCode, this.closeDescription);
|
||||
}
|
||||
|
||||
this._debug('Drop: destroying socket');
|
||||
this.socket.destroy();
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.setCloseTimer = function() {
|
||||
this._debug('setCloseTimer');
|
||||
this.clearCloseTimer();
|
||||
this._debug('Setting close timer');
|
||||
this.waitingForCloseResponse = true;
|
||||
this.closeTimer = setTimeout(this._closeTimerHandler, this.closeTimeout);
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.clearCloseTimer = function() {
|
||||
this._debug('clearCloseTimer');
|
||||
if (this.closeTimer) {
|
||||
this._debug('Clearing close timer');
|
||||
clearTimeout(this.closeTimer);
|
||||
this.waitingForCloseResponse = false;
|
||||
this.closeTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.handleCloseTimer = function() {
|
||||
this._debug('handleCloseTimer');
|
||||
this.closeTimer = null;
|
||||
if (this.waitingForCloseResponse) {
|
||||
this._debug('Close response not received from client. Forcing socket end.');
|
||||
this.waitingForCloseResponse = false;
|
||||
this.state = STATE_CLOSED;
|
||||
this.socket.end();
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.processFrame = function(frame) {
|
||||
this._debug('processFrame');
|
||||
this._debug(' -- frame: %s', frame);
|
||||
|
||||
// Any non-control opcode besides 0x00 (continuation) received in the
|
||||
// middle of a fragmented message is illegal.
|
||||
if (this.frameQueue.length !== 0 && (frame.opcode > 0x00 && frame.opcode < 0x08)) {
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
|
||||
'Illegal frame opcode 0x' + frame.opcode.toString(16) + ' ' +
|
||||
'received in middle of fragmented message.');
|
||||
return;
|
||||
}
|
||||
|
||||
switch(frame.opcode) {
|
||||
case 0x02: // WebSocketFrame.BINARY_FRAME
|
||||
this._debug('-- Binary Frame');
|
||||
if (this.assembleFragments) {
|
||||
if (frame.fin) {
|
||||
// Complete single-frame message received
|
||||
this._debug('---- Emitting \'message\' event');
|
||||
this.emit('message', {
|
||||
type: 'binary',
|
||||
binaryData: frame.binaryPayload
|
||||
});
|
||||
}
|
||||
else {
|
||||
// beginning of a fragmented message
|
||||
this.frameQueue.push(frame);
|
||||
this.fragmentationSize = frame.length;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 0x01: // WebSocketFrame.TEXT_FRAME
|
||||
this._debug('-- Text Frame');
|
||||
if (this.assembleFragments) {
|
||||
if (frame.fin) {
|
||||
if (!isValidUTF8(frame.binaryPayload)) {
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA,
|
||||
'Invalid UTF-8 Data Received');
|
||||
return;
|
||||
}
|
||||
// Complete single-frame message received
|
||||
this._debug('---- Emitting \'message\' event');
|
||||
this.emit('message', {
|
||||
type: 'utf8',
|
||||
utf8Data: frame.binaryPayload.toString('utf8')
|
||||
});
|
||||
}
|
||||
else {
|
||||
// beginning of a fragmented message
|
||||
this.frameQueue.push(frame);
|
||||
this.fragmentationSize = frame.length;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 0x00: // WebSocketFrame.CONTINUATION
|
||||
this._debug('-- Continuation Frame');
|
||||
if (this.assembleFragments) {
|
||||
if (this.frameQueue.length === 0) {
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
|
||||
'Unexpected Continuation Frame');
|
||||
return;
|
||||
}
|
||||
|
||||
this.fragmentationSize += frame.length;
|
||||
|
||||
if (this.fragmentationSize > this.maxReceivedMessageSize) {
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG,
|
||||
'Maximum message size exceeded.');
|
||||
return;
|
||||
}
|
||||
|
||||
this.frameQueue.push(frame);
|
||||
|
||||
if (frame.fin) {
|
||||
// end of fragmented message, so we process the whole
|
||||
// message now. We also have to decode the utf-8 data
|
||||
// for text frames after combining all the fragments.
|
||||
var bytesCopied = 0;
|
||||
var binaryPayload = bufferAllocUnsafe(this.fragmentationSize);
|
||||
var opcode = this.frameQueue[0].opcode;
|
||||
this.frameQueue.forEach(function (currentFrame) {
|
||||
currentFrame.binaryPayload.copy(binaryPayload, bytesCopied);
|
||||
bytesCopied += currentFrame.binaryPayload.length;
|
||||
});
|
||||
this.frameQueue = [];
|
||||
this.fragmentationSize = 0;
|
||||
|
||||
switch (opcode) {
|
||||
case 0x02: // WebSocketOpcode.BINARY_FRAME
|
||||
this.emit('message', {
|
||||
type: 'binary',
|
||||
binaryData: binaryPayload
|
||||
});
|
||||
break;
|
||||
case 0x01: // WebSocketOpcode.TEXT_FRAME
|
||||
if (!isValidUTF8(binaryPayload)) {
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA,
|
||||
'Invalid UTF-8 Data Received');
|
||||
return;
|
||||
}
|
||||
this.emit('message', {
|
||||
type: 'utf8',
|
||||
utf8Data: binaryPayload.toString('utf8')
|
||||
});
|
||||
break;
|
||||
default:
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
|
||||
'Unexpected first opcode in fragmentation sequence: 0x' + opcode.toString(16));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 0x09: // WebSocketFrame.PING
|
||||
this._debug('-- Ping Frame');
|
||||
|
||||
if (this._pingListenerCount > 0) {
|
||||
// logic to emit the ping frame: this is only done when a listener is known to exist
|
||||
// Expose a function allowing the user to override the default ping() behavior
|
||||
var cancelled = false;
|
||||
var cancel = function() {
|
||||
cancelled = true;
|
||||
};
|
||||
this.emit('ping', cancel, frame.binaryPayload);
|
||||
|
||||
// Only send a pong if the client did not indicate that he would like to cancel
|
||||
if (!cancelled) {
|
||||
this.pong(frame.binaryPayload);
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.pong(frame.binaryPayload);
|
||||
}
|
||||
|
||||
break;
|
||||
case 0x0A: // WebSocketFrame.PONG
|
||||
this._debug('-- Pong Frame');
|
||||
this.emit('pong', frame.binaryPayload);
|
||||
break;
|
||||
case 0x08: // WebSocketFrame.CONNECTION_CLOSE
|
||||
this._debug('-- Close Frame');
|
||||
if (this.waitingForCloseResponse) {
|
||||
// Got response to our request to close the connection.
|
||||
// Close is complete, so we just hang up.
|
||||
this._debug('---- Got close response from peer. Completing closing handshake.');
|
||||
this.clearCloseTimer();
|
||||
this.waitingForCloseResponse = false;
|
||||
this.state = STATE_CLOSED;
|
||||
this.socket.end();
|
||||
return;
|
||||
}
|
||||
|
||||
this._debug('---- Closing handshake initiated by peer.');
|
||||
// Got request from other party to close connection.
|
||||
// Send back acknowledgement and then hang up.
|
||||
this.state = STATE_PEER_REQUESTED_CLOSE;
|
||||
var respondCloseReasonCode;
|
||||
|
||||
// Make sure the close reason provided is legal according to
|
||||
// the protocol spec. Providing no close status is legal.
|
||||
// WebSocketFrame sets closeStatus to -1 by default, so if it
|
||||
// is still -1, then no status was provided.
|
||||
if (frame.invalidCloseFrameLength) {
|
||||
this.closeReasonCode = 1005; // 1005 = No reason provided.
|
||||
respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR;
|
||||
}
|
||||
else if (frame.closeStatus === -1 || validateCloseReason(frame.closeStatus)) {
|
||||
this.closeReasonCode = frame.closeStatus;
|
||||
respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_NORMAL;
|
||||
}
|
||||
else {
|
||||
this.closeReasonCode = frame.closeStatus;
|
||||
respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR;
|
||||
}
|
||||
|
||||
// If there is a textual description in the close frame, extract it.
|
||||
if (frame.binaryPayload.length > 1) {
|
||||
if (!isValidUTF8(frame.binaryPayload)) {
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA,
|
||||
'Invalid UTF-8 Data Received');
|
||||
return;
|
||||
}
|
||||
this.closeDescription = frame.binaryPayload.toString('utf8');
|
||||
}
|
||||
else {
|
||||
this.closeDescription = WebSocketConnection.CLOSE_DESCRIPTIONS[this.closeReasonCode];
|
||||
}
|
||||
this._debug(
|
||||
'------ Remote peer %s - code: %d - %s - close frame payload length: %d',
|
||||
this.remoteAddress, this.closeReasonCode,
|
||||
this.closeDescription, frame.length
|
||||
);
|
||||
this._debug('------ responding to remote peer\'s close request.');
|
||||
this.sendCloseFrame(respondCloseReasonCode, null);
|
||||
this.connected = false;
|
||||
break;
|
||||
default:
|
||||
this._debug('-- Unrecognized Opcode %d', frame.opcode);
|
||||
this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
|
||||
'Unrecognized Opcode: 0x' + frame.opcode.toString(16));
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.send = function(data, cb) {
|
||||
this._debug('send');
|
||||
if (Buffer.isBuffer(data)) {
|
||||
this.sendBytes(data, cb);
|
||||
}
|
||||
else if (typeof(data['toString']) === 'function') {
|
||||
this.sendUTF(data, cb);
|
||||
}
|
||||
else {
|
||||
throw new Error('Data provided must either be a Node Buffer or implement toString()');
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.sendUTF = function(data, cb) {
|
||||
data = bufferFromString(data.toString(), 'utf8');
|
||||
this._debug('sendUTF: %d bytes', data.length);
|
||||
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
|
||||
frame.opcode = 0x01; // WebSocketOpcode.TEXT_FRAME
|
||||
frame.binaryPayload = data;
|
||||
this.fragmentAndSend(frame, cb);
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.sendBytes = function(data, cb) {
|
||||
this._debug('sendBytes');
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
throw new Error('You must pass a Node Buffer object to WebSocketConnection.prototype.sendBytes()');
|
||||
}
|
||||
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
|
||||
frame.opcode = 0x02; // WebSocketOpcode.BINARY_FRAME
|
||||
frame.binaryPayload = data;
|
||||
this.fragmentAndSend(frame, cb);
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.ping = function(data) {
|
||||
this._debug('ping');
|
||||
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
|
||||
frame.opcode = 0x09; // WebSocketOpcode.PING
|
||||
frame.fin = true;
|
||||
if (data) {
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
data = bufferFromString(data.toString(), 'utf8');
|
||||
}
|
||||
if (data.length > 125) {
|
||||
this._debug('WebSocket: Data for ping is longer than 125 bytes. Truncating.');
|
||||
data = data.slice(0,124);
|
||||
}
|
||||
frame.binaryPayload = data;
|
||||
}
|
||||
this.sendFrame(frame);
|
||||
};
|
||||
|
||||
// Pong frames have to echo back the contents of the data portion of the
|
||||
// ping frame exactly, byte for byte.
|
||||
WebSocketConnection.prototype.pong = function(binaryPayload) {
|
||||
this._debug('pong');
|
||||
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
|
||||
frame.opcode = 0x0A; // WebSocketOpcode.PONG
|
||||
if (Buffer.isBuffer(binaryPayload) && binaryPayload.length > 125) {
|
||||
this._debug('WebSocket: Data for pong is longer than 125 bytes. Truncating.');
|
||||
binaryPayload = binaryPayload.slice(0,124);
|
||||
}
|
||||
frame.binaryPayload = binaryPayload;
|
||||
frame.fin = true;
|
||||
this.sendFrame(frame);
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.fragmentAndSend = function(frame, cb) {
|
||||
this._debug('fragmentAndSend');
|
||||
if (frame.opcode > 0x07) {
|
||||
throw new Error('You cannot fragment control frames.');
|
||||
}
|
||||
|
||||
var threshold = this.config.fragmentationThreshold;
|
||||
var length = frame.binaryPayload.length;
|
||||
|
||||
// Send immediately if fragmentation is disabled or the message is not
|
||||
// larger than the fragmentation threshold.
|
||||
if (!this.config.fragmentOutgoingMessages || (frame.binaryPayload && length <= threshold)) {
|
||||
frame.fin = true;
|
||||
this.sendFrame(frame, cb);
|
||||
return;
|
||||
}
|
||||
|
||||
var numFragments = Math.ceil(length / threshold);
|
||||
var sentFragments = 0;
|
||||
var sentCallback = function fragmentSentCallback(err) {
|
||||
if (err) {
|
||||
if (typeof cb === 'function') {
|
||||
// pass only the first error
|
||||
cb(err);
|
||||
cb = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
++sentFragments;
|
||||
if ((sentFragments === numFragments) && (typeof cb === 'function')) {
|
||||
cb();
|
||||
}
|
||||
};
|
||||
for (var i=1; i <= numFragments; i++) {
|
||||
var currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
|
||||
|
||||
// continuation opcode except for first frame.
|
||||
currentFrame.opcode = (i === 1) ? frame.opcode : 0x00;
|
||||
|
||||
// fin set on last frame only
|
||||
currentFrame.fin = (i === numFragments);
|
||||
|
||||
// length is likely to be shorter on the last fragment
|
||||
var currentLength = (i === numFragments) ? length - (threshold * (i-1)) : threshold;
|
||||
var sliceStart = threshold * (i-1);
|
||||
|
||||
// Slice the right portion of the original payload
|
||||
currentFrame.binaryPayload = frame.binaryPayload.slice(sliceStart, sliceStart + currentLength);
|
||||
|
||||
this.sendFrame(currentFrame, sentCallback);
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.sendCloseFrame = function(reasonCode, description, cb) {
|
||||
if (typeof(reasonCode) !== 'number') {
|
||||
reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL;
|
||||
}
|
||||
|
||||
this._debug('sendCloseFrame state: %s, reasonCode: %d, description: %s', this.state, reasonCode, description);
|
||||
|
||||
if (this.state !== STATE_OPEN && this.state !== STATE_PEER_REQUESTED_CLOSE) { return; }
|
||||
|
||||
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
|
||||
frame.fin = true;
|
||||
frame.opcode = 0x08; // WebSocketOpcode.CONNECTION_CLOSE
|
||||
frame.closeStatus = reasonCode;
|
||||
if (typeof(description) === 'string') {
|
||||
frame.binaryPayload = bufferFromString(description, 'utf8');
|
||||
}
|
||||
|
||||
this.sendFrame(frame, cb);
|
||||
this.socket.end();
|
||||
};
|
||||
|
||||
WebSocketConnection.prototype.sendFrame = function(frame, cb) {
|
||||
this._debug('sendFrame');
|
||||
frame.mask = this.maskOutgoingPackets;
|
||||
var flushed = this.socket.write(frame.toBuffer(), cb);
|
||||
this.outputBufferFull = !flushed;
|
||||
return flushed;
|
||||
};
|
||||
|
||||
module.exports = WebSocketConnection;
|
||||
|
||||
|
||||
|
||||
function instrumentSocketForDebugging(connection, socket) {
|
||||
/* jshint loopfunc: true */
|
||||
if (!connection._debug.enabled) { return; }
|
||||
|
||||
var originalSocketEmit = socket.emit;
|
||||
socket.emit = function(event) {
|
||||
connection._debug('||| Socket Event \'%s\'', event);
|
||||
originalSocketEmit.apply(this, arguments);
|
||||
};
|
||||
|
||||
for (var key in socket) {
|
||||
if ('function' !== typeof(socket[key])) { continue; }
|
||||
if (['emit'].indexOf(key) !== -1) { continue; }
|
||||
(function(key) {
|
||||
var original = socket[key];
|
||||
if (key === 'on') {
|
||||
socket[key] = function proxyMethod__EventEmitter__On() {
|
||||
connection._debug('||| Socket method called: %s (%s)', key, arguments[0]);
|
||||
return original.apply(this, arguments);
|
||||
};
|
||||
return;
|
||||
}
|
||||
socket[key] = function proxyMethod() {
|
||||
connection._debug('||| Socket method called: %s', key);
|
||||
return original.apply(this, arguments);
|
||||
};
|
||||
})(key);
|
||||
}
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var bufferUtil = require('bufferutil');
|
||||
var bufferAllocUnsafe = require('./utils').bufferAllocUnsafe;
|
||||
|
||||
const DECODE_HEADER = 1;
|
||||
const WAITING_FOR_16_BIT_LENGTH = 2;
|
||||
const WAITING_FOR_64_BIT_LENGTH = 3;
|
||||
const WAITING_FOR_MASK_KEY = 4;
|
||||
const WAITING_FOR_PAYLOAD = 5;
|
||||
const COMPLETE = 6;
|
||||
|
||||
// WebSocketConnection will pass shared buffer objects for maskBytes and
|
||||
// frameHeader into the constructor to avoid tons of small memory allocations
|
||||
// for each frame we have to parse. This is only used for parsing frames
|
||||
// we receive off the wire.
|
||||
function WebSocketFrame(maskBytes, frameHeader, config) {
|
||||
this.maskBytes = maskBytes;
|
||||
this.frameHeader = frameHeader;
|
||||
this.config = config;
|
||||
this.maxReceivedFrameSize = config.maxReceivedFrameSize;
|
||||
this.protocolError = false;
|
||||
this.frameTooLarge = false;
|
||||
this.invalidCloseFrameLength = false;
|
||||
this.parseState = DECODE_HEADER;
|
||||
this.closeStatus = -1;
|
||||
}
|
||||
|
||||
WebSocketFrame.prototype.addData = function(bufferList) {
|
||||
if (this.parseState === DECODE_HEADER) {
|
||||
if (bufferList.length >= 2) {
|
||||
bufferList.joinInto(this.frameHeader, 0, 0, 2);
|
||||
bufferList.advance(2);
|
||||
var firstByte = this.frameHeader[0];
|
||||
var secondByte = this.frameHeader[1];
|
||||
|
||||
this.fin = Boolean(firstByte & 0x80);
|
||||
this.rsv1 = Boolean(firstByte & 0x40);
|
||||
this.rsv2 = Boolean(firstByte & 0x20);
|
||||
this.rsv3 = Boolean(firstByte & 0x10);
|
||||
this.mask = Boolean(secondByte & 0x80);
|
||||
|
||||
this.opcode = firstByte & 0x0F;
|
||||
this.length = secondByte & 0x7F;
|
||||
|
||||
// Control frame sanity check
|
||||
if (this.opcode >= 0x08) {
|
||||
if (this.length > 125) {
|
||||
this.protocolError = true;
|
||||
this.dropReason = 'Illegal control frame longer than 125 bytes.';
|
||||
return true;
|
||||
}
|
||||
if (!this.fin) {
|
||||
this.protocolError = true;
|
||||
this.dropReason = 'Control frames must not be fragmented.';
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.length === 126) {
|
||||
this.parseState = WAITING_FOR_16_BIT_LENGTH;
|
||||
}
|
||||
else if (this.length === 127) {
|
||||
this.parseState = WAITING_FOR_64_BIT_LENGTH;
|
||||
}
|
||||
else {
|
||||
this.parseState = WAITING_FOR_MASK_KEY;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.parseState === WAITING_FOR_16_BIT_LENGTH) {
|
||||
if (bufferList.length >= 2) {
|
||||
bufferList.joinInto(this.frameHeader, 2, 0, 2);
|
||||
bufferList.advance(2);
|
||||
this.length = this.frameHeader.readUInt16BE(2);
|
||||
this.parseState = WAITING_FOR_MASK_KEY;
|
||||
}
|
||||
}
|
||||
else if (this.parseState === WAITING_FOR_64_BIT_LENGTH) {
|
||||
if (bufferList.length >= 8) {
|
||||
bufferList.joinInto(this.frameHeader, 2, 0, 8);
|
||||
bufferList.advance(8);
|
||||
var lengthPair = [
|
||||
this.frameHeader.readUInt32BE(2),
|
||||
this.frameHeader.readUInt32BE(2+4)
|
||||
];
|
||||
|
||||
if (lengthPair[0] !== 0) {
|
||||
this.protocolError = true;
|
||||
this.dropReason = 'Unsupported 64-bit length frame received';
|
||||
return true;
|
||||
}
|
||||
this.length = lengthPair[1];
|
||||
this.parseState = WAITING_FOR_MASK_KEY;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.parseState === WAITING_FOR_MASK_KEY) {
|
||||
if (this.mask) {
|
||||
if (bufferList.length >= 4) {
|
||||
bufferList.joinInto(this.maskBytes, 0, 0, 4);
|
||||
bufferList.advance(4);
|
||||
this.parseState = WAITING_FOR_PAYLOAD;
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.parseState = WAITING_FOR_PAYLOAD;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.parseState === WAITING_FOR_PAYLOAD) {
|
||||
if (this.length > this.maxReceivedFrameSize) {
|
||||
this.frameTooLarge = true;
|
||||
this.dropReason = 'Frame size of ' + this.length.toString(10) +
|
||||
' bytes exceeds maximum accepted frame size';
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.length === 0) {
|
||||
this.binaryPayload = bufferAllocUnsafe(0);
|
||||
this.parseState = COMPLETE;
|
||||
return true;
|
||||
}
|
||||
if (bufferList.length >= this.length) {
|
||||
this.binaryPayload = bufferList.take(this.length);
|
||||
bufferList.advance(this.length);
|
||||
if (this.mask) {
|
||||
bufferUtil.unmask(this.binaryPayload, this.maskBytes);
|
||||
// xor(this.binaryPayload, this.maskBytes, 0);
|
||||
}
|
||||
|
||||
if (this.opcode === 0x08) { // WebSocketOpcode.CONNECTION_CLOSE
|
||||
if (this.length === 1) {
|
||||
// Invalid length for a close frame. Must be zero or at least two.
|
||||
this.binaryPayload = bufferAllocUnsafe(0);
|
||||
this.invalidCloseFrameLength = true;
|
||||
}
|
||||
if (this.length >= 2) {
|
||||
this.closeStatus = this.binaryPayload.readUInt16BE(0);
|
||||
this.binaryPayload = this.binaryPayload.slice(2);
|
||||
}
|
||||
}
|
||||
|
||||
this.parseState = COMPLETE;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
WebSocketFrame.prototype.throwAwayPayload = function(bufferList) {
|
||||
if (bufferList.length >= this.length) {
|
||||
bufferList.advance(this.length);
|
||||
this.parseState = COMPLETE;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
WebSocketFrame.prototype.toBuffer = function(nullMask) {
|
||||
var maskKey;
|
||||
var headerLength = 2;
|
||||
var data;
|
||||
var outputPos;
|
||||
var firstByte = 0x00;
|
||||
var secondByte = 0x00;
|
||||
|
||||
if (this.fin) {
|
||||
firstByte |= 0x80;
|
||||
}
|
||||
if (this.rsv1) {
|
||||
firstByte |= 0x40;
|
||||
}
|
||||
if (this.rsv2) {
|
||||
firstByte |= 0x20;
|
||||
}
|
||||
if (this.rsv3) {
|
||||
firstByte |= 0x10;
|
||||
}
|
||||
if (this.mask) {
|
||||
secondByte |= 0x80;
|
||||
}
|
||||
|
||||
firstByte |= (this.opcode & 0x0F);
|
||||
|
||||
// the close frame is a special case because the close reason is
|
||||
// prepended to the payload data.
|
||||
if (this.opcode === 0x08) {
|
||||
this.length = 2;
|
||||
if (this.binaryPayload) {
|
||||
this.length += this.binaryPayload.length;
|
||||
}
|
||||
data = bufferAllocUnsafe(this.length);
|
||||
data.writeUInt16BE(this.closeStatus, 0);
|
||||
if (this.length > 2) {
|
||||
this.binaryPayload.copy(data, 2);
|
||||
}
|
||||
}
|
||||
else if (this.binaryPayload) {
|
||||
data = this.binaryPayload;
|
||||
this.length = data.length;
|
||||
}
|
||||
else {
|
||||
this.length = 0;
|
||||
}
|
||||
|
||||
if (this.length <= 125) {
|
||||
// encode the length directly into the two-byte frame header
|
||||
secondByte |= (this.length & 0x7F);
|
||||
}
|
||||
else if (this.length > 125 && this.length <= 0xFFFF) {
|
||||
// Use 16-bit length
|
||||
secondByte |= 126;
|
||||
headerLength += 2;
|
||||
}
|
||||
else if (this.length > 0xFFFF) {
|
||||
// Use 64-bit length
|
||||
secondByte |= 127;
|
||||
headerLength += 8;
|
||||
}
|
||||
|
||||
var output = bufferAllocUnsafe(this.length + headerLength + (this.mask ? 4 : 0));
|
||||
|
||||
// write the frame header
|
||||
output[0] = firstByte;
|
||||
output[1] = secondByte;
|
||||
|
||||
outputPos = 2;
|
||||
|
||||
if (this.length > 125 && this.length <= 0xFFFF) {
|
||||
// write 16-bit length
|
||||
output.writeUInt16BE(this.length, outputPos);
|
||||
outputPos += 2;
|
||||
}
|
||||
else if (this.length > 0xFFFF) {
|
||||
// write 64-bit length
|
||||
output.writeUInt32BE(0x00000000, outputPos);
|
||||
output.writeUInt32BE(this.length, outputPos + 4);
|
||||
outputPos += 8;
|
||||
}
|
||||
|
||||
if (this.mask) {
|
||||
maskKey = nullMask ? 0 : ((Math.random() * 0xFFFFFFFF) >>> 0);
|
||||
this.maskBytes.writeUInt32BE(maskKey, 0);
|
||||
|
||||
// write the mask key
|
||||
this.maskBytes.copy(output, outputPos);
|
||||
outputPos += 4;
|
||||
|
||||
if (data) {
|
||||
bufferUtil.mask(data, this.maskBytes, output, outputPos, this.length);
|
||||
}
|
||||
}
|
||||
else if (data) {
|
||||
data.copy(output, outputPos);
|
||||
}
|
||||
|
||||
return output;
|
||||
};
|
||||
|
||||
WebSocketFrame.prototype.toString = function() {
|
||||
return 'Opcode: ' + this.opcode + ', fin: ' + this.fin + ', length: ' + this.length + ', hasPayload: ' + Boolean(this.binaryPayload) + ', masked: ' + this.mask;
|
||||
};
|
||||
|
||||
|
||||
module.exports = WebSocketFrame;
|
||||
+532
@@ -0,0 +1,532 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var crypto = require('crypto');
|
||||
var util = require('util');
|
||||
var url = require('url');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var WebSocketConnection = require('./WebSocketConnection');
|
||||
|
||||
var headerValueSplitRegExp = /,\s*/;
|
||||
var headerParamSplitRegExp = /;\s*/;
|
||||
var headerSanitizeRegExp = /[\r\n]/g;
|
||||
var xForwardedForSeparatorRegExp = /,\s*/;
|
||||
var separators = [
|
||||
'(', ')', '<', '>', '@',
|
||||
',', ';', ':', '\\', '\"',
|
||||
'/', '[', ']', '?', '=',
|
||||
'{', '}', ' ', String.fromCharCode(9)
|
||||
];
|
||||
var controlChars = [String.fromCharCode(127) /* DEL */];
|
||||
for (var i=0; i < 31; i ++) {
|
||||
/* US-ASCII Control Characters */
|
||||
controlChars.push(String.fromCharCode(i));
|
||||
}
|
||||
|
||||
var cookieNameValidateRegEx = /([\x00-\x20\x22\x28\x29\x2c\x2f\x3a-\x3f\x40\x5b-\x5e\x7b\x7d\x7f])/;
|
||||
var cookieValueValidateRegEx = /[^\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]/;
|
||||
var cookieValueDQuoteValidateRegEx = /^"[^"]*"$/;
|
||||
var controlCharsAndSemicolonRegEx = /[\x00-\x20\x3b]/g;
|
||||
|
||||
var cookieSeparatorRegEx = /[;,] */;
|
||||
|
||||
var httpStatusDescriptions = {
|
||||
100: 'Continue',
|
||||
101: 'Switching Protocols',
|
||||
200: 'OK',
|
||||
201: 'Created',
|
||||
203: 'Non-Authoritative Information',
|
||||
204: 'No Content',
|
||||
205: 'Reset Content',
|
||||
206: 'Partial Content',
|
||||
300: 'Multiple Choices',
|
||||
301: 'Moved Permanently',
|
||||
302: 'Found',
|
||||
303: 'See Other',
|
||||
304: 'Not Modified',
|
||||
305: 'Use Proxy',
|
||||
307: 'Temporary Redirect',
|
||||
400: 'Bad Request',
|
||||
401: 'Unauthorized',
|
||||
402: 'Payment Required',
|
||||
403: 'Forbidden',
|
||||
404: 'Not Found',
|
||||
406: 'Not Acceptable',
|
||||
407: 'Proxy Authorization Required',
|
||||
408: 'Request Timeout',
|
||||
409: 'Conflict',
|
||||
410: 'Gone',
|
||||
411: 'Length Required',
|
||||
412: 'Precondition Failed',
|
||||
413: 'Request Entity Too Long',
|
||||
414: 'Request-URI Too Long',
|
||||
415: 'Unsupported Media Type',
|
||||
416: 'Requested Range Not Satisfiable',
|
||||
417: 'Expectation Failed',
|
||||
426: 'Upgrade Required',
|
||||
500: 'Internal Server Error',
|
||||
501: 'Not Implemented',
|
||||
502: 'Bad Gateway',
|
||||
503: 'Service Unavailable',
|
||||
504: 'Gateway Timeout',
|
||||
505: 'HTTP Version Not Supported'
|
||||
};
|
||||
|
||||
function WebSocketRequest(socket, httpRequest, serverConfig) {
|
||||
// Superclass Constructor
|
||||
EventEmitter.call(this);
|
||||
|
||||
this.socket = socket;
|
||||
this.httpRequest = httpRequest;
|
||||
this.resource = httpRequest.url;
|
||||
this.remoteAddress = socket.remoteAddress;
|
||||
this.remoteAddresses = [this.remoteAddress];
|
||||
this.serverConfig = serverConfig;
|
||||
|
||||
// Watch for the underlying TCP socket closing before we call accept
|
||||
this._socketIsClosing = false;
|
||||
this._socketCloseHandler = this._handleSocketCloseBeforeAccept.bind(this);
|
||||
this.socket.on('end', this._socketCloseHandler);
|
||||
this.socket.on('close', this._socketCloseHandler);
|
||||
|
||||
this._resolved = false;
|
||||
}
|
||||
|
||||
util.inherits(WebSocketRequest, EventEmitter);
|
||||
|
||||
WebSocketRequest.prototype.readHandshake = function() {
|
||||
var self = this;
|
||||
var request = this.httpRequest;
|
||||
|
||||
// Decode URL
|
||||
this.resourceURL = url.parse(this.resource, true);
|
||||
|
||||
this.host = request.headers['host'];
|
||||
if (!this.host) {
|
||||
throw new Error('Client must provide a Host header.');
|
||||
}
|
||||
|
||||
this.key = request.headers['sec-websocket-key'];
|
||||
if (!this.key) {
|
||||
throw new Error('Client must provide a value for Sec-WebSocket-Key.');
|
||||
}
|
||||
|
||||
this.webSocketVersion = parseInt(request.headers['sec-websocket-version'], 10);
|
||||
|
||||
if (!this.webSocketVersion || isNaN(this.webSocketVersion)) {
|
||||
throw new Error('Client must provide a value for Sec-WebSocket-Version.');
|
||||
}
|
||||
|
||||
switch (this.webSocketVersion) {
|
||||
case 8:
|
||||
case 13:
|
||||
break;
|
||||
default:
|
||||
var e = new Error('Unsupported websocket client version: ' + this.webSocketVersion +
|
||||
'Only versions 8 and 13 are supported.');
|
||||
e.httpCode = 426;
|
||||
e.headers = {
|
||||
'Sec-WebSocket-Version': '13'
|
||||
};
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (this.webSocketVersion === 13) {
|
||||
this.origin = request.headers['origin'];
|
||||
}
|
||||
else if (this.webSocketVersion === 8) {
|
||||
this.origin = request.headers['sec-websocket-origin'];
|
||||
}
|
||||
|
||||
// Protocol is optional.
|
||||
var protocolString = request.headers['sec-websocket-protocol'];
|
||||
this.protocolFullCaseMap = {};
|
||||
this.requestedProtocols = [];
|
||||
if (protocolString) {
|
||||
var requestedProtocolsFullCase = protocolString.split(headerValueSplitRegExp);
|
||||
requestedProtocolsFullCase.forEach(function(protocol) {
|
||||
var lcProtocol = protocol.toLocaleLowerCase();
|
||||
self.requestedProtocols.push(lcProtocol);
|
||||
self.protocolFullCaseMap[lcProtocol] = protocol;
|
||||
});
|
||||
}
|
||||
|
||||
if (!this.serverConfig.ignoreXForwardedFor &&
|
||||
request.headers['x-forwarded-for']) {
|
||||
var immediatePeerIP = this.remoteAddress;
|
||||
this.remoteAddresses = request.headers['x-forwarded-for']
|
||||
.split(xForwardedForSeparatorRegExp);
|
||||
this.remoteAddresses.push(immediatePeerIP);
|
||||
this.remoteAddress = this.remoteAddresses[0];
|
||||
}
|
||||
|
||||
// Extensions are optional.
|
||||
if (this.serverConfig.parseExtensions) {
|
||||
var extensionsString = request.headers['sec-websocket-extensions'];
|
||||
this.requestedExtensions = this.parseExtensions(extensionsString);
|
||||
} else {
|
||||
this.requestedExtensions = [];
|
||||
}
|
||||
|
||||
// Cookies are optional
|
||||
if (this.serverConfig.parseCookies) {
|
||||
var cookieString = request.headers['cookie'];
|
||||
this.cookies = this.parseCookies(cookieString);
|
||||
} else {
|
||||
this.cookies = [];
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketRequest.prototype.parseExtensions = function(extensionsString) {
|
||||
if (!extensionsString || extensionsString.length === 0) {
|
||||
return [];
|
||||
}
|
||||
var extensions = extensionsString.toLocaleLowerCase().split(headerValueSplitRegExp);
|
||||
extensions.forEach(function(extension, index, array) {
|
||||
var params = extension.split(headerParamSplitRegExp);
|
||||
var extensionName = params[0];
|
||||
var extensionParams = params.slice(1);
|
||||
extensionParams.forEach(function(rawParam, index, array) {
|
||||
var arr = rawParam.split('=');
|
||||
var obj = {
|
||||
name: arr[0],
|
||||
value: arr[1]
|
||||
};
|
||||
array.splice(index, 1, obj);
|
||||
});
|
||||
var obj = {
|
||||
name: extensionName,
|
||||
params: extensionParams
|
||||
};
|
||||
array.splice(index, 1, obj);
|
||||
});
|
||||
return extensions;
|
||||
};
|
||||
|
||||
// This function adapted from node-cookie
|
||||
// https://github.com/shtylman/node-cookie
|
||||
WebSocketRequest.prototype.parseCookies = function(str) {
|
||||
// Sanity Check
|
||||
if (!str || typeof(str) !== 'string') {
|
||||
return [];
|
||||
}
|
||||
|
||||
var cookies = [];
|
||||
var pairs = str.split(cookieSeparatorRegEx);
|
||||
|
||||
pairs.forEach(function(pair) {
|
||||
var eq_idx = pair.indexOf('=');
|
||||
if (eq_idx === -1) {
|
||||
cookies.push({
|
||||
name: pair,
|
||||
value: null
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var key = pair.substr(0, eq_idx).trim();
|
||||
var val = pair.substr(++eq_idx, pair.length).trim();
|
||||
|
||||
// quoted values
|
||||
if ('"' === val[0]) {
|
||||
val = val.slice(1, -1);
|
||||
}
|
||||
|
||||
cookies.push({
|
||||
name: key,
|
||||
value: decodeURIComponent(val)
|
||||
});
|
||||
});
|
||||
|
||||
return cookies;
|
||||
};
|
||||
|
||||
WebSocketRequest.prototype.accept = function(acceptedProtocol, allowedOrigin, cookies) {
|
||||
this._verifyResolution();
|
||||
|
||||
// TODO: Handle extensions
|
||||
|
||||
var protocolFullCase;
|
||||
|
||||
if (acceptedProtocol) {
|
||||
protocolFullCase = this.protocolFullCaseMap[acceptedProtocol.toLocaleLowerCase()];
|
||||
if (typeof(protocolFullCase) === 'undefined') {
|
||||
protocolFullCase = acceptedProtocol;
|
||||
}
|
||||
}
|
||||
else {
|
||||
protocolFullCase = acceptedProtocol;
|
||||
}
|
||||
this.protocolFullCaseMap = null;
|
||||
|
||||
// Create key validation hash
|
||||
var sha1 = crypto.createHash('sha1');
|
||||
sha1.update(this.key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
|
||||
var acceptKey = sha1.digest('base64');
|
||||
|
||||
var response = 'HTTP/1.1 101 Switching Protocols\r\n' +
|
||||
'Upgrade: websocket\r\n' +
|
||||
'Connection: Upgrade\r\n' +
|
||||
'Sec-WebSocket-Accept: ' + acceptKey + '\r\n';
|
||||
|
||||
if (protocolFullCase) {
|
||||
// validate protocol
|
||||
for (var i=0; i < protocolFullCase.length; i++) {
|
||||
var charCode = protocolFullCase.charCodeAt(i);
|
||||
var character = protocolFullCase.charAt(i);
|
||||
if (charCode < 0x21 || charCode > 0x7E || separators.indexOf(character) !== -1) {
|
||||
this.reject(500);
|
||||
throw new Error('Illegal character "' + String.fromCharCode(character) + '" in subprotocol.');
|
||||
}
|
||||
}
|
||||
if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) {
|
||||
this.reject(500);
|
||||
throw new Error('Specified protocol was not requested by the client.');
|
||||
}
|
||||
|
||||
protocolFullCase = protocolFullCase.replace(headerSanitizeRegExp, '');
|
||||
response += 'Sec-WebSocket-Protocol: ' + protocolFullCase + '\r\n';
|
||||
}
|
||||
this.requestedProtocols = null;
|
||||
|
||||
if (allowedOrigin) {
|
||||
allowedOrigin = allowedOrigin.replace(headerSanitizeRegExp, '');
|
||||
if (this.webSocketVersion === 13) {
|
||||
response += 'Origin: ' + allowedOrigin + '\r\n';
|
||||
}
|
||||
else if (this.webSocketVersion === 8) {
|
||||
response += 'Sec-WebSocket-Origin: ' + allowedOrigin + '\r\n';
|
||||
}
|
||||
}
|
||||
|
||||
if (cookies) {
|
||||
if (!Array.isArray(cookies)) {
|
||||
this.reject(500);
|
||||
throw new Error('Value supplied for "cookies" argument must be an array.');
|
||||
}
|
||||
var seenCookies = {};
|
||||
cookies.forEach(function(cookie) {
|
||||
if (!cookie.name || !cookie.value) {
|
||||
this.reject(500);
|
||||
throw new Error('Each cookie to set must at least provide a "name" and "value"');
|
||||
}
|
||||
|
||||
// Make sure there are no \r\n sequences inserted
|
||||
cookie.name = cookie.name.replace(controlCharsAndSemicolonRegEx, '');
|
||||
cookie.value = cookie.value.replace(controlCharsAndSemicolonRegEx, '');
|
||||
|
||||
if (seenCookies[cookie.name]) {
|
||||
this.reject(500);
|
||||
throw new Error('You may not specify the same cookie name twice.');
|
||||
}
|
||||
seenCookies[cookie.name] = true;
|
||||
|
||||
// token (RFC 2616, Section 2.2)
|
||||
var invalidChar = cookie.name.match(cookieNameValidateRegEx);
|
||||
if (invalidChar) {
|
||||
this.reject(500);
|
||||
throw new Error('Illegal character ' + invalidChar[0] + ' in cookie name');
|
||||
}
|
||||
|
||||
// RFC 6265, Section 4.1.1
|
||||
// *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) | %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
|
||||
if (cookie.value.match(cookieValueDQuoteValidateRegEx)) {
|
||||
invalidChar = cookie.value.slice(1, -1).match(cookieValueValidateRegEx);
|
||||
} else {
|
||||
invalidChar = cookie.value.match(cookieValueValidateRegEx);
|
||||
}
|
||||
if (invalidChar) {
|
||||
this.reject(500);
|
||||
throw new Error('Illegal character ' + invalidChar[0] + ' in cookie value');
|
||||
}
|
||||
|
||||
var cookieParts = [cookie.name + '=' + cookie.value];
|
||||
|
||||
// RFC 6265, Section 4.1.1
|
||||
// 'Path=' path-value | <any CHAR except CTLs or ';'>
|
||||
if(cookie.path){
|
||||
invalidChar = cookie.path.match(controlCharsAndSemicolonRegEx);
|
||||
if (invalidChar) {
|
||||
this.reject(500);
|
||||
throw new Error('Illegal character ' + invalidChar[0] + ' in cookie path');
|
||||
}
|
||||
cookieParts.push('Path=' + cookie.path);
|
||||
}
|
||||
|
||||
// RFC 6265, Section 4.1.2.3
|
||||
// 'Domain=' subdomain
|
||||
if (cookie.domain) {
|
||||
if (typeof(cookie.domain) !== 'string') {
|
||||
this.reject(500);
|
||||
throw new Error('Domain must be specified and must be a string.');
|
||||
}
|
||||
invalidChar = cookie.domain.match(controlCharsAndSemicolonRegEx);
|
||||
if (invalidChar) {
|
||||
this.reject(500);
|
||||
throw new Error('Illegal character ' + invalidChar[0] + ' in cookie domain');
|
||||
}
|
||||
cookieParts.push('Domain=' + cookie.domain.toLowerCase());
|
||||
}
|
||||
|
||||
// RFC 6265, Section 4.1.1
|
||||
//'Expires=' sane-cookie-date | Force Date object requirement by using only epoch
|
||||
if (cookie.expires) {
|
||||
if (!(cookie.expires instanceof Date)){
|
||||
this.reject(500);
|
||||
throw new Error('Value supplied for cookie "expires" must be a vaild date object');
|
||||
}
|
||||
cookieParts.push('Expires=' + cookie.expires.toGMTString());
|
||||
}
|
||||
|
||||
// RFC 6265, Section 4.1.1
|
||||
//'Max-Age=' non-zero-digit *DIGIT
|
||||
if (cookie.maxage) {
|
||||
var maxage = cookie.maxage;
|
||||
if (typeof(maxage) === 'string') {
|
||||
maxage = parseInt(maxage, 10);
|
||||
}
|
||||
if (isNaN(maxage) || maxage <= 0 ) {
|
||||
this.reject(500);
|
||||
throw new Error('Value supplied for cookie "maxage" must be a non-zero number');
|
||||
}
|
||||
maxage = Math.round(maxage);
|
||||
cookieParts.push('Max-Age=' + maxage.toString(10));
|
||||
}
|
||||
|
||||
// RFC 6265, Section 4.1.1
|
||||
//'Secure;'
|
||||
if (cookie.secure) {
|
||||
if (typeof(cookie.secure) !== 'boolean') {
|
||||
this.reject(500);
|
||||
throw new Error('Value supplied for cookie "secure" must be of type boolean');
|
||||
}
|
||||
cookieParts.push('Secure');
|
||||
}
|
||||
|
||||
// RFC 6265, Section 4.1.1
|
||||
//'HttpOnly;'
|
||||
if (cookie.httponly) {
|
||||
if (typeof(cookie.httponly) !== 'boolean') {
|
||||
this.reject(500);
|
||||
throw new Error('Value supplied for cookie "httponly" must be of type boolean');
|
||||
}
|
||||
cookieParts.push('HttpOnly');
|
||||
}
|
||||
|
||||
response += ('Set-Cookie: ' + cookieParts.join(';') + '\r\n');
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
// TODO: handle negotiated extensions
|
||||
// if (negotiatedExtensions) {
|
||||
// response += 'Sec-WebSocket-Extensions: ' + negotiatedExtensions.join(', ') + '\r\n';
|
||||
// }
|
||||
|
||||
// Mark the request resolved now so that the user can't call accept or
|
||||
// reject a second time.
|
||||
this._resolved = true;
|
||||
this.emit('requestResolved', this);
|
||||
|
||||
response += '\r\n';
|
||||
|
||||
var connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig);
|
||||
connection.webSocketVersion = this.webSocketVersion;
|
||||
connection.remoteAddress = this.remoteAddress;
|
||||
connection.remoteAddresses = this.remoteAddresses;
|
||||
|
||||
var self = this;
|
||||
|
||||
if (this._socketIsClosing) {
|
||||
// Handle case when the client hangs up before we get a chance to
|
||||
// accept the connection and send our side of the opening handshake.
|
||||
cleanupFailedConnection(connection);
|
||||
}
|
||||
else {
|
||||
this.socket.write(response, 'ascii', function(error) {
|
||||
if (error) {
|
||||
cleanupFailedConnection(connection);
|
||||
return;
|
||||
}
|
||||
|
||||
self._removeSocketCloseListeners();
|
||||
connection._addSocketEventListeners();
|
||||
});
|
||||
}
|
||||
|
||||
this.emit('requestAccepted', connection);
|
||||
return connection;
|
||||
};
|
||||
|
||||
WebSocketRequest.prototype.reject = function(status, reason, extraHeaders) {
|
||||
this._verifyResolution();
|
||||
|
||||
// Mark the request resolved now so that the user can't call accept or
|
||||
// reject a second time.
|
||||
this._resolved = true;
|
||||
this.emit('requestResolved', this);
|
||||
|
||||
if (typeof(status) !== 'number') {
|
||||
status = 403;
|
||||
}
|
||||
var response = 'HTTP/1.1 ' + status + ' ' + httpStatusDescriptions[status] + '\r\n' +
|
||||
'Connection: close\r\n';
|
||||
if (reason) {
|
||||
reason = reason.replace(headerSanitizeRegExp, '');
|
||||
response += 'X-WebSocket-Reject-Reason: ' + reason + '\r\n';
|
||||
}
|
||||
|
||||
if (extraHeaders) {
|
||||
for (var key in extraHeaders) {
|
||||
var sanitizedValue = extraHeaders[key].toString().replace(headerSanitizeRegExp, '');
|
||||
var sanitizedKey = key.replace(headerSanitizeRegExp, '');
|
||||
response += (sanitizedKey + ': ' + sanitizedValue + '\r\n');
|
||||
}
|
||||
}
|
||||
|
||||
response += '\r\n';
|
||||
this.socket.end(response, 'ascii');
|
||||
|
||||
this.emit('requestRejected', this);
|
||||
};
|
||||
|
||||
WebSocketRequest.prototype._handleSocketCloseBeforeAccept = function() {
|
||||
this._socketIsClosing = true;
|
||||
this._removeSocketCloseListeners();
|
||||
};
|
||||
|
||||
WebSocketRequest.prototype._removeSocketCloseListeners = function() {
|
||||
this.socket.removeListener('end', this._socketCloseHandler);
|
||||
this.socket.removeListener('close', this._socketCloseHandler);
|
||||
};
|
||||
|
||||
WebSocketRequest.prototype._verifyResolution = function() {
|
||||
if (this._resolved) {
|
||||
throw new Error('WebSocketRequest may only be accepted or rejected one time.');
|
||||
}
|
||||
};
|
||||
|
||||
function cleanupFailedConnection(connection) {
|
||||
// Since we have to return a connection object even if the socket is
|
||||
// already dead in order not to break the API, we schedule a 'close'
|
||||
// event on the connection object to occur immediately.
|
||||
process.nextTick(function() {
|
||||
// WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006
|
||||
// Third param: Skip sending the close frame to a dead socket
|
||||
connection.drop(1006, 'TCP connection lost before handshake completed.', true);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = WebSocketRequest;
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var extend = require('./utils').extend;
|
||||
var util = require('util');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var WebSocketRouterRequest = require('./WebSocketRouterRequest');
|
||||
|
||||
function WebSocketRouter(config) {
|
||||
// Superclass Constructor
|
||||
EventEmitter.call(this);
|
||||
|
||||
this.config = {
|
||||
// The WebSocketServer instance to attach to.
|
||||
server: null
|
||||
};
|
||||
if (config) {
|
||||
extend(this.config, config);
|
||||
}
|
||||
this.handlers = [];
|
||||
|
||||
this._requestHandler = this.handleRequest.bind(this);
|
||||
if (this.config.server) {
|
||||
this.attachServer(this.config.server);
|
||||
}
|
||||
}
|
||||
|
||||
util.inherits(WebSocketRouter, EventEmitter);
|
||||
|
||||
WebSocketRouter.prototype.attachServer = function(server) {
|
||||
if (server) {
|
||||
this.server = server;
|
||||
this.server.on('request', this._requestHandler);
|
||||
}
|
||||
else {
|
||||
throw new Error('You must specify a WebSocketServer instance to attach to.');
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketRouter.prototype.detachServer = function() {
|
||||
if (this.server) {
|
||||
this.server.removeListener('request', this._requestHandler);
|
||||
this.server = null;
|
||||
}
|
||||
else {
|
||||
throw new Error('Cannot detach from server: not attached.');
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketRouter.prototype.mount = function(path, protocol, callback) {
|
||||
if (!path) {
|
||||
throw new Error('You must specify a path for this handler.');
|
||||
}
|
||||
if (!protocol) {
|
||||
protocol = '____no_protocol____';
|
||||
}
|
||||
if (!callback) {
|
||||
throw new Error('You must specify a callback for this handler.');
|
||||
}
|
||||
|
||||
path = this.pathToRegExp(path);
|
||||
if (!(path instanceof RegExp)) {
|
||||
throw new Error('Path must be specified as either a string or a RegExp.');
|
||||
}
|
||||
var pathString = path.toString();
|
||||
|
||||
// normalize protocol to lower-case
|
||||
protocol = protocol.toLocaleLowerCase();
|
||||
|
||||
if (this.findHandlerIndex(pathString, protocol) !== -1) {
|
||||
throw new Error('You may only mount one handler per path/protocol combination.');
|
||||
}
|
||||
|
||||
this.handlers.push({
|
||||
'path': path,
|
||||
'pathString': pathString,
|
||||
'protocol': protocol,
|
||||
'callback': callback
|
||||
});
|
||||
};
|
||||
WebSocketRouter.prototype.unmount = function(path, protocol) {
|
||||
var index = this.findHandlerIndex(this.pathToRegExp(path).toString(), protocol);
|
||||
if (index !== -1) {
|
||||
this.handlers.splice(index, 1);
|
||||
}
|
||||
else {
|
||||
throw new Error('Unable to find a route matching the specified path and protocol.');
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketRouter.prototype.findHandlerIndex = function(pathString, protocol) {
|
||||
protocol = protocol.toLocaleLowerCase();
|
||||
for (var i=0, len=this.handlers.length; i < len; i++) {
|
||||
var handler = this.handlers[i];
|
||||
if (handler.pathString === pathString && handler.protocol === protocol) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
|
||||
WebSocketRouter.prototype.pathToRegExp = function(path) {
|
||||
if (typeof(path) === 'string') {
|
||||
if (path === '*') {
|
||||
path = /^.*$/;
|
||||
}
|
||||
else {
|
||||
path = path.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
|
||||
path = new RegExp('^' + path + '$');
|
||||
}
|
||||
}
|
||||
return path;
|
||||
};
|
||||
|
||||
WebSocketRouter.prototype.handleRequest = function(request) {
|
||||
var requestedProtocols = request.requestedProtocols;
|
||||
if (requestedProtocols.length === 0) {
|
||||
requestedProtocols = ['____no_protocol____'];
|
||||
}
|
||||
|
||||
// Find a handler with the first requested protocol first
|
||||
for (var i=0; i < requestedProtocols.length; i++) {
|
||||
var requestedProtocol = requestedProtocols[i].toLocaleLowerCase();
|
||||
|
||||
// find the first handler that can process this request
|
||||
for (var j=0, len=this.handlers.length; j < len; j++) {
|
||||
var handler = this.handlers[j];
|
||||
if (handler.path.test(request.resourceURL.pathname)) {
|
||||
if (requestedProtocol === handler.protocol ||
|
||||
handler.protocol === '*')
|
||||
{
|
||||
var routerRequest = new WebSocketRouterRequest(request, requestedProtocol);
|
||||
handler.callback(routerRequest);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here we were unable to find a suitable handler.
|
||||
request.reject(404, 'No handler is available for the given request.');
|
||||
};
|
||||
|
||||
module.exports = WebSocketRouter;
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var util = require('util');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
|
||||
function WebSocketRouterRequest(webSocketRequest, resolvedProtocol) {
|
||||
// Superclass Constructor
|
||||
EventEmitter.call(this);
|
||||
|
||||
this.webSocketRequest = webSocketRequest;
|
||||
if (resolvedProtocol === '____no_protocol____') {
|
||||
this.protocol = null;
|
||||
}
|
||||
else {
|
||||
this.protocol = resolvedProtocol;
|
||||
}
|
||||
this.origin = webSocketRequest.origin;
|
||||
this.resource = webSocketRequest.resource;
|
||||
this.resourceURL = webSocketRequest.resourceURL;
|
||||
this.httpRequest = webSocketRequest.httpRequest;
|
||||
this.remoteAddress = webSocketRequest.remoteAddress;
|
||||
this.webSocketVersion = webSocketRequest.webSocketVersion;
|
||||
this.requestedExtensions = webSocketRequest.requestedExtensions;
|
||||
this.cookies = webSocketRequest.cookies;
|
||||
}
|
||||
|
||||
util.inherits(WebSocketRouterRequest, EventEmitter);
|
||||
|
||||
WebSocketRouterRequest.prototype.accept = function(origin, cookies) {
|
||||
var connection = this.webSocketRequest.accept(this.protocol, origin, cookies);
|
||||
this.emit('requestAccepted', connection);
|
||||
return connection;
|
||||
};
|
||||
|
||||
WebSocketRouterRequest.prototype.reject = function(status, reason, extraHeaders) {
|
||||
this.webSocketRequest.reject(status, reason, extraHeaders);
|
||||
this.emit('requestRejected', this);
|
||||
};
|
||||
|
||||
module.exports = WebSocketRouterRequest;
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
/************************************************************************
|
||||
* Copyright 2010-2015 Brian McKelvey.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
***********************************************************************/
|
||||
|
||||
var extend = require('./utils').extend;
|
||||
var utils = require('./utils');
|
||||
var util = require('util');
|
||||
var debug = require('debug')('websocket:server');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var WebSocketRequest = require('./WebSocketRequest');
|
||||
|
||||
var WebSocketServer = function WebSocketServer(config) {
|
||||
// Superclass Constructor
|
||||
EventEmitter.call(this);
|
||||
|
||||
this._handlers = {
|
||||
upgrade: this.handleUpgrade.bind(this),
|
||||
requestAccepted: this.handleRequestAccepted.bind(this),
|
||||
requestResolved: this.handleRequestResolved.bind(this)
|
||||
};
|
||||
this.connections = [];
|
||||
this.pendingRequests = [];
|
||||
if (config) {
|
||||
this.mount(config);
|
||||
}
|
||||
};
|
||||
|
||||
util.inherits(WebSocketServer, EventEmitter);
|
||||
|
||||
WebSocketServer.prototype.mount = function(config) {
|
||||
this.config = {
|
||||
// The http server instance to attach to. Required.
|
||||
httpServer: null,
|
||||
|
||||
// 64KiB max frame size.
|
||||
maxReceivedFrameSize: 0x10000,
|
||||
|
||||
// 1MiB max message size, only applicable if
|
||||
// assembleFragments is true
|
||||
maxReceivedMessageSize: 0x100000,
|
||||
|
||||
// Outgoing messages larger than fragmentationThreshold will be
|
||||
// split into multiple fragments.
|
||||
fragmentOutgoingMessages: true,
|
||||
|
||||
// Outgoing frames are fragmented if they exceed this threshold.
|
||||
// Default is 16KiB
|
||||
fragmentationThreshold: 0x4000,
|
||||
|
||||
// If true, the server will automatically send a ping to all
|
||||
// clients every 'keepaliveInterval' milliseconds. The timer is
|
||||
// reset on any received data from the client.
|
||||
keepalive: true,
|
||||
|
||||
// The interval to send keepalive pings to connected clients if the
|
||||
// connection is idle. Any received data will reset the counter.
|
||||
keepaliveInterval: 20000,
|
||||
|
||||
// If true, the server will consider any connection that has not
|
||||
// received any data within the amount of time specified by
|
||||
// 'keepaliveGracePeriod' after a keepalive ping has been sent to
|
||||
// be dead, and will drop the connection.
|
||||
// Ignored if keepalive is false.
|
||||
dropConnectionOnKeepaliveTimeout: true,
|
||||
|
||||
// The amount of time to wait after sending a keepalive ping before
|
||||
// closing the connection if the connected peer does not respond.
|
||||
// Ignored if keepalive is false.
|
||||
keepaliveGracePeriod: 10000,
|
||||
|
||||
// Whether to use native TCP keep-alive instead of WebSockets ping
|
||||
// and pong packets. Native TCP keep-alive sends smaller packets
|
||||
// on the wire and so uses bandwidth more efficiently. This may
|
||||
// be more important when talking to mobile devices.
|
||||
// If this value is set to true, then these values will be ignored:
|
||||
// keepaliveGracePeriod
|
||||
// dropConnectionOnKeepaliveTimeout
|
||||
useNativeKeepalive: false,
|
||||
|
||||
// If true, fragmented messages will be automatically assembled
|
||||
// and the full message will be emitted via a 'message' event.
|
||||
// If false, each frame will be emitted via a 'frame' event and
|
||||
// the application will be responsible for aggregating multiple
|
||||
// fragmented frames. Single-frame messages will emit a 'message'
|
||||
// event in addition to the 'frame' event.
|
||||
// Most users will want to leave this set to 'true'
|
||||
assembleFragments: true,
|
||||
|
||||
// If this is true, websocket connections will be accepted
|
||||
// regardless of the path and protocol specified by the client.
|
||||
// The protocol accepted will be the first that was requested
|
||||
// by the client. Clients from any origin will be accepted.
|
||||
// This should only be used in the simplest of cases. You should
|
||||
// probably leave this set to 'false' and inspect the request
|
||||
// object to make sure it's acceptable before accepting it.
|
||||
autoAcceptConnections: false,
|
||||
|
||||
// Whether or not the X-Forwarded-For header should be respected.
|
||||
// It's important to set this to 'true' when accepting connections
|
||||
// from untrusted clients, as a malicious client could spoof its
|
||||
// IP address by simply setting this header. It's meant to be added
|
||||
// by a trusted proxy or other intermediary within your own
|
||||
// infrastructure.
|
||||
// See: http://en.wikipedia.org/wiki/X-Forwarded-For
|
||||
ignoreXForwardedFor: false,
|
||||
|
||||
// If this is true, 'cookie' headers are parsed and exposed as WebSocketRequest.cookies
|
||||
parseCookies: true,
|
||||
|
||||
// If this is true, 'sec-websocket-extensions' headers are parsed and exposed as WebSocketRequest.requestedExtensions
|
||||
parseExtensions: true,
|
||||
|
||||
// The Nagle Algorithm makes more efficient use of network resources
|
||||
// by introducing a small delay before sending small packets so that
|
||||
// multiple messages can be batched together before going onto the
|
||||
// wire. This however comes at the cost of latency, so the default
|
||||
// is to disable it. If you don't need low latency and are streaming
|
||||
// lots of small messages, you can change this to 'false'
|
||||
disableNagleAlgorithm: true,
|
||||
|
||||
// The number of milliseconds to wait after sending a close frame
|
||||
// for an acknowledgement to come back before giving up and just
|
||||
// closing the socket.
|
||||
closeTimeout: 5000
|
||||
};
|
||||
extend(this.config, config);
|
||||
|
||||
if (this.config.httpServer) {
|
||||
if (!Array.isArray(this.config.httpServer)) {
|
||||
this.config.httpServer = [this.config.httpServer];
|
||||
}
|
||||
var upgradeHandler = this._handlers.upgrade;
|
||||
this.config.httpServer.forEach(function(httpServer) {
|
||||
httpServer.on('upgrade', upgradeHandler);
|
||||
});
|
||||
}
|
||||
else {
|
||||
throw new Error('You must specify an httpServer on which to mount the WebSocket server.');
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.unmount = function() {
|
||||
var upgradeHandler = this._handlers.upgrade;
|
||||
this.config.httpServer.forEach(function(httpServer) {
|
||||
httpServer.removeListener('upgrade', upgradeHandler);
|
||||
});
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.closeAllConnections = function() {
|
||||
this.connections.forEach(function(connection) {
|
||||
connection.close();
|
||||
});
|
||||
this.pendingRequests.forEach(function(request) {
|
||||
process.nextTick(function() {
|
||||
request.reject(503); // HTTP 503 Service Unavailable
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.broadcast = function(data) {
|
||||
if (Buffer.isBuffer(data)) {
|
||||
this.broadcastBytes(data);
|
||||
}
|
||||
else if (typeof(data.toString) === 'function') {
|
||||
this.broadcastUTF(data);
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.broadcastUTF = function(utfData) {
|
||||
this.connections.forEach(function(connection) {
|
||||
connection.sendUTF(utfData);
|
||||
});
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.broadcastBytes = function(binaryData) {
|
||||
this.connections.forEach(function(connection) {
|
||||
connection.sendBytes(binaryData);
|
||||
});
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.shutDown = function() {
|
||||
this.unmount();
|
||||
this.closeAllConnections();
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.handleUpgrade = function(request, socket) {
|
||||
var self = this;
|
||||
var wsRequest = new WebSocketRequest(socket, request, this.config);
|
||||
try {
|
||||
wsRequest.readHandshake();
|
||||
}
|
||||
catch(e) {
|
||||
wsRequest.reject(
|
||||
e.httpCode ? e.httpCode : 400,
|
||||
e.message,
|
||||
e.headers
|
||||
);
|
||||
debug('Invalid handshake: %s', e.message);
|
||||
this.emit('upgradeError', e);
|
||||
return;
|
||||
}
|
||||
|
||||
this.pendingRequests.push(wsRequest);
|
||||
|
||||
wsRequest.once('requestAccepted', this._handlers.requestAccepted);
|
||||
wsRequest.once('requestResolved', this._handlers.requestResolved);
|
||||
socket.once('close', function () {
|
||||
self._handlers.requestResolved(wsRequest);
|
||||
});
|
||||
|
||||
if (!this.config.autoAcceptConnections && utils.eventEmitterListenerCount(this, 'request') > 0) {
|
||||
this.emit('request', wsRequest);
|
||||
}
|
||||
else if (this.config.autoAcceptConnections) {
|
||||
wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin);
|
||||
}
|
||||
else {
|
||||
wsRequest.reject(404, 'No handler is configured to accept the connection.');
|
||||
}
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.handleRequestAccepted = function(connection) {
|
||||
var self = this;
|
||||
connection.once('close', function(closeReason, description) {
|
||||
self.handleConnectionClose(connection, closeReason, description);
|
||||
});
|
||||
this.connections.push(connection);
|
||||
this.emit('connect', connection);
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.handleConnectionClose = function(connection, closeReason, description) {
|
||||
var index = this.connections.indexOf(connection);
|
||||
if (index !== -1) {
|
||||
this.connections.splice(index, 1);
|
||||
}
|
||||
this.emit('close', connection, closeReason, description);
|
||||
};
|
||||
|
||||
WebSocketServer.prototype.handleRequestResolved = function(request) {
|
||||
var index = this.pendingRequests.indexOf(request);
|
||||
if (index !== -1) { this.pendingRequests.splice(index, 1); }
|
||||
};
|
||||
|
||||
module.exports = WebSocketServer;
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
var _globalThis;
|
||||
if (typeof globalThis === 'object') {
|
||||
_globalThis = globalThis;
|
||||
} else {
|
||||
try {
|
||||
_globalThis = require('es5-ext/global');
|
||||
} catch (error) {
|
||||
} finally {
|
||||
if (!_globalThis && typeof window !== 'undefined') { _globalThis = window; }
|
||||
if (!_globalThis) { throw new Error('Could not determine global this'); }
|
||||
}
|
||||
}
|
||||
|
||||
var NativeWebSocket = _globalThis.WebSocket || _globalThis.MozWebSocket;
|
||||
var websocket_version = require('./version');
|
||||
|
||||
|
||||
/**
|
||||
* Expose a W3C WebSocket class with just one or two arguments.
|
||||
*/
|
||||
function W3CWebSocket(uri, protocols) {
|
||||
var native_instance;
|
||||
|
||||
if (protocols) {
|
||||
native_instance = new NativeWebSocket(uri, protocols);
|
||||
}
|
||||
else {
|
||||
native_instance = new NativeWebSocket(uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket
|
||||
* class). Since it is an Object it will be returned as it is when creating an
|
||||
* instance of W3CWebSocket via 'new W3CWebSocket()'.
|
||||
*
|
||||
* ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2
|
||||
*/
|
||||
return native_instance;
|
||||
}
|
||||
if (NativeWebSocket) {
|
||||
['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {
|
||||
Object.defineProperty(W3CWebSocket, prop, {
|
||||
get: function() { return NativeWebSocket[prop]; }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
module.exports = {
|
||||
'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,
|
||||
'version' : websocket_version
|
||||
};
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
var noop = exports.noop = function(){};
|
||||
|
||||
exports.extend = function extend(dest, source) {
|
||||
for (var prop in source) {
|
||||
dest[prop] = source[prop];
|
||||
}
|
||||
};
|
||||
|
||||
exports.eventEmitterListenerCount =
|
||||
require('events').EventEmitter.listenerCount ||
|
||||
function(emitter, type) { return emitter.listeners(type).length; };
|
||||
|
||||
exports.bufferAllocUnsafe = Buffer.allocUnsafe ?
|
||||
Buffer.allocUnsafe :
|
||||
function oldBufferAllocUnsafe(size) { return new Buffer(size); };
|
||||
|
||||
exports.bufferFromString = Buffer.from ?
|
||||
Buffer.from :
|
||||
function oldBufferFromString(string, encoding) {
|
||||
return new Buffer(string, encoding);
|
||||
};
|
||||
|
||||
exports.BufferingLogger = function createBufferingLogger(identifier, uniqueID) {
|
||||
var logFunction = require('debug')(identifier);
|
||||
if (logFunction.enabled) {
|
||||
var logger = new BufferingLogger(identifier, uniqueID, logFunction);
|
||||
var debug = logger.log.bind(logger);
|
||||
debug.printOutput = logger.printOutput.bind(logger);
|
||||
debug.enabled = logFunction.enabled;
|
||||
return debug;
|
||||
}
|
||||
logFunction.printOutput = noop;
|
||||
return logFunction;
|
||||
};
|
||||
|
||||
function BufferingLogger(identifier, uniqueID, logFunction) {
|
||||
this.logFunction = logFunction;
|
||||
this.identifier = identifier;
|
||||
this.uniqueID = uniqueID;
|
||||
this.buffer = [];
|
||||
}
|
||||
|
||||
BufferingLogger.prototype.log = function() {
|
||||
this.buffer.push([ new Date(), Array.prototype.slice.call(arguments) ]);
|
||||
return this;
|
||||
};
|
||||
|
||||
BufferingLogger.prototype.clear = function() {
|
||||
this.buffer = [];
|
||||
return this;
|
||||
};
|
||||
|
||||
BufferingLogger.prototype.printOutput = function(logFunction) {
|
||||
if (!logFunction) { logFunction = this.logFunction; }
|
||||
var uniqueID = this.uniqueID;
|
||||
this.buffer.forEach(function(entry) {
|
||||
var date = entry[0].toLocaleString();
|
||||
var args = entry[1].slice();
|
||||
var formatString = args[0];
|
||||
if (formatString !== (void 0) && formatString !== null) {
|
||||
formatString = '%s - %s - ' + formatString.toString();
|
||||
args.splice(0, 1, formatString, date, uniqueID);
|
||||
logFunction.apply(global, args);
|
||||
}
|
||||
});
|
||||
};
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require('../package.json').version;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
module.exports = {
|
||||
'server' : require('./WebSocketServer'),
|
||||
'client' : require('./WebSocketClient'),
|
||||
'router' : require('./WebSocketRouter'),
|
||||
'frame' : require('./WebSocketFrame'),
|
||||
'request' : require('./WebSocketRequest'),
|
||||
'connection' : require('./WebSocketConnection'),
|
||||
'w3cwebsocket' : require('./W3CWebSocket'),
|
||||
'deprecation' : require('./Deprecation'),
|
||||
'version' : require('./version')
|
||||
};
|
||||
+1
@@ -0,0 +1 @@
|
||||
repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"env": {
|
||||
"browser": true,
|
||||
"node": true
|
||||
},
|
||||
"rules": {
|
||||
"no-console": 0,
|
||||
"no-empty": [1, { "allowEmptyCatch": true }]
|
||||
},
|
||||
"extends": "eslint:recommended"
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
support
|
||||
test
|
||||
examples
|
||||
example
|
||||
*.sock
|
||||
dist
|
||||
yarn.lock
|
||||
coverage
|
||||
bower.json
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
|
||||
language: node_js
|
||||
node_js:
|
||||
- "6"
|
||||
- "5"
|
||||
- "4"
|
||||
|
||||
install:
|
||||
- make node_modules
|
||||
|
||||
script:
|
||||
- make lint
|
||||
- make test
|
||||
- make coveralls
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
|
||||
2.6.9 / 2017-09-22
|
||||
==================
|
||||
|
||||
* remove ReDoS regexp in %o formatter (#504)
|
||||
|
||||
2.6.8 / 2017-05-18
|
||||
==================
|
||||
|
||||
* Fix: Check for undefined on browser globals (#462, @marbemac)
|
||||
|
||||
2.6.7 / 2017-05-16
|
||||
==================
|
||||
|
||||
* Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom)
|
||||
* Fix: Inline extend function in node implementation (#452, @dougwilson)
|
||||
* Docs: Fix typo (#455, @msasad)
|
||||
|
||||
2.6.5 / 2017-04-27
|
||||
==================
|
||||
|
||||
* Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek)
|
||||
* Misc: clean up browser reference checks (#447, @thebigredgeek)
|
||||
* Misc: add npm-debug.log to .gitignore (@thebigredgeek)
|
||||
|
||||
|
||||
2.6.4 / 2017-04-20
|
||||
==================
|
||||
|
||||
* Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo)
|
||||
* Chore: ignore bower.json in npm installations. (#437, @joaovieira)
|
||||
* Misc: update "ms" to v0.7.3 (@tootallnate)
|
||||
|
||||
2.6.3 / 2017-03-13
|
||||
==================
|
||||
|
||||
* Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts)
|
||||
* Docs: Changelog fix (@thebigredgeek)
|
||||
|
||||
2.6.2 / 2017-03-10
|
||||
==================
|
||||
|
||||
* Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin)
|
||||
* Docs: Add backers and sponsors from Open Collective (#422, @piamancini)
|
||||
* Docs: Add Slackin invite badge (@tootallnate)
|
||||
|
||||
2.6.1 / 2017-02-10
|
||||
==================
|
||||
|
||||
* Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error
|
||||
* Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0)
|
||||
* Fix: IE8 "Expected identifier" error (#414, @vgoma)
|
||||
* Fix: Namespaces would not disable once enabled (#409, @musikov)
|
||||
|
||||
2.6.0 / 2016-12-28
|
||||
==================
|
||||
|
||||
* Fix: added better null pointer checks for browser useColors (@thebigredgeek)
|
||||
* Improvement: removed explicit `window.debug` export (#404, @tootallnate)
|
||||
* Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate)
|
||||
|
||||
2.5.2 / 2016-12-25
|
||||
==================
|
||||
|
||||
* Fix: reference error on window within webworkers (#393, @KlausTrainer)
|
||||
* Docs: fixed README typo (#391, @lurch)
|
||||
* Docs: added notice about v3 api discussion (@thebigredgeek)
|
||||
|
||||
2.5.1 / 2016-12-20
|
||||
==================
|
||||
|
||||
* Fix: babel-core compatibility
|
||||
|
||||
2.5.0 / 2016-12-20
|
||||
==================
|
||||
|
||||
* Fix: wrong reference in bower file (@thebigredgeek)
|
||||
* Fix: webworker compatibility (@thebigredgeek)
|
||||
* Fix: output formatting issue (#388, @kribblo)
|
||||
* Fix: babel-loader compatibility (#383, @escwald)
|
||||
* Misc: removed built asset from repo and publications (@thebigredgeek)
|
||||
* Misc: moved source files to /src (#378, @yamikuronue)
|
||||
* Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
|
||||
* Test: coveralls integration (#378, @yamikuronue)
|
||||
* Docs: simplified language in the opening paragraph (#373, @yamikuronue)
|
||||
|
||||
2.4.5 / 2016-12-17
|
||||
==================
|
||||
|
||||
* Fix: `navigator` undefined in Rhino (#376, @jochenberger)
|
||||
* Fix: custom log function (#379, @hsiliev)
|
||||
* Improvement: bit of cleanup + linting fixes (@thebigredgeek)
|
||||
* Improvement: rm non-maintainted `dist/` dir (#375, @freewil)
|
||||
* Docs: simplified language in the opening paragraph. (#373, @yamikuronue)
|
||||
|
||||
2.4.4 / 2016-12-14
|
||||
==================
|
||||
|
||||
* Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)
|
||||
|
||||
2.4.3 / 2016-12-14
|
||||
==================
|
||||
|
||||
* Fix: navigation.userAgent error for react native (#364, @escwald)
|
||||
|
||||
2.4.2 / 2016-12-14
|
||||
==================
|
||||
|
||||
* Fix: browser colors (#367, @tootallnate)
|
||||
* Misc: travis ci integration (@thebigredgeek)
|
||||
* Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)
|
||||
|
||||
2.4.1 / 2016-12-13
|
||||
==================
|
||||
|
||||
* Fix: typo that broke the package (#356)
|
||||
|
||||
2.4.0 / 2016-12-13
|
||||
==================
|
||||
|
||||
* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
|
||||
* Fix: revert "handle regex special characters" (@tootallnate)
|
||||
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
|
||||
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
|
||||
* Improvement: allow colors in workers (#335, @botverse)
|
||||
* Improvement: use same color for same namespace. (#338, @lchenay)
|
||||
|
||||
2.3.3 / 2016-11-09
|
||||
==================
|
||||
|
||||
* Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne)
|
||||
* Fix: Returning `localStorage` saved values (#331, Levi Thomason)
|
||||
* Improvement: Don't create an empty object when no `process` (Nathan Rajlich)
|
||||
|
||||
2.3.2 / 2016-11-09
|
||||
==================
|
||||
|
||||
* Fix: be super-safe in index.js as well (@TooTallNate)
|
||||
* Fix: should check whether process exists (Tom Newby)
|
||||
|
||||
2.3.1 / 2016-11-09
|
||||
==================
|
||||
|
||||
* Fix: Added electron compatibility (#324, @paulcbetts)
|
||||
* Improvement: Added performance optimizations (@tootallnate)
|
||||
* Readme: Corrected PowerShell environment variable example (#252, @gimre)
|
||||
* Misc: Removed yarn lock file from source control (#321, @fengmk2)
|
||||
|
||||
2.3.0 / 2016-11-07
|
||||
==================
|
||||
|
||||
* Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
|
||||
* Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
|
||||
* Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
|
||||
* Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
|
||||
* Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
|
||||
* Package: Update "ms" to 0.7.2 (#315, @DevSide)
|
||||
* Package: removed superfluous version property from bower.json (#207 @kkirsche)
|
||||
* Readme: fix USE_COLORS to DEBUG_COLORS
|
||||
* Readme: Doc fixes for format string sugar (#269, @mlucool)
|
||||
* Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
|
||||
* Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
|
||||
* Readme: better docs for browser support (#224, @matthewmueller)
|
||||
* Tooling: Added yarn integration for development (#317, @thebigredgeek)
|
||||
* Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
|
||||
* Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
|
||||
* Misc: Updated contributors (@thebigredgeek)
|
||||
|
||||
2.2.0 / 2015-05-09
|
||||
==================
|
||||
|
||||
* package: update "ms" to v0.7.1 (#202, @dougwilson)
|
||||
* README: add logging to file example (#193, @DanielOchoa)
|
||||
* README: fixed a typo (#191, @amir-s)
|
||||
* browser: expose `storage` (#190, @stephenmathieson)
|
||||
* Makefile: add a `distclean` target (#189, @stephenmathieson)
|
||||
|
||||
2.1.3 / 2015-03-13
|
||||
==================
|
||||
|
||||
* Updated stdout/stderr example (#186)
|
||||
* Updated example/stdout.js to match debug current behaviour
|
||||
* Renamed example/stderr.js to stdout.js
|
||||
* Update Readme.md (#184)
|
||||
* replace high intensity foreground color for bold (#182, #183)
|
||||
|
||||
2.1.2 / 2015-03-01
|
||||
==================
|
||||
|
||||
* dist: recompile
|
||||
* update "ms" to v0.7.0
|
||||
* package: update "browserify" to v9.0.3
|
||||
* component: fix "ms.js" repo location
|
||||
* changed bower package name
|
||||
* updated documentation about using debug in a browser
|
||||
* fix: security error on safari (#167, #168, @yields)
|
||||
|
||||
2.1.1 / 2014-12-29
|
||||
==================
|
||||
|
||||
* browser: use `typeof` to check for `console` existence
|
||||
* browser: check for `console.log` truthiness (fix IE 8/9)
|
||||
* browser: add support for Chrome apps
|
||||
* Readme: added Windows usage remarks
|
||||
* Add `bower.json` to properly support bower install
|
||||
|
||||
2.1.0 / 2014-10-15
|
||||
==================
|
||||
|
||||
* node: implement `DEBUG_FD` env variable support
|
||||
* package: update "browserify" to v6.1.0
|
||||
* package: add "license" field to package.json (#135, @panuhorsmalahti)
|
||||
|
||||
2.0.0 / 2014-09-01
|
||||
==================
|
||||
|
||||
* package: update "browserify" to v5.11.0
|
||||
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
|
||||
|
||||
1.0.4 / 2014-07-15
|
||||
==================
|
||||
|
||||
* dist: recompile
|
||||
* example: remove `console.info()` log usage
|
||||
* example: add "Content-Type" UTF-8 header to browser example
|
||||
* browser: place %c marker after the space character
|
||||
* browser: reset the "content" color via `color: inherit`
|
||||
* browser: add colors support for Firefox >= v31
|
||||
* debug: prefer an instance `log()` function over the global one (#119)
|
||||
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
|
||||
|
||||
1.0.3 / 2014-07-09
|
||||
==================
|
||||
|
||||
* Add support for multiple wildcards in namespaces (#122, @seegno)
|
||||
* browser: fix lint
|
||||
|
||||
1.0.2 / 2014-06-10
|
||||
==================
|
||||
|
||||
* browser: update color palette (#113, @gscottolson)
|
||||
* common: make console logging function configurable (#108, @timoxley)
|
||||
* node: fix %o colors on old node <= 0.8.x
|
||||
* Makefile: find node path using shell/which (#109, @timoxley)
|
||||
|
||||
1.0.1 / 2014-06-06
|
||||
==================
|
||||
|
||||
* browser: use `removeItem()` to clear localStorage
|
||||
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
|
||||
* package: add "contributors" section
|
||||
* node: fix comment typo
|
||||
* README: list authors
|
||||
|
||||
1.0.0 / 2014-06-04
|
||||
==================
|
||||
|
||||
* make ms diff be global, not be scope
|
||||
* debug: ignore empty strings in enable()
|
||||
* node: make DEBUG_COLORS able to disable coloring
|
||||
* *: export the `colors` array
|
||||
* npmignore: don't publish the `dist` dir
|
||||
* Makefile: refactor to use browserify
|
||||
* package: add "browserify" as a dev dependency
|
||||
* Readme: add Web Inspector Colors section
|
||||
* node: reset terminal color for the debug content
|
||||
* node: map "%o" to `util.inspect()`
|
||||
* browser: map "%j" to `JSON.stringify()`
|
||||
* debug: add custom "formatters"
|
||||
* debug: use "ms" module for humanizing the diff
|
||||
* Readme: add "bash" syntax highlighting
|
||||
* browser: add Firebug color support
|
||||
* browser: add colors for WebKit browsers
|
||||
* node: apply log to `console`
|
||||
* rewrite: abstract common logic for Node & browsers
|
||||
* add .jshintrc file
|
||||
|
||||
0.8.1 / 2014-04-14
|
||||
==================
|
||||
|
||||
* package: re-add the "component" section
|
||||
|
||||
0.8.0 / 2014-03-30
|
||||
==================
|
||||
|
||||
* add `enable()` method for nodejs. Closes #27
|
||||
* change from stderr to stdout
|
||||
* remove unnecessary index.js file
|
||||
|
||||
0.7.4 / 2013-11-13
|
||||
==================
|
||||
|
||||
* remove "browserify" key from package.json (fixes something in browserify)
|
||||
|
||||
0.7.3 / 2013-10-30
|
||||
==================
|
||||
|
||||
* fix: catch localStorage security error when cookies are blocked (Chrome)
|
||||
* add debug(err) support. Closes #46
|
||||
* add .browser prop to package.json. Closes #42
|
||||
|
||||
0.7.2 / 2013-02-06
|
||||
==================
|
||||
|
||||
* fix package.json
|
||||
* fix: Mobile Safari (private mode) is broken with debug
|
||||
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
|
||||
|
||||
0.7.1 / 2013-02-05
|
||||
==================
|
||||
|
||||
* add repository URL to package.json
|
||||
* add DEBUG_COLORED to force colored output
|
||||
* add browserify support
|
||||
* fix component. Closes #24
|
||||
|
||||
0.7.0 / 2012-05-04
|
||||
==================
|
||||
|
||||
* Added .component to package.json
|
||||
* Added debug.component.js build
|
||||
|
||||
0.6.0 / 2012-03-16
|
||||
==================
|
||||
|
||||
* Added support for "-" prefix in DEBUG [Vinay Pulim]
|
||||
* Added `.enabled` flag to the node version [TooTallNate]
|
||||
|
||||
0.5.0 / 2012-02-02
|
||||
==================
|
||||
|
||||
* Added: humanize diffs. Closes #8
|
||||
* Added `debug.disable()` to the CS variant
|
||||
* Removed padding. Closes #10
|
||||
* Fixed: persist client-side variant again. Closes #9
|
||||
|
||||
0.4.0 / 2012-02-01
|
||||
==================
|
||||
|
||||
* Added browser variant support for older browsers [TooTallNate]
|
||||
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
|
||||
* Added padding to diff (moved it to the right)
|
||||
|
||||
0.3.0 / 2012-01-26
|
||||
==================
|
||||
|
||||
* Added millisecond diff when isatty, otherwise UTC string
|
||||
|
||||
0.2.0 / 2012-01-22
|
||||
==================
|
||||
|
||||
* Added wildcard support
|
||||
|
||||
0.1.0 / 2011-12-02
|
||||
==================
|
||||
|
||||
* Added: remove colors unless stderr isatty [TooTallNate]
|
||||
|
||||
0.0.1 / 2010-01-03
|
||||
==================
|
||||
|
||||
* Initial release
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
|
||||
and associated documentation files (the 'Software'), to deal in the Software without restriction,
|
||||
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# get Makefile directory name: http://stackoverflow.com/a/5982798/376773
|
||||
THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
|
||||
THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)
|
||||
|
||||
# BIN directory
|
||||
BIN := $(THIS_DIR)/node_modules/.bin
|
||||
|
||||
# Path
|
||||
PATH := node_modules/.bin:$(PATH)
|
||||
SHELL := /bin/bash
|
||||
|
||||
# applications
|
||||
NODE ?= $(shell which node)
|
||||
YARN ?= $(shell which yarn)
|
||||
PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm))
|
||||
BROWSERIFY ?= $(NODE) $(BIN)/browserify
|
||||
|
||||
.FORCE:
|
||||
|
||||
install: node_modules
|
||||
|
||||
node_modules: package.json
|
||||
@NODE_ENV= $(PKG) install
|
||||
@touch node_modules
|
||||
|
||||
lint: .FORCE
|
||||
eslint browser.js debug.js index.js node.js
|
||||
|
||||
test-node: .FORCE
|
||||
istanbul cover node_modules/mocha/bin/_mocha -- test/**.js
|
||||
|
||||
test-browser: .FORCE
|
||||
mkdir -p dist
|
||||
|
||||
@$(BROWSERIFY) \
|
||||
--standalone debug \
|
||||
. > dist/debug.js
|
||||
|
||||
karma start --single-run
|
||||
rimraf dist
|
||||
|
||||
test: .FORCE
|
||||
concurrently \
|
||||
"make test-node" \
|
||||
"make test-browser"
|
||||
|
||||
coveralls:
|
||||
cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js
|
||||
|
||||
.PHONY: all install clean distclean
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
# debug
|
||||
[](https://travis-ci.org/visionmedia/debug) [](https://coveralls.io/github/visionmedia/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers)
|
||||
[](#sponsors)
|
||||
|
||||
|
||||
|
||||
A tiny node.js debugging utility modelled after node core's debugging technique.
|
||||
|
||||
**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)**
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
$ npm install debug
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
|
||||
|
||||
Example _app.js_:
|
||||
|
||||
```js
|
||||
var debug = require('debug')('http')
|
||||
, http = require('http')
|
||||
, name = 'My App';
|
||||
|
||||
// fake app
|
||||
|
||||
debug('booting %s', name);
|
||||
|
||||
http.createServer(function(req, res){
|
||||
debug(req.method + ' ' + req.url);
|
||||
res.end('hello\n');
|
||||
}).listen(3000, function(){
|
||||
debug('listening');
|
||||
});
|
||||
|
||||
// fake worker of some kind
|
||||
|
||||
require('./worker');
|
||||
```
|
||||
|
||||
Example _worker.js_:
|
||||
|
||||
```js
|
||||
var debug = require('debug')('worker');
|
||||
|
||||
setInterval(function(){
|
||||
debug('doing some work');
|
||||
}, 1000);
|
||||
```
|
||||
|
||||
The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
#### Windows note
|
||||
|
||||
On Windows the environment variable is set using the `set` command.
|
||||
|
||||
```cmd
|
||||
set DEBUG=*,-not_this
|
||||
```
|
||||
|
||||
Note that PowerShell uses different syntax to set environment variables.
|
||||
|
||||
```cmd
|
||||
$env:DEBUG = "*,-not_this"
|
||||
```
|
||||
|
||||
Then, run the program to be debugged as usual.
|
||||
|
||||
## Millisecond diff
|
||||
|
||||
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
|
||||
|
||||

|
||||
|
||||
When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:
|
||||
|
||||

|
||||
|
||||
## Conventions
|
||||
|
||||
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".
|
||||
|
||||
## Wildcards
|
||||
|
||||
The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
|
||||
|
||||
You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:".
|
||||
|
||||
## Environment Variables
|
||||
|
||||
When running through Node.js, you can set a few environment variables that will
|
||||
change the behavior of the debug logging:
|
||||
|
||||
| Name | Purpose |
|
||||
|-----------|-------------------------------------------------|
|
||||
| `DEBUG` | Enables/disables specific debugging namespaces. |
|
||||
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
|
||||
| `DEBUG_DEPTH` | Object inspection depth. |
|
||||
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
|
||||
|
||||
|
||||
__Note:__ The environment variables beginning with `DEBUG_` end up being
|
||||
converted into an Options object that gets used with `%o`/`%O` formatters.
|
||||
See the Node.js documentation for
|
||||
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
|
||||
for the complete list.
|
||||
|
||||
## Formatters
|
||||
|
||||
|
||||
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters:
|
||||
|
||||
| Formatter | Representation |
|
||||
|-----------|----------------|
|
||||
| `%O` | Pretty-print an Object on multiple lines. |
|
||||
| `%o` | Pretty-print an Object all on a single line. |
|
||||
| `%s` | String. |
|
||||
| `%d` | Number (both integer and float). |
|
||||
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
|
||||
| `%%` | Single percent sign ('%'). This does not consume an argument. |
|
||||
|
||||
### Custom formatters
|
||||
|
||||
You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like:
|
||||
|
||||
```js
|
||||
const createDebug = require('debug')
|
||||
createDebug.formatters.h = (v) => {
|
||||
return v.toString('hex')
|
||||
}
|
||||
|
||||
// …elsewhere
|
||||
const debug = createDebug('foo')
|
||||
debug('this is hex: %h', new Buffer('hello world'))
|
||||
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
|
||||
```
|
||||
|
||||
## Browser support
|
||||
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
|
||||
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
|
||||
if you don't want to build it yourself.
|
||||
|
||||
Debug's enable state is currently persisted by `localStorage`.
|
||||
Consider the situation shown below where you have `worker:a` and `worker:b`,
|
||||
and wish to debug both. You can enable this using `localStorage.debug`:
|
||||
|
||||
```js
|
||||
localStorage.debug = 'worker:*'
|
||||
```
|
||||
|
||||
And then refresh the page.
|
||||
|
||||
```js
|
||||
a = debug('worker:a');
|
||||
b = debug('worker:b');
|
||||
|
||||
setInterval(function(){
|
||||
a('doing some work');
|
||||
}, 1000);
|
||||
|
||||
setInterval(function(){
|
||||
b('doing some work');
|
||||
}, 1200);
|
||||
```
|
||||
|
||||
#### Web Inspector Colors
|
||||
|
||||
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
|
||||
option. These are WebKit web inspectors, Firefox ([since version
|
||||
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
|
||||
and the Firebug plugin for Firefox (any version).
|
||||
|
||||
Colored output looks something like:
|
||||
|
||||

|
||||
|
||||
|
||||
## Output streams
|
||||
|
||||
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
|
||||
|
||||
Example _stdout.js_:
|
||||
|
||||
```js
|
||||
var debug = require('debug');
|
||||
var error = debug('app:error');
|
||||
|
||||
// by default stderr is used
|
||||
error('goes to stderr!');
|
||||
|
||||
var log = debug('app:log');
|
||||
// set this namespace to log via console.log
|
||||
log.log = console.log.bind(console); // don't forget to bind to console!
|
||||
log('goes to stdout');
|
||||
error('still goes to stderr!');
|
||||
|
||||
// set all output to go via console.info
|
||||
// overrides all per-namespace log settings
|
||||
debug.log = console.info.bind(console);
|
||||
error('now goes to stdout via console.info');
|
||||
log('still goes to stdout, but via console.info now');
|
||||
```
|
||||
|
||||
|
||||
## Authors
|
||||
|
||||
- TJ Holowaychuk
|
||||
- Nathan Rajlich
|
||||
- Andrew Rhyne
|
||||
|
||||
## Backers
|
||||
|
||||
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
|
||||
|
||||
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
|
||||
|
||||
|
||||
## Sponsors
|
||||
|
||||
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
|
||||
|
||||
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
|
||||
|
||||
## License
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "debug",
|
||||
"repo": "visionmedia/debug",
|
||||
"description": "small debugging utility",
|
||||
"version": "2.6.9",
|
||||
"keywords": [
|
||||
"debug",
|
||||
"log",
|
||||
"debugger"
|
||||
],
|
||||
"main": "src/browser.js",
|
||||
"scripts": [
|
||||
"src/browser.js",
|
||||
"src/debug.js"
|
||||
],
|
||||
"dependencies": {
|
||||
"rauchg/ms.js": "0.7.1"
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// Karma configuration
|
||||
// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC)
|
||||
|
||||
module.exports = function(config) {
|
||||
config.set({
|
||||
|
||||
// base path that will be used to resolve all patterns (eg. files, exclude)
|
||||
basePath: '',
|
||||
|
||||
|
||||
// frameworks to use
|
||||
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
|
||||
frameworks: ['mocha', 'chai', 'sinon'],
|
||||
|
||||
|
||||
// list of files / patterns to load in the browser
|
||||
files: [
|
||||
'dist/debug.js',
|
||||
'test/*spec.js'
|
||||
],
|
||||
|
||||
|
||||
// list of files to exclude
|
||||
exclude: [
|
||||
'src/node.js'
|
||||
],
|
||||
|
||||
|
||||
// preprocess matching files before serving them to the browser
|
||||
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
|
||||
preprocessors: {
|
||||
},
|
||||
|
||||
// test results reporter to use
|
||||
// possible values: 'dots', 'progress'
|
||||
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
|
||||
reporters: ['progress'],
|
||||
|
||||
|
||||
// web server port
|
||||
port: 9876,
|
||||
|
||||
|
||||
// enable / disable colors in the output (reporters and logs)
|
||||
colors: true,
|
||||
|
||||
|
||||
// level of logging
|
||||
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
|
||||
logLevel: config.LOG_INFO,
|
||||
|
||||
|
||||
// enable / disable watching file and executing tests whenever any file changes
|
||||
autoWatch: true,
|
||||
|
||||
|
||||
// start these browsers
|
||||
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
|
||||
browsers: ['PhantomJS'],
|
||||
|
||||
|
||||
// Continuous Integration mode
|
||||
// if true, Karma captures browsers, runs the tests and exits
|
||||
singleRun: false,
|
||||
|
||||
// Concurrency level
|
||||
// how many browser should be started simultaneous
|
||||
concurrency: Infinity
|
||||
})
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require('./src/node');
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "debug",
|
||||
"version": "2.6.9",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/visionmedia/debug.git"
|
||||
},
|
||||
"description": "small debugging utility",
|
||||
"keywords": [
|
||||
"debug",
|
||||
"log",
|
||||
"debugger"
|
||||
],
|
||||
"author": "TJ Holowaychuk <tj@vision-media.ca>",
|
||||
"contributors": [
|
||||
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
|
||||
"Andrew Rhyne <rhyneandrew@gmail.com>"
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"browserify": "9.0.3",
|
||||
"chai": "^3.5.0",
|
||||
"concurrently": "^3.1.0",
|
||||
"coveralls": "^2.11.15",
|
||||
"eslint": "^3.12.1",
|
||||
"istanbul": "^0.4.5",
|
||||
"karma": "^1.3.0",
|
||||
"karma-chai": "^0.1.0",
|
||||
"karma-mocha": "^1.3.0",
|
||||
"karma-phantomjs-launcher": "^1.0.2",
|
||||
"karma-sinon": "^1.0.5",
|
||||
"mocha": "^3.2.0",
|
||||
"mocha-lcov-reporter": "^1.2.0",
|
||||
"rimraf": "^2.5.4",
|
||||
"sinon": "^1.17.6",
|
||||
"sinon-chai": "^2.8.0"
|
||||
},
|
||||
"main": "./src/index.js",
|
||||
"browser": "./src/browser.js",
|
||||
"component": {
|
||||
"scripts": {
|
||||
"debug/index.js": "browser.js",
|
||||
"debug/debug.js": "debug.js"
|
||||
}
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* This is the web browser implementation of `debug()`.
|
||||
*
|
||||
* Expose `debug()` as the module.
|
||||
*/
|
||||
|
||||
exports = module.exports = require('./debug');
|
||||
exports.log = log;
|
||||
exports.formatArgs = formatArgs;
|
||||
exports.save = save;
|
||||
exports.load = load;
|
||||
exports.useColors = useColors;
|
||||
exports.storage = 'undefined' != typeof chrome
|
||||
&& 'undefined' != typeof chrome.storage
|
||||
? chrome.storage.local
|
||||
: localstorage();
|
||||
|
||||
/**
|
||||
* Colors.
|
||||
*/
|
||||
|
||||
exports.colors = [
|
||||
'lightseagreen',
|
||||
'forestgreen',
|
||||
'goldenrod',
|
||||
'dodgerblue',
|
||||
'darkorchid',
|
||||
'crimson'
|
||||
];
|
||||
|
||||
/**
|
||||
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
|
||||
* and the Firebug extension (any Firefox version) are known
|
||||
* to support "%c" CSS customizations.
|
||||
*
|
||||
* TODO: add a `localStorage` variable to explicitly enable/disable colors
|
||||
*/
|
||||
|
||||
function useColors() {
|
||||
// NB: In an Electron preload script, document will be defined but not fully
|
||||
// initialized. Since we know we're in Chrome, we'll just detect this case
|
||||
// explicitly
|
||||
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// is webkit? http://stackoverflow.com/a/16459606/376773
|
||||
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
|
||||
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
|
||||
// is firebug? http://stackoverflow.com/a/398120/376773
|
||||
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
|
||||
// is firefox >= v31?
|
||||
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
|
||||
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
|
||||
// double check webkit in userAgent just in case we are in a worker
|
||||
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
|
||||
}
|
||||
|
||||
/**
|
||||
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
|
||||
*/
|
||||
|
||||
exports.formatters.j = function(v) {
|
||||
try {
|
||||
return JSON.stringify(v);
|
||||
} catch (err) {
|
||||
return '[UnexpectedJSONParseError]: ' + err.message;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Colorize log arguments if enabled.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function formatArgs(args) {
|
||||
var useColors = this.useColors;
|
||||
|
||||
args[0] = (useColors ? '%c' : '')
|
||||
+ this.namespace
|
||||
+ (useColors ? ' %c' : ' ')
|
||||
+ args[0]
|
||||
+ (useColors ? '%c ' : ' ')
|
||||
+ '+' + exports.humanize(this.diff);
|
||||
|
||||
if (!useColors) return;
|
||||
|
||||
var c = 'color: ' + this.color;
|
||||
args.splice(1, 0, c, 'color: inherit')
|
||||
|
||||
// the final "%c" is somewhat tricky, because there could be other
|
||||
// arguments passed either before or after the %c, so we need to
|
||||
// figure out the correct index to insert the CSS into
|
||||
var index = 0;
|
||||
var lastC = 0;
|
||||
args[0].replace(/%[a-zA-Z%]/g, function(match) {
|
||||
if ('%%' === match) return;
|
||||
index++;
|
||||
if ('%c' === match) {
|
||||
// we only are interested in the *last* %c
|
||||
// (the user may have provided their own)
|
||||
lastC = index;
|
||||
}
|
||||
});
|
||||
|
||||
args.splice(lastC, 0, c);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes `console.log()` when available.
|
||||
* No-op when `console.log` is not a "function".
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function log() {
|
||||
// this hackery is required for IE8/9, where
|
||||
// the `console.log` function doesn't have 'apply'
|
||||
return 'object' === typeof console
|
||||
&& console.log
|
||||
&& Function.prototype.apply.call(console.log, console, arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save `namespaces`.
|
||||
*
|
||||
* @param {String} namespaces
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function save(namespaces) {
|
||||
try {
|
||||
if (null == namespaces) {
|
||||
exports.storage.removeItem('debug');
|
||||
} else {
|
||||
exports.storage.debug = namespaces;
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `namespaces`.
|
||||
*
|
||||
* @return {String} returns the previously persisted debug modes
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function load() {
|
||||
var r;
|
||||
try {
|
||||
r = exports.storage.debug;
|
||||
} catch(e) {}
|
||||
|
||||
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
|
||||
if (!r && typeof process !== 'undefined' && 'env' in process) {
|
||||
r = process.env.DEBUG;
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable namespaces listed in `localStorage.debug` initially.
|
||||
*/
|
||||
|
||||
exports.enable(load());
|
||||
|
||||
/**
|
||||
* Localstorage attempts to return the localstorage.
|
||||
*
|
||||
* This is necessary because safari throws
|
||||
* when a user disables cookies/localstorage
|
||||
* and you attempt to access it.
|
||||
*
|
||||
* @return {LocalStorage}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function localstorage() {
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch (e) {}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
/**
|
||||
* This is the common logic for both the Node.js and web browser
|
||||
* implementations of `debug()`.
|
||||
*
|
||||
* Expose `debug()` as the module.
|
||||
*/
|
||||
|
||||
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
|
||||
exports.coerce = coerce;
|
||||
exports.disable = disable;
|
||||
exports.enable = enable;
|
||||
exports.enabled = enabled;
|
||||
exports.humanize = require('ms');
|
||||
|
||||
/**
|
||||
* The currently active debug mode names, and names to skip.
|
||||
*/
|
||||
|
||||
exports.names = [];
|
||||
exports.skips = [];
|
||||
|
||||
/**
|
||||
* Map of special "%n" handling functions, for the debug "format" argument.
|
||||
*
|
||||
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
|
||||
*/
|
||||
|
||||
exports.formatters = {};
|
||||
|
||||
/**
|
||||
* Previous log timestamp.
|
||||
*/
|
||||
|
||||
var prevTime;
|
||||
|
||||
/**
|
||||
* Select a color.
|
||||
* @param {String} namespace
|
||||
* @return {Number}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function selectColor(namespace) {
|
||||
var hash = 0, i;
|
||||
|
||||
for (i in namespace) {
|
||||
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
|
||||
hash |= 0; // Convert to 32bit integer
|
||||
}
|
||||
|
||||
return exports.colors[Math.abs(hash) % exports.colors.length];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a debugger with the given `namespace`.
|
||||
*
|
||||
* @param {String} namespace
|
||||
* @return {Function}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function createDebug(namespace) {
|
||||
|
||||
function debug() {
|
||||
// disabled?
|
||||
if (!debug.enabled) return;
|
||||
|
||||
var self = debug;
|
||||
|
||||
// set `diff` timestamp
|
||||
var curr = +new Date();
|
||||
var ms = curr - (prevTime || curr);
|
||||
self.diff = ms;
|
||||
self.prev = prevTime;
|
||||
self.curr = curr;
|
||||
prevTime = curr;
|
||||
|
||||
// turn the `arguments` into a proper Array
|
||||
var args = new Array(arguments.length);
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
args[0] = exports.coerce(args[0]);
|
||||
|
||||
if ('string' !== typeof args[0]) {
|
||||
// anything else let's inspect with %O
|
||||
args.unshift('%O');
|
||||
}
|
||||
|
||||
// apply any `formatters` transformations
|
||||
var index = 0;
|
||||
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
|
||||
// if we encounter an escaped % then don't increase the array index
|
||||
if (match === '%%') return match;
|
||||
index++;
|
||||
var formatter = exports.formatters[format];
|
||||
if ('function' === typeof formatter) {
|
||||
var val = args[index];
|
||||
match = formatter.call(self, val);
|
||||
|
||||
// now we need to remove `args[index]` since it's inlined in the `format`
|
||||
args.splice(index, 1);
|
||||
index--;
|
||||
}
|
||||
return match;
|
||||
});
|
||||
|
||||
// apply env-specific formatting (colors, etc.)
|
||||
exports.formatArgs.call(self, args);
|
||||
|
||||
var logFn = debug.log || exports.log || console.log.bind(console);
|
||||
logFn.apply(self, args);
|
||||
}
|
||||
|
||||
debug.namespace = namespace;
|
||||
debug.enabled = exports.enabled(namespace);
|
||||
debug.useColors = exports.useColors();
|
||||
debug.color = selectColor(namespace);
|
||||
|
||||
// env-specific initialization logic for debug instances
|
||||
if ('function' === typeof exports.init) {
|
||||
exports.init(debug);
|
||||
}
|
||||
|
||||
return debug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables a debug mode by namespaces. This can include modes
|
||||
* separated by a colon and wildcards.
|
||||
*
|
||||
* @param {String} namespaces
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function enable(namespaces) {
|
||||
exports.save(namespaces);
|
||||
|
||||
exports.names = [];
|
||||
exports.skips = [];
|
||||
|
||||
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
|
||||
var len = split.length;
|
||||
|
||||
for (var i = 0; i < len; i++) {
|
||||
if (!split[i]) continue; // ignore empty strings
|
||||
namespaces = split[i].replace(/\*/g, '.*?');
|
||||
if (namespaces[0] === '-') {
|
||||
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
|
||||
} else {
|
||||
exports.names.push(new RegExp('^' + namespaces + '$'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable debug output.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function disable() {
|
||||
exports.enable('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the given mode name is enabled, false otherwise.
|
||||
*
|
||||
* @param {String} name
|
||||
* @return {Boolean}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function enabled(name) {
|
||||
var i, len;
|
||||
for (i = 0, len = exports.skips.length; i < len; i++) {
|
||||
if (exports.skips[i].test(name)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (i = 0, len = exports.names.length; i < len; i++) {
|
||||
if (exports.names[i].test(name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce `val`.
|
||||
*
|
||||
* @param {Mixed} val
|
||||
* @return {Mixed}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function coerce(val) {
|
||||
if (val instanceof Error) return val.stack || val.message;
|
||||
return val;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Detect Electron renderer process, which is node, but we should
|
||||
* treat as a browser.
|
||||
*/
|
||||
|
||||
if (typeof process !== 'undefined' && process.type === 'renderer') {
|
||||
module.exports = require('./browser.js');
|
||||
} else {
|
||||
module.exports = require('./node.js');
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
module.exports = inspectorLog;
|
||||
|
||||
// black hole
|
||||
const nullStream = new (require('stream').Writable)();
|
||||
nullStream._write = () => {};
|
||||
|
||||
/**
|
||||
* Outputs a `console.log()` to the Node.js Inspector console *only*.
|
||||
*/
|
||||
function inspectorLog() {
|
||||
const stdout = console._stdout;
|
||||
console._stdout = nullStream;
|
||||
console.log.apply(console, arguments);
|
||||
console._stdout = stdout;
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var tty = require('tty');
|
||||
var util = require('util');
|
||||
|
||||
/**
|
||||
* This is the Node.js implementation of `debug()`.
|
||||
*
|
||||
* Expose `debug()` as the module.
|
||||
*/
|
||||
|
||||
exports = module.exports = require('./debug');
|
||||
exports.init = init;
|
||||
exports.log = log;
|
||||
exports.formatArgs = formatArgs;
|
||||
exports.save = save;
|
||||
exports.load = load;
|
||||
exports.useColors = useColors;
|
||||
|
||||
/**
|
||||
* Colors.
|
||||
*/
|
||||
|
||||
exports.colors = [6, 2, 3, 4, 5, 1];
|
||||
|
||||
/**
|
||||
* Build up the default `inspectOpts` object from the environment variables.
|
||||
*
|
||||
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
|
||||
*/
|
||||
|
||||
exports.inspectOpts = Object.keys(process.env).filter(function (key) {
|
||||
return /^debug_/i.test(key);
|
||||
}).reduce(function (obj, key) {
|
||||
// camel-case
|
||||
var prop = key
|
||||
.substring(6)
|
||||
.toLowerCase()
|
||||
.replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
|
||||
|
||||
// coerce string value into JS value
|
||||
var val = process.env[key];
|
||||
if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
|
||||
else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
|
||||
else if (val === 'null') val = null;
|
||||
else val = Number(val);
|
||||
|
||||
obj[prop] = val;
|
||||
return obj;
|
||||
}, {});
|
||||
|
||||
/**
|
||||
* The file descriptor to write the `debug()` calls to.
|
||||
* Set the `DEBUG_FD` env variable to override with another value. i.e.:
|
||||
*
|
||||
* $ DEBUG_FD=3 node script.js 3>debug.log
|
||||
*/
|
||||
|
||||
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
|
||||
|
||||
if (1 !== fd && 2 !== fd) {
|
||||
util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()
|
||||
}
|
||||
|
||||
var stream = 1 === fd ? process.stdout :
|
||||
2 === fd ? process.stderr :
|
||||
createWritableStdioStream(fd);
|
||||
|
||||
/**
|
||||
* Is stdout a TTY? Colored output is enabled when `true`.
|
||||
*/
|
||||
|
||||
function useColors() {
|
||||
return 'colors' in exports.inspectOpts
|
||||
? Boolean(exports.inspectOpts.colors)
|
||||
: tty.isatty(fd);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map %o to `util.inspect()`, all on a single line.
|
||||
*/
|
||||
|
||||
exports.formatters.o = function(v) {
|
||||
this.inspectOpts.colors = this.useColors;
|
||||
return util.inspect(v, this.inspectOpts)
|
||||
.split('\n').map(function(str) {
|
||||
return str.trim()
|
||||
}).join(' ');
|
||||
};
|
||||
|
||||
/**
|
||||
* Map %o to `util.inspect()`, allowing multiple lines if needed.
|
||||
*/
|
||||
|
||||
exports.formatters.O = function(v) {
|
||||
this.inspectOpts.colors = this.useColors;
|
||||
return util.inspect(v, this.inspectOpts);
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds ANSI color escape codes if enabled.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function formatArgs(args) {
|
||||
var name = this.namespace;
|
||||
var useColors = this.useColors;
|
||||
|
||||
if (useColors) {
|
||||
var c = this.color;
|
||||
var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
|
||||
|
||||
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
|
||||
args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
|
||||
} else {
|
||||
args[0] = new Date().toUTCString()
|
||||
+ ' ' + name + ' ' + args[0];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes `util.format()` with the specified arguments and writes to `stream`.
|
||||
*/
|
||||
|
||||
function log() {
|
||||
return stream.write(util.format.apply(util, arguments) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Save `namespaces`.
|
||||
*
|
||||
* @param {String} namespaces
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function save(namespaces) {
|
||||
if (null == namespaces) {
|
||||
// If you set a process.env field to null or undefined, it gets cast to the
|
||||
// string 'null' or 'undefined'. Just delete instead.
|
||||
delete process.env.DEBUG;
|
||||
} else {
|
||||
process.env.DEBUG = namespaces;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `namespaces`.
|
||||
*
|
||||
* @return {String} returns the previously persisted debug modes
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function load() {
|
||||
return process.env.DEBUG;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copied from `node/src/node.js`.
|
||||
*
|
||||
* XXX: It's lame that node doesn't expose this API out-of-the-box. It also
|
||||
* relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
|
||||
*/
|
||||
|
||||
function createWritableStdioStream (fd) {
|
||||
var stream;
|
||||
var tty_wrap = process.binding('tty_wrap');
|
||||
|
||||
// Note stream._type is used for test-module-load-list.js
|
||||
|
||||
switch (tty_wrap.guessHandleType(fd)) {
|
||||
case 'TTY':
|
||||
stream = new tty.WriteStream(fd);
|
||||
stream._type = 'tty';
|
||||
|
||||
// Hack to have stream not keep the event loop alive.
|
||||
// See https://github.com/joyent/node/issues/1726
|
||||
if (stream._handle && stream._handle.unref) {
|
||||
stream._handle.unref();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'FILE':
|
||||
var fs = require('fs');
|
||||
stream = new fs.SyncWriteStream(fd, { autoClose: false });
|
||||
stream._type = 'fs';
|
||||
break;
|
||||
|
||||
case 'PIPE':
|
||||
case 'TCP':
|
||||
var net = require('net');
|
||||
stream = new net.Socket({
|
||||
fd: fd,
|
||||
readable: false,
|
||||
writable: true
|
||||
});
|
||||
|
||||
// FIXME Should probably have an option in net.Socket to create a
|
||||
// stream from an existing fd which is writable only. But for now
|
||||
// we'll just add this hack and set the `readable` member to false.
|
||||
// Test: ./node test/fixtures/echo.js < /etc/passwd
|
||||
stream.readable = false;
|
||||
stream.read = null;
|
||||
stream._type = 'pipe';
|
||||
|
||||
// FIXME Hack to have stream not keep the event loop alive.
|
||||
// See https://github.com/joyent/node/issues/1726
|
||||
if (stream._handle && stream._handle.unref) {
|
||||
stream._handle.unref();
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
// Probably an error on in uv_guess_handle()
|
||||
throw new Error('Implement me. Unknown stream file type!');
|
||||
}
|
||||
|
||||
// For supporting legacy API we put the FD here.
|
||||
stream.fd = fd;
|
||||
|
||||
stream._isStdio = true;
|
||||
|
||||
return stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Init logic for `debug` instances.
|
||||
*
|
||||
* Create a new `inspectOpts` object in case `useColors` is set
|
||||
* differently for a particular `debug` instance.
|
||||
*/
|
||||
|
||||
function init (debug) {
|
||||
debug.inspectOpts = {};
|
||||
|
||||
var keys = Object.keys(exports.inspectOpts);
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable namespaces listed in `process.env.DEBUG` initially.
|
||||
*/
|
||||
|
||||
exports.enable(load());
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Helpers.
|
||||
*/
|
||||
|
||||
var s = 1000;
|
||||
var m = s * 60;
|
||||
var h = m * 60;
|
||||
var d = h * 24;
|
||||
var y = d * 365.25;
|
||||
|
||||
/**
|
||||
* Parse or format the given `val`.
|
||||
*
|
||||
* Options:
|
||||
*
|
||||
* - `long` verbose formatting [false]
|
||||
*
|
||||
* @param {String|Number} val
|
||||
* @param {Object} [options]
|
||||
* @throws {Error} throw an error if val is not a non-empty string or a number
|
||||
* @return {String|Number}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
module.exports = function(val, options) {
|
||||
options = options || {};
|
||||
var type = typeof val;
|
||||
if (type === 'string' && val.length > 0) {
|
||||
return parse(val);
|
||||
} else if (type === 'number' && isNaN(val) === false) {
|
||||
return options.long ? fmtLong(val) : fmtShort(val);
|
||||
}
|
||||
throw new Error(
|
||||
'val is not a non-empty string or a valid number. val=' +
|
||||
JSON.stringify(val)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse the given `str` and return milliseconds.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {Number}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function parse(str) {
|
||||
str = String(str);
|
||||
if (str.length > 100) {
|
||||
return;
|
||||
}
|
||||
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
|
||||
str
|
||||
);
|
||||
if (!match) {
|
||||
return;
|
||||
}
|
||||
var n = parseFloat(match[1]);
|
||||
var type = (match[2] || 'ms').toLowerCase();
|
||||
switch (type) {
|
||||
case 'years':
|
||||
case 'year':
|
||||
case 'yrs':
|
||||
case 'yr':
|
||||
case 'y':
|
||||
return n * y;
|
||||
case 'days':
|
||||
case 'day':
|
||||
case 'd':
|
||||
return n * d;
|
||||
case 'hours':
|
||||
case 'hour':
|
||||
case 'hrs':
|
||||
case 'hr':
|
||||
case 'h':
|
||||
return n * h;
|
||||
case 'minutes':
|
||||
case 'minute':
|
||||
case 'mins':
|
||||
case 'min':
|
||||
case 'm':
|
||||
return n * m;
|
||||
case 'seconds':
|
||||
case 'second':
|
||||
case 'secs':
|
||||
case 'sec':
|
||||
case 's':
|
||||
return n * s;
|
||||
case 'milliseconds':
|
||||
case 'millisecond':
|
||||
case 'msecs':
|
||||
case 'msec':
|
||||
case 'ms':
|
||||
return n;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Short format for `ms`.
|
||||
*
|
||||
* @param {Number} ms
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function fmtShort(ms) {
|
||||
if (ms >= d) {
|
||||
return Math.round(ms / d) + 'd';
|
||||
}
|
||||
if (ms >= h) {
|
||||
return Math.round(ms / h) + 'h';
|
||||
}
|
||||
if (ms >= m) {
|
||||
return Math.round(ms / m) + 'm';
|
||||
}
|
||||
if (ms >= s) {
|
||||
return Math.round(ms / s) + 's';
|
||||
}
|
||||
return ms + 'ms';
|
||||
}
|
||||
|
||||
/**
|
||||
* Long format for `ms`.
|
||||
*
|
||||
* @param {Number} ms
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function fmtLong(ms) {
|
||||
return plural(ms, d, 'day') ||
|
||||
plural(ms, h, 'hour') ||
|
||||
plural(ms, m, 'minute') ||
|
||||
plural(ms, s, 'second') ||
|
||||
ms + ' ms';
|
||||
}
|
||||
|
||||
/**
|
||||
* Pluralization helper.
|
||||
*/
|
||||
|
||||
function plural(ms, n, name) {
|
||||
if (ms < n) {
|
||||
return;
|
||||
}
|
||||
if (ms < n * 1.5) {
|
||||
return Math.floor(ms / n) + ' ' + name;
|
||||
}
|
||||
return Math.ceil(ms / n) + ' ' + name + 's';
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Zeit, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "ms",
|
||||
"version": "2.0.0",
|
||||
"description": "Tiny milisecond conversion utility",
|
||||
"repository": "zeit/ms",
|
||||
"main": "./index",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"scripts": {
|
||||
"precommit": "lint-staged",
|
||||
"lint": "eslint lib/* bin/*",
|
||||
"test": "mocha tests.js"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": "eslint:recommended",
|
||||
"env": {
|
||||
"node": true,
|
||||
"es6": true
|
||||
}
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.js": [
|
||||
"npm run lint",
|
||||
"prettier --single-quote --write",
|
||||
"git add"
|
||||
]
|
||||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"eslint": "3.19.0",
|
||||
"expect.js": "0.3.1",
|
||||
"husky": "0.13.3",
|
||||
"lint-staged": "3.4.1",
|
||||
"mocha": "3.4.1"
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
# ms
|
||||
|
||||
[](https://travis-ci.org/zeit/ms)
|
||||
[](https://zeit.chat/)
|
||||
|
||||
Use this package to easily convert various time formats to milliseconds.
|
||||
|
||||
## Examples
|
||||
|
||||
```js
|
||||
ms('2 days') // 172800000
|
||||
ms('1d') // 86400000
|
||||
ms('10h') // 36000000
|
||||
ms('2.5 hrs') // 9000000
|
||||
ms('2h') // 7200000
|
||||
ms('1m') // 60000
|
||||
ms('5s') // 5000
|
||||
ms('1y') // 31557600000
|
||||
ms('100') // 100
|
||||
```
|
||||
|
||||
### Convert from milliseconds
|
||||
|
||||
```js
|
||||
ms(60000) // "1m"
|
||||
ms(2 * 60000) // "2m"
|
||||
ms(ms('10 hours')) // "10h"
|
||||
```
|
||||
|
||||
### Time format written-out
|
||||
|
||||
```js
|
||||
ms(60000, { long: true }) // "1 minute"
|
||||
ms(2 * 60000, { long: true }) // "2 minutes"
|
||||
ms(ms('10 hours'), { long: true }) // "10 hours"
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- Works both in [node](https://nodejs.org) and in the browser.
|
||||
- If a number is supplied to `ms`, a string with a unit is returned.
|
||||
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`).
|
||||
- If you pass a string with a number and a valid unit, the number of equivalent ms is returned.
|
||||
|
||||
## Caught a bug?
|
||||
|
||||
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
|
||||
2. Link the package to the global module directory: `npm link`
|
||||
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms!
|
||||
|
||||
As always, you can run the tests using: `npm test`
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"name": "websocket",
|
||||
"description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",
|
||||
"keywords": [
|
||||
"websocket",
|
||||
"websockets",
|
||||
"socket",
|
||||
"networking",
|
||||
"comet",
|
||||
"push",
|
||||
"RFC-6455",
|
||||
"realtime",
|
||||
"server",
|
||||
"client"
|
||||
],
|
||||
"author": "Brian McKelvey <theturtle32@gmail.com> (https://github.com/theturtle32)",
|
||||
"contributors": [
|
||||
"Iñaki Baz Castillo <ibc@aliax.net> (http://dev.sipdoc.net)"
|
||||
],
|
||||
"version": "1.0.34",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/theturtle32/WebSocket-Node.git"
|
||||
},
|
||||
"homepage": "https://github.com/theturtle32/WebSocket-Node",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"debug": "^2.2.0",
|
||||
"es5-ext": "^0.10.50",
|
||||
"typedarray-to-buffer": "^3.1.5",
|
||||
"utf-8-validate": "^5.0.2",
|
||||
"yaeti": "^0.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"buffer-equal": "^1.0.0",
|
||||
"gulp": "^4.0.2",
|
||||
"gulp-jshint": "^2.0.4",
|
||||
"jshint-stylish": "^2.2.1",
|
||||
"jshint": "^2.0.0",
|
||||
"tape": "^4.9.1"
|
||||
},
|
||||
"config": {
|
||||
"verbose": false
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tape test/unit/*.js",
|
||||
"gulp": "gulp"
|
||||
},
|
||||
"main": "index",
|
||||
"directories": {
|
||||
"lib": "./lib"
|
||||
},
|
||||
"browser": "lib/browser.js",
|
||||
"license": "Apache-2.0"
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
// This file was copied from https://github.com/substack/node-bufferlist
|
||||
// and modified to be able to copy bytes from the bufferlist directly into
|
||||
// a pre-existing fixed-size buffer without an additional memory allocation.
|
||||
|
||||
// bufferlist.js
|
||||
// Treat a linked list of buffers as a single variable-size buffer.
|
||||
var Buffer = require('buffer').Buffer;
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var bufferAllocUnsafe = require('../lib/utils').bufferAllocUnsafe;
|
||||
|
||||
module.exports = BufferList;
|
||||
module.exports.BufferList = BufferList; // backwards compatibility
|
||||
|
||||
function BufferList(opts) {
|
||||
if (!(this instanceof BufferList)) return new BufferList(opts);
|
||||
EventEmitter.call(this);
|
||||
var self = this;
|
||||
|
||||
if (typeof(opts) == 'undefined') opts = {};
|
||||
|
||||
// default encoding to use for take(). Leaving as 'undefined'
|
||||
// makes take() return a Buffer instead.
|
||||
self.encoding = opts.encoding;
|
||||
|
||||
var head = { next : null, buffer : null };
|
||||
var last = { next : null, buffer : null };
|
||||
|
||||
// length can get negative when advanced past the end
|
||||
// and this is the desired behavior
|
||||
var length = 0;
|
||||
self.__defineGetter__('length', function () {
|
||||
return length;
|
||||
});
|
||||
|
||||
// keep an offset of the head to decide when to head = head.next
|
||||
var offset = 0;
|
||||
|
||||
// Write to the bufferlist. Emits 'write'. Always returns true.
|
||||
self.write = function (buf) {
|
||||
if (!head.buffer) {
|
||||
head.buffer = buf;
|
||||
last = head;
|
||||
}
|
||||
else {
|
||||
last.next = { next : null, buffer : buf };
|
||||
last = last.next;
|
||||
}
|
||||
length += buf.length;
|
||||
self.emit('write', buf);
|
||||
return true;
|
||||
};
|
||||
|
||||
self.end = function (buf) {
|
||||
if (Buffer.isBuffer(buf)) self.write(buf);
|
||||
};
|
||||
|
||||
// Push buffers to the end of the linked list. (deprecated)
|
||||
// Return this (self).
|
||||
self.push = function () {
|
||||
var args = [].concat.apply([], arguments);
|
||||
args.forEach(self.write);
|
||||
return self;
|
||||
};
|
||||
|
||||
// For each buffer, perform some action.
|
||||
// If fn's result is a true value, cut out early.
|
||||
// Returns this (self).
|
||||
self.forEach = function (fn) {
|
||||
if (!head.buffer) return bufferAllocUnsafe(0);
|
||||
|
||||
if (head.buffer.length - offset <= 0) return self;
|
||||
var firstBuf = head.buffer.slice(offset);
|
||||
|
||||
var b = { buffer : firstBuf, next : head.next };
|
||||
|
||||
while (b && b.buffer) {
|
||||
var r = fn(b.buffer);
|
||||
if (r) break;
|
||||
b = b.next;
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
// Create a single Buffer out of all the chunks or some subset specified by
|
||||
// start and one-past the end (like slice) in bytes.
|
||||
self.join = function (start, end) {
|
||||
if (!head.buffer) return bufferAllocUnsafe(0);
|
||||
if (start == undefined) start = 0;
|
||||
if (end == undefined) end = self.length;
|
||||
|
||||
var big = bufferAllocUnsafe(end - start);
|
||||
var ix = 0;
|
||||
self.forEach(function (buffer) {
|
||||
if (start < (ix + buffer.length) && ix < end) {
|
||||
// at least partially contained in the range
|
||||
buffer.copy(
|
||||
big,
|
||||
Math.max(0, ix - start),
|
||||
Math.max(0, start - ix),
|
||||
Math.min(buffer.length, end - ix)
|
||||
);
|
||||
}
|
||||
ix += buffer.length;
|
||||
if (ix > end) return true; // stop processing past end
|
||||
});
|
||||
|
||||
return big;
|
||||
};
|
||||
|
||||
self.joinInto = function (targetBuffer, targetStart, sourceStart, sourceEnd) {
|
||||
if (!head.buffer) return new bufferAllocUnsafe(0);
|
||||
if (sourceStart == undefined) sourceStart = 0;
|
||||
if (sourceEnd == undefined) sourceEnd = self.length;
|
||||
|
||||
var big = targetBuffer;
|
||||
if (big.length - targetStart < sourceEnd - sourceStart) {
|
||||
throw new Error("Insufficient space available in target Buffer.");
|
||||
}
|
||||
var ix = 0;
|
||||
self.forEach(function (buffer) {
|
||||
if (sourceStart < (ix + buffer.length) && ix < sourceEnd) {
|
||||
// at least partially contained in the range
|
||||
buffer.copy(
|
||||
big,
|
||||
Math.max(targetStart, targetStart + ix - sourceStart),
|
||||
Math.max(0, sourceStart - ix),
|
||||
Math.min(buffer.length, sourceEnd - ix)
|
||||
);
|
||||
}
|
||||
ix += buffer.length;
|
||||
if (ix > sourceEnd) return true; // stop processing past end
|
||||
});
|
||||
|
||||
return big;
|
||||
};
|
||||
|
||||
// Advance the buffer stream by n bytes.
|
||||
// If n the aggregate advance offset passes the end of the buffer list,
|
||||
// operations such as .take() will return empty strings until enough data is
|
||||
// pushed.
|
||||
// Returns this (self).
|
||||
self.advance = function (n) {
|
||||
offset += n;
|
||||
length -= n;
|
||||
while (head.buffer && offset >= head.buffer.length) {
|
||||
offset -= head.buffer.length;
|
||||
head = head.next
|
||||
? head.next
|
||||
: { buffer : null, next : null }
|
||||
;
|
||||
}
|
||||
if (head.buffer === null) last = { next : null, buffer : null };
|
||||
self.emit('advance', n);
|
||||
return self;
|
||||
};
|
||||
|
||||
// Take n bytes from the start of the buffers.
|
||||
// Returns a string.
|
||||
// If there are less than n bytes in all the buffers or n is undefined,
|
||||
// returns the entire concatenated buffer string.
|
||||
self.take = function (n, encoding) {
|
||||
if (n == undefined) n = self.length;
|
||||
else if (typeof n !== 'number') {
|
||||
encoding = n;
|
||||
n = self.length;
|
||||
}
|
||||
var b = head;
|
||||
if (!encoding) encoding = self.encoding;
|
||||
if (encoding) {
|
||||
var acc = '';
|
||||
self.forEach(function (buffer) {
|
||||
if (n <= 0) return true;
|
||||
acc += buffer.toString(
|
||||
encoding, 0, Math.min(n,buffer.length)
|
||||
);
|
||||
n -= buffer.length;
|
||||
});
|
||||
return acc;
|
||||
} else {
|
||||
// If no 'encoding' is specified, then return a Buffer.
|
||||
return self.join(0, n);
|
||||
}
|
||||
};
|
||||
|
||||
// The entire concatenated buffer as a string.
|
||||
self.toString = function () {
|
||||
return self.take('binary');
|
||||
};
|
||||
}
|
||||
require('util').inherits(BufferList, EventEmitter);
|
||||
Reference in New Issue
Block a user