diff options
Diffstat (limited to 'common/src/main/webapp/usageguide/appserver/node_modules/mongodb')
203 files changed, 82966 insertions, 0 deletions
diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/.coveralls.yml b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/.coveralls.yml new file mode 100644 index 00000000..ad1e93c3 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/.coveralls.yml @@ -0,0 +1 @@ +repo_token: GZFmqKPy7XEX0uOl9TDZFUoOQ5AHADMkU diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/.eslintrc b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/.eslintrc new file mode 100644 index 00000000..753e2a52 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/.eslintrc @@ -0,0 +1,15 @@ +{ + "extends": ["eslint:recommended"], + "env": { + "node": true, + "mocha": true + }, + "ecmaFeatures": { + "es6": true, + }, + "plugins": [ + ], + "rules": { + "no-console":0 + } +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/HISTORY.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/HISTORY.md new file mode 100644 index 00000000..4b45e196 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/HISTORY.md @@ -0,0 +1,1593 @@ +2.2.16 2016-12-13 +----------------- +* NODE-899 reversed upsertedId change to bring back old behavior. + +2.2.15 2016-12-10 +----------------- +* Updated mongodb-core to 2.1.2. + * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. + * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). + +2.2.14 2016-12-08 +----------------- +* Updated mongodb-core to 2.1.1. +* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. + +2.2.13 2016-12-05 +----------------- +* Updated mongodb-core to 2.1.0. +* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. +* Expose parserType as property on topology objects. + +2.2.12 2016-11-29 +----------------- +* Updated mongodb-core to 2.0.14. + * Updated bson library to 0.5.7. + * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). + * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). + * Only check isConnected against availableConnections (Issue #142). + * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. + * Set default servername to host is not passed through for sni. + * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). + * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. + * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. + * NODE-850 Update Max Staleness implementation. + * NODE-849 username no longer required for MONGODB-X509 auth. + * NODE-848 BSON Regex flags must be alphabetically ordered. + * NODE-846 Create notice for all third party libraries. + * NODE-843 Executing bulk operations overwrites write concern parameter. + * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. + * NODE-840 Resync CRUD spec tests. + * Unescapable while(true) loop (Issue #152). +* NODE-864 close event not emits during network issues using single server topology. +* Introduced maxStalenessSeconds. +* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. +* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). + +2.2.11 2016-10-21 +----------------- +* Updated mongodb-core to 2.0.13. + - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). + - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). + - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). + - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). +* Updated bson library to 0.5.6. + - Included cyclic dependency detection +* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). +* NODE-824, readPreference "nearest" does not work when specified at collection level. +* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. +* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. +* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. + +2.2.10 2016-09-15 +----------------- +* Updated mongodb-core to 2.0.12. +* fix debug logging message not printing server name. +* fixed application metadata being sent by wrong ismaster. +* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. +* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". +* Updated bson library to 0.5.5. +* Added DBPointer up conversion to DBRef. +* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. +* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. +* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. +* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. + +2.2.9 2016-08-29 +---------------- +* Updated mongodb-core to 2.0.11. +* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. +* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). +* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. +* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). + +2.2.8 2016-08-23 +---------------- +* Updated mongodb-core to 2.0.10. +* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. +* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). + +2.2.7 2016-08-19 +---------------- +* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). +* Updated mongodb-core to 2.0.9. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* NODE-798 Driver hangs on count command in replica set with one member. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* Allow passing in servername for TLS connections for SNI support. + +2.2.6 2016-08-16 +---------------- +* Updated mongodb-core to 2.0.8. +* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). +* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. +* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) +* Added hashed connection names and fullResult. +* Updated bson library to 0.5.3. +* Enable maxTimeMS in count, distinct, findAndModify. + +2.2.5 2016-07-28 +---------------- +* Updated mongodb-core to 2.0.7. +* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). +* Added better warnings when passing in illegal seed list members to a Mongos topology. +* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. +* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) +* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. + +2.2.4 2016-07-19 +---------------- +* NPM corrupted upload fix. + +2.2.3 2016-07-19 +---------------- +* Updated mongodb-core to 2.0.6. +* Destroy connection on socket timeout due to newer node versions not closing the socket. + +2.2.2 2016-07-15 +---------------- +* Updated mongodb-core to 2.0.5. +* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. +* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. +* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. +* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. + +2.2.1 2016-07-11 +---------------- +* Updated mongodb-core to 2.0.4. +* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. +* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. +* NODE-746 Improves replicaset errors for wrong setName. + +2.2.0 2016-07-05 +---------------- +* Updated mongodb-core to 2.0.3. +* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. +* All authentication methods now handle both auth/reauthenticate and logout events. +* Introduced logout method to get rid of onAll option for logout command. +* Updated bson to 0.5.0 that includes Decimal128 support. +* Fixed logger error serialization issue. +* Documentation fixes. +* Implemented Server Selection Specification test suite. +* Added warning level to logger. +* Added warning message when sockeTimeout < haInterval for Replset/Mongos. +* Mongos emits close event on no proxies available or when reconnect attempt fails. +* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. +* Don't throw in auth methods but return error in callback. + +2.1.21 2016-05-30 +----------------- +* Updated mongodb-core to 1.3.21. +* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). +* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. +* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. +* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). +* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. +* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. + +2.1.20 2016-05-25 +----------------- +* Refactored MongoClient options handling to simplify the logic, unifying it. +* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. +* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. +* Updated mongodb-core to 1.3.20. +* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. +* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. +* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. + +2.1.19 2016-05-17 +---------------- +* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. +* Ensure replicaset topology destroy is never called by SDAM. +* Ensure all paths are correctly returned on inspectServer in replset. +* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. + +2.1.18 2016-04-27 +----------------- +* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. + +2.1.17 2016-04-26 +----------------- +* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. +* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. +* Fix timeout issue using new flags #1361. +* Updated mongodb-core to 1.3.17. +* Better handling of unique createIndex error. +* Emit error only if db instance has an error listener. +* DEFAULT authMechanism; don't throw error if explicitly set by user. + +2.1.16 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.16. + +2.1.15 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.15. +* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). +- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. +- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. + +2.1.14 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.13. +* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. + +2.1.13 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.12. + +2.1.12 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.11. +* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. +* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. +* isConnected method for mongos uses same selection code as getServer. +* Exceptions in cursor getServer trapped and correctly delegated to high level handler. + +2.1.11 2016-03-23 +----------------- +* Updated mongodb-core to 1.3.10. +* Introducing simplified connections settings. + +2.1.10 2016-03-21 +----------------- +* Updated mongodb-core to 1.3.9. +* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) +* Forwards SDAM monitoring events from mongodb-core. + +2.1.9 2016-03-16 +---------------- +* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. +* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. + +2.1.8 2016-03-14 +---------------- +* Updated mongodb-core to 1.3.5. +* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. +* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. +* Ensure RequestId can never be larger than Max Number integer size. +* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. +* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). +* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. +* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. +* NODE-663 added lookup helper on aggregation cursor. +* NODE-585 Result object specified incorrectly for findAndModify?. +* NODE-666 harden validation for findAndModify CRUD methods. + +2.1.7 2016-02-09 +---------------- +* NODE-656 fixed corner case where cursor count command could be left without a connection available. +* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. +* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). +* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). +* NODE-657 insertOne don`t return promise in some cases. +* Added destroy alias for abort function on GridFSBucketWriteStream. + +2.1.6 2016-02-05 +---------------- +* Updated mongodb-core to 1.3.1. + +2.1.5 2016-02-04 +---------------- +* Updated mongodb-core to 1.3.0. +* Added raw support for the command function on topologies. +* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +* NODE-638, Cannot authenticate database user with utf-8 password. +* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +* Switched to using Array.push instead of concat for use cases of a lot of documents. +* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +* Added peer optional dependencies support using require_optional module. +* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) +* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) + +2.1.4 2016-01-12 +---------------- +* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). +* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). +* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). + +2.1.3 2016-01-04 +---------------- +* Updated mongodb-core to 1.2.31. +* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +2.1.2 2015-12-23 +---------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.1.1 2015-12-13 +---------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.1.0 2015-12-06 +---------------- +* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. +* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. +* Full MongoDB 3.2 support. +* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Updated mongodb-core to 1.2.26. +* Return destination in GridStore pipe function. +* NODE-606 better error handling on destroyed topology for db.js methods. +* Added isDestroyed method to server, replset and mongos topologies. +* Upgraded test suite to run using mongodb-topology-manager. + +2.0.53 2015-12-23 +----------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.0.52 2015-12-14 +----------------- +* removed remove from Gridstore.close. + +2.0.51 2015-12-13 +----------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.0.50 2015-12-06 +----------------- +* Updated mongodb-core to 1.2.26. + +2.0.49 2015-11-20 +----------------- +* Updated mongodb-core to 1.2.24 with several fixes. + * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). + * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + * ismaster runs against admin.$cmd instead of system.$cmd. + * Fixes to handle getMore command errors for MongoDB 3.2 + * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +2.0.48 2015-11-07 +----------------- +* GridFS no longer performs any deletes when writing a brand new file that does not have any previous <db>.fs.chunks or <db>.fs.files documents. +* Updated mongodb-core to 1.2.21. +* Hardened the checking for replicaset equality checks. +* OpReplay flag correctly set on Wire protocol query. +* Mongos load balancing added, introduced localThresholdMS to control the feature. +* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +2.0.47 2015-10-28 +----------------- +* Updated mongodb-core to 1.2.20. +* Fixed bug in arbiter connection capping code. +* NODE-599 correctly handle arrays of server tags in order of priority. +* Fix for 2.6 wire protocol handler related to readPreference handling. +* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +2.0.46 2015-10-15 +----------------- +* Updated mongodb-core to 1.2.19. +* NODE-578 Order of sort fields is lost for numeric field names. +* Expose BSON Map (ES6 Map or polyfill). +* Minor fixes for APM support to pass extended APM test suite. + +2.0.45 2015-09-30 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 2015-09-28 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 2015-09-14 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 2015-08-18 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 2015-08-14 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 2015-07-14 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 2015-07-14 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 2015-07-07 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 2015-05-20 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 2015-05-19 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 2015-05-08 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 2015-05-07 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 2015-05-07 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 2015-04-24 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 2015-04-07 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 2015-04-07 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 2015-03-26 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 2015-03-24 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\<Object\>' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/LICENSE new file mode 100644 index 00000000..ad410e11 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/LICENSE @@ -0,0 +1,201 @@ +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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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.
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/Makefile b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/Makefile new file mode 100644 index 00000000..36e12024 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/README.md new file mode 100644 index 00000000..73f27857 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/README.md @@ -0,0 +1,415 @@ +[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) +[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| api-doc | http://mongodb.github.io/node-mongodb-native/2.2/api/ | +| source | https://github.com/mongodb/node-mongodb-native | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) <http://christiankvalheim.com> + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login <https://jira.mongodb.org>. +- Navigate to the NODE project <https://jira.mongodb.org/browse/NODE>. +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +# Installation + +The recommended way to get started using the Node.js 2.0 driver is by using the `NPM` (Node Package Manager) to install the dependency in your project. + +## MongoDB Driver + +Given that you have created your own project using `npm init` we install the mongodb driver and it's dependencies by executing the following `NPM` command. + +``` +npm install mongodb --save +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +## Troubleshooting + +The MongoDB driver depends on several other packages. These are. + +* mongodb-core +* bson +* kerberos +* node-gyp + +The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build node.js itself to be able to compile and install the `kerberos` module. Furthermore the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager what libraries to install. + +{{% note class="important" %}} +Windows already contains the SSPI API used for Kerberos authentication. However you will need to install a full compiler tool chain using visual studio C++ to correctly install the kerberos extension. +{{% /note %}} + +### Diagnosing on UNIX + +If you don’t have the build essentials it won’t build. In the case of linux you will need gcc and g++, node.js with all the headers and python. The easiest way to figure out what’s missing is by trying to build the kerberos project. You can do this by performing the following steps. + +``` +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +``` + +If all the steps complete you have the right toolchain installed. If you get node-gyp not found you need to install it globally by doing. + +``` +npm install -g node-gyp +``` + +If correctly compiles and runs the tests you are golden. We can now try to install the mongod driver by performing the following command. + +``` +cd yourproject +npm install mongodb --save +``` + +If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. + +``` +npm --loglevel verbose install mongodb +``` + +This will print out all the steps npm is performing while trying to install the module. + +### Diagnosing on Windows + +A known compiler tool chain known to work for compiling `kerberos` on windows is the following. + +* Visual Studio c++ 2010 (do not use higher versions) +* Windows 7 64bit SDK +* Python 2.7 or higher + +Open visual studio command prompt. Ensure node.exe is in your path and install node-gyp. + +``` +npm install -g node-gyp +``` + +Next you will have to build the project manually to test it. Use any tool you use with git and grab the repo. + +``` +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +node-gyp rebuild +``` + +This should rebuild the driver successfully if you have everything set up correctly. + +### Other possible issues + +Your python installation might be hosed making gyp break. I always recommend that you test your deployment environment first by trying to build node itself on the server in question as this should unearth any issues with broken packages (and there are a lot of broken packages out there). + +Another thing is to ensure your user has write permission to wherever the node modules are being installed. + +QuickStart +========== +The quick start guide will show you how to setup a simple application using node.js and MongoDB. Its scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. + +Create the package.json file +---------------------------- +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project + +``` +npm init +``` + +Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` + +``` +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb": "~2.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +Connecting to MongoDB +--------------------- +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server and the database **myproject**. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + db.close(); +}); +``` + +Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. + +Let's Add some code to show the different CRUD operations available. + +Inserting a Document +-------------------- +Let's create a function that will insert some documents for us. + +```js +var insertDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the document collection"); + callback(result); + }); +} +``` + +The insert command will return a results object that contains several fields that might be useful. + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + db.close(); + }); +}); +``` + +We can now run the update **app.js** file. + +``` +node app.js +``` + +You should see the following output after running the **app.js** file. + +``` +Connected correctly to server +Inserted 3 documents into the document collection +``` + +Updating a document +------------------- +Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. + +```js +var updateDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + db.close(); + }); + }); +}); +``` + +Delete a document +----------------- +Next lets delete the document where the field **a** equals to **3**. + +```js +var deleteDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +This will delete the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient +.connect** callback function. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + deleteDocument(db, function() { + db.close(); + }); + }); + }); +}); +``` + +Finally let's retrieve all the documents using a simple find. + +Find All Documents +------------------ +We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. + +```js +var findDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + assert.equal(2, docs.length); + console.log("Found the following records"); + console.dir(docs); + callback(docs); + }); +} +``` + +This query will return all the documents in the **documents** collection. Since we deleted a document the total +documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + deleteDocument(db, function() { + findDocuments(db, function() { + db.close(); + }); + }); + }); + }); +}); +``` + +This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org/) + * [Read about Schemas](http://learnmongodbthehardway.com/) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/THIRD-PARTY-NOTICES b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/THIRD-PARTY-NOTICES new file mode 100644 index 00000000..c13e5d9a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/THIRD-PARTY-NOTICES @@ -0,0 +1,41 @@ +Mongodb-core uses third-party libraries or other resources that may +be distributed under licenses different than the Mongodb-core software. + +In the event that we accidentally failed to list a required notice, +please bring it to our attention through any of the ways detailed here: + + mongodb-dev@googlegroups.com + +The attached notices are provided for information only. + +For any licenses that require disclosure of source, sources are available at +https://github.com/mongodb/node-mongodb-native. + +1) License Notice for nan.h +--------------------------- + +The MIT License (MIT) +===================== + +Copyright (c) 2016 NAN contributors +----------------------------------- + +NAN contributors listed at <https://github.com/nodejs/nan#contributors> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to +do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/boot_auth.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/boot_auth.js new file mode 100644 index 00000000..95956c7a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/boot_auth.js @@ -0,0 +1,52 @@ +var ReplSetManager = require('mongodb-topology-manager').ReplSet, + f = require('util').format; + +var rsOptions = { + server: { + keyFile: __dirname + '/test/functional/data/keyfile.txt', + auth: null, + replSet: 'rs' + }, + client: { + replSet: 'rs' + } +} + +// Set up the nodes +var nodes = [{ + options: { + bind_ip: 'localhost', port: 31000, + dbpath: f('%s/../db/31000', __dirname), + } +}, { + options: { + bind_ip: 'localhost', port: 31001, + dbpath: f('%s/../db/31001', __dirname), + } +}, { + options: { + bind_ip: 'localhost', port: 31002, + dbpath: f('%s/../db/31002', __dirname), + } +}] + +// Merge in any node start up options +for(var i = 0; i < nodes.length; i++) { + for(var name in rsOptions.server) { + nodes[i].options[name] = rsOptions.server[name]; + } +} + +// Create a manager +var replicasetManager = new ReplSetManager('mongod', nodes, rsOptions.client); +// Purge the set +replicasetManager.purge().then(function() { + // Start the server + replicasetManager.start().then(function() { + process.exit(0); + }).catch(function(e) { + console.log("====== ") + console.dir(e) + // // console.dir(e); + }); +}); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/conf.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/conf.json new file mode 100644 index 00000000..aba0b7a3 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/conf.json @@ -0,0 +1,73 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/functional/operation_example_tests.js", + "test/functional/operation_promises_example_tests.js", + "test/functional/operation_generators_example_tests.js", + "test/functional/authentication_tests.js", + "test/functional/gridfs_stream_tests.js", + "lib/admin.js", + "lib/collection.js", + "lib/cursor.js", + "lib/aggregation_cursor.js", + "lib/command_cursor.js", + "lib/db.js", + "lib/mongo_client.js", + "lib/mongos.js", + "lib/read_preference.js", + "lib/replset.js", + "lib/server.js", + "lib/bulk/common.js", + "lib/bulk/ordered.js", + "lib/bulk/unordered.js", + "lib/gridfs/grid_store.js", + "node_modules/mongodb-core/lib/error.js", + "lib/gridfs-stream/index.js", + "lib/gridfs-stream/download.js", + "lib/gridfs-stream/upload.js", + "node_modules/mongodb-core/lib/connection/logger.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/index.js new file mode 100644 index 00000000..5808750f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/index.js @@ -0,0 +1,55 @@ +// Core module +var core = require('mongodb-core'), + Instrumentation = require('./lib/apm'); + +// Set up the connect function +var connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; + +// Actual driver classes exported +connect.Admin = require('./lib/admin'); +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/server'); +connect.ReplSet = require('./lib/replset'); +connect.Mongos = require('./lib/mongos'); +connect.ReadPreference = require('./lib/read_preference'); +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.Cursor = require('./lib/cursor'); +connect.GridFSBucket = require('./lib/gridfs-stream'); +// Exported to be used in tests not to be used anywhere else +connect.CoreServer = require('mongodb-core').Server; +connect.CoreConnection = require('mongodb-core').Connection; + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.Map = core.BSON.Map; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Int32 = core.BSON.Int32; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; +connect.Decimal128 = core.BSON.Decimal128; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + return new Instrumentation(core, options, callback); +} + +// Set our exports to be the connect function +module.exports = connect; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/insert_bench.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/insert_bench.js new file mode 100644 index 00000000..5c4d0b9e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/insert_bench.js @@ -0,0 +1,231 @@ +var MongoClient = require('./').MongoClient, + assert = require('assert'); + +// var memwatch = require('memwatch-next'); +// memwatch.on('leak', function(info) { +// console.log("======== leak") +// }); +// +// memwatch.on('stats', function(stats) { +// console.log("======== stats") +// console.dir(stats) +// }); + +// // Take first snapshot +// var hd = new memwatch.HeapDiff(); + +MongoClient.connect('mongodb://localhost:27017/bench', function(err, db) { + var docs = []; + var total = 1000; + var count = total; + var measurements = []; + + // Insert a bunch of documents + for(var i = 0; i < 100; i++) { + docs.push(JSON.parse(data)); + } + + var col = db.collection('inserts'); + + function execute(col, callback) { + var start = new Date().getTime(); + + col.find({}).limit(100).toArray(function(e, docs) { + measurements.push(new Date().getTime() - start); + assert.equal(null, e); + callback(); + }); + } + + console.log("== insert documents") + col.insert(docs, function(e, r) { + docs = []; + assert.equal(null, e); + + console.log("== start bench") + for(var i = 0; i < total; i++) { + execute(col, function(e) { + count = count - 1; + + if(count == 0) { + // Calculate total execution time for operations + var totalTime = measurements.reduce(function(prev, curr) { + return prev + curr; + }, 0); + + console.log("==========================================="); + console.log("total time: " + totalTime) + + // var diff = hd.end(); + // console.log("==========================================="); + // console.log(JSON.stringify(diff, null, 2)) + + db.close(); + process.exit(0) + } + }); + } + }); +}); + +var data = JSON.stringify({ + "data": [ + { + "_id": 1, + "x": 11 + }, + { + "_id": 2, + "x": 22 + }, + { + "_id": 3, + "x": 33 + } + ], + "collection_name": "test", + "database_name": "command-monitoring-tests", + "tests": [ + { + "description": "A successful mixed bulk write", + "operation": { + "name": "bulkWrite", + "arguments": { + "requests": [ + { + "insertOne": { + "document": { + "_id": 4, + "x": 44 + } + } + }, + { + "updateOne": { + "filter": { + "_id": 3 + }, + "update": { + "set": { + "x": 333 + } + } + } + } + ] + } + }, + "expectations": [ + { + "command_started_event": { + "command": { + "insert": "test", + "documents": [ + { + "_id": 4, + "x": 44 + } + ], + "ordered": true + }, + "command_name": "insert", + "database_name": "command-monitoring-tests" + } + }, + { + "command_succeeded_event": { + "reply": { + "ok": 1.0, + "n": 1 + }, + "command_name": "insert" + } + }, + { + "command_started_event": { + "command": { + "update": "test", + "updates": [ + { + "q": { + "_id": 3 + }, + "u": { + "set": { + "x": 333 + } + }, + "upsert": false, + "multi": false + } + ], + "ordered": true + }, + "command_name": "update", + "database_name": "command-monitoring-tests" + } + }, + { + "command_succeeded_event": { + "reply": { + "ok": 1.0, + "n": 1 + }, + "command_name": "update" + } + } + ] + }, + { + "description": "A successful unordered bulk write with an unacknowledged write concern", + "operation": { + "name": "bulkWrite", + "arguments": { + "requests": [ + { + "insertOne": { + "document": { + "_id": 4, + "x": 44 + } + } + } + ], + "ordered": false, + "writeConcern": { + "w": 0 + } + } + }, + "expectations": [ + { + "command_started_event": { + "command": { + "insert": "test", + "documents": [ + { + "_id": 4, + "x": 44 + } + ], + "ordered": false, + "writeConcern": { + "w": 0 + } + }, + "command_name": "insert", + "database_name": "command-monitoring-tests" + } + }, + { + "command_succeeded_event": { + "reply": { + "ok": 1.0 + }, + "command_name": "insert" + } + } + ] + } + ] +}); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/admin.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/admin.js new file mode 100644 index 00000000..1a16bcb6 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/admin.js @@ -0,0 +1,576 @@ +"use strict"; + +var toError = require('./utils').toError, + Define = require('./metadata'), + shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Use the admin database for the operation + * var adminDb = db.admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +var Admin = function(db, topology, promiseLibrary) { + if(!(this instanceof Admin)) return new Admin(db, topology); + + // Internal state + this.s = { + db: db + , topology: topology + , promiseLibrary: promiseLibrary + } +} + +var define = Admin.define = new Define('Admin', Admin, false); + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) { + return callback != null ? callback(err, doc) : null; + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand(command, options, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.serverInfo(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.serverInfo(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('buildInfo', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err != null) return callback(err, null); + callback(null, doc); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('serverInfo', {callback: true, promise:true}); + +/** + * Retrieve this db's server status. + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return serverStatus(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + serverStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var serverStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { + if(err == null && doc.ok === 1) { + callback(null, doc); + } else { + if(err) return callback(err, false); + return callback(toError(doc), false); + } + }); +} + +define.classMethod('serverStatus', {callback: true, promise:true}); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingLevel = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingLevel(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingLevel(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingLevel = function(self, callback) { + self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { + if(err == null && doc.ok === 1) { + var was = doc.was; + if(was == 0) return callback(null, "off"); + if(was == 1) return callback(null, "slow_only"); + if(was == 2) return callback(null, "all"); + return callback(new Error("Error: illegal profiling level value " + was), null); + } else { + err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + } + }); +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('ping', {callback: true, promise:true}); + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.authenticate = function(username, password, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options); + options.authdb = 'admin'; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.authenticate(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.authenticate(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.logout = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.logout({dbName: 'admin'}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.logout({dbName: 'admin'}, function(err) { + if(err) return reject(err); + resolve(true); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Get write concern +var writeConcern = function(options, db) { + options = shallowClone(options); + + // If options already contain write concerns return it + if(options.w || options.wtimeout || options.j || options.fsync) { + return options; + } + + // Set db write concern if available + if(db.writeConcern) { + if(options.w) options.w = db.writeConcern.w; + if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; + if(options.j) options.j = db.writeConcern.j; + if(options.fsync) options.fsync = db.writeConcern.fsync; + } + + // Return modified options + return options; +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name to admin + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.addUser(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.addUser(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('addUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.removeUser(username, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.removeUser(username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.setProfilingLevel = function(level, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return setProfilingLevel(self, level, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + setProfilingLevel(self, level, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var setProfilingLevel = function(self, level, callback) { + var command = {}; + var profile = 0; + + if(level == "off") { + profile = 0; + } else if(level == "slow_only") { + profile = 1; + } else if(level == "all") { + profile = 2; + } else { + return callback(new Error("Error: illegal profiling level value " + level)); + } + + // Set up the profile number + command['profile'] = profile; + + self.s.db.executeDbAdminCommand(command, function(err, doc) { + if(err == null && doc.ok === 1) + return callback(null, level); + return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + }); +} + +define.classMethod('setProfilingLevel', {callback: true, promise:true}); + +/** + * Retrive the current profiling information for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingInfo = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingInfo(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingInfo(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingInfo = function(self, callback) { + try { + self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options=null] Optional settings. + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') + return validateCollection(self, collectionName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + validateCollection(self, collectionName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var validateCollection = function(self, collectionName, options, callback) { + var command = {validate: collectionName}; + var keys = Object.keys(options); + + // Decorate command with extra options + for(var i = 0; i < keys.length; i++) { + if(options.hasOwnProperty(keys[i])) { + command[keys[i]] = options[keys[i]]; + } + } + + self.s.db.command(command, function(err, doc) { + if(err != null) return callback(err, null); + + if(doc.ok === 0) + return callback(new Error("Error with validate command"), null); + if(doc.result != null && doc.result.constructor != String) + return callback(new Error("Error with validation data"), null); + if(doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error("Error: invalid collection " + collectionName), null); + if(doc.valid != null && !doc.valid) + return callback(new Error("Error: invalid collection " + collectionName), null); + + return callback(null, doc); + }); +} + +define.classMethod('validateCollection', {callback: true, promise:true}); + +/** + * List the available databases + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('listDatabases', {callback: true, promise:true}); + +/** + * Get ReplicaSet status + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return replSetGetStatus(self, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replSetGetStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var replSetGetStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { + if(err == null && doc.ok === 1) + return callback(null, doc); + if(err) return callback(err, false); + callback(toError(doc), false); + }); +} + +define.classMethod('replSetGetStatus', {callback: true, promise:true}); + +module.exports = Admin; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/aggregation_cursor.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 00000000..0448cb06 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,429 @@ +"use strict"; + +var inherits = require('util').inherits + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor'); + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var state = AggregationCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(AggregationCursor, Readable); + +// Extend the Cursor +for(var name in CoreCursor.prototype) { + AggregationCursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {AggregationCursor} + */ +AggregationCursor.prototype.batchSize = function(value) { + if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true }); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.geoNear = function(document) { + this.s.cmd.pipeline.push({$geoNear: document}); + return this; +} + +define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.group = function(document) { + this.s.cmd.pipeline.push({$group: document}); + return this; +} + +define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.limit = function(value) { + this.s.cmd.pipeline.push({$limit: value}); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.match = function(document) { + this.s.cmd.pipeline.push({$match: document}); + return this; +} + +define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.out = function(destination) { + this.s.cmd.pipeline.push({$out: destination}); + return this; +} + +define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.project = function(document) { + this.s.cmd.pipeline.push({$project: document}); + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a lookup stage to the aggregation pipeline + * @method + * @param {object} document The lookup stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.lookup = function(document) { + this.s.cmd.pipeline.push({$lookup: document}); + return this; +} + +define.classMethod('lookup', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.redact = function(document) { + this.s.cmd.pipeline.push({$redact: document}); + return this; +} + +define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.skip = function(value) { + this.s.cmd.pipeline.push({$skip: value}); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.sort = function(document) { + this.s.cmd.pipeline.push({$sort: document}); + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.unwind = function(field) { + this.s.cmd.pipeline.push({$unwind: field}); + return this; +} + +define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); + +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method AggregationCursor.prototype.each + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +AggregationCursor.INIT = 0; +AggregationCursor.OPEN = 1; +AggregationCursor.CLOSED = 2; + +module.exports = AggregationCursor; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/apm.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/apm.js new file mode 100644 index 00000000..ad912e25 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/apm.js @@ -0,0 +1,594 @@ +var EventEmitter = require('events').EventEmitter, + inherits = require('util').inherits; + +// Get prototypes +var AggregationCursor = require('./aggregation_cursor'), + CommandCursor = require('./command_cursor'), + OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, + UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, + GridStore = require('./gridfs/grid_store'), + Cursor = require('./cursor'), + Collection = require('./collection'), + Db = require('./db'); + +var basicOperationIdGenerator = { + operationId: 1, + + next: function() { + return this.operationId++; + } +} + +var basicTimestampGenerator = { + current: function() { + return new Date().getTime(); + }, + + duration: function(start, end) { + return end - start; + } +} + +var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce', + 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb']; + +var Instrumentation = function(core, options, callback) { + options = options || {}; + + // Optional id generators + var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; + // Optional timestamp generator + var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; + // Extend with event emitter functionality + EventEmitter.call(this); + + // Contains all the instrumentation overloads + this.overloads = []; + + // --------------------------------------------------------- + // + // Instrument prototype + // + // --------------------------------------------------------- + + var instrumentPrototype = function(callback) { + var instrumentations = [] + + // Classes to support + var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation, + CommandCursor, AggregationCursor, Cursor, Collection, Db]; + + // Add instrumentations to the available list + for(var i = 0; i < classes.length; i++) { + if(classes[i].define) { + instrumentations.push(classes[i].define.generate()); + } + } + + // Return the list of instrumentation points + callback(null, instrumentations); + } + + // Did the user want to instrument the prototype + if(typeof callback == 'function') { + instrumentPrototype(callback); + } + + // --------------------------------------------------------- + // + // Server + // + // --------------------------------------------------------- + + // Reference + var self = this; + // Names of methods we need to wrap + var methods = ['command', 'insert', 'update', 'remove']; + // Prototype + var proto = core.Server.prototype; + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var requestId = core.Query.nextRequestId(); + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + var ns = args[0]; + var commandObj = args[1]; + var options = args[2] || {}; + var keys = Object.keys(commandObj); + var commandName = keys[0]; + var db = ns.split('.')[0]; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Do we have a legacy insert/update/remove command + if(x == 'insert') { //} && !this.lastIsMaster().maxWireVersion) { + commandName = 'insert'; + + // Re-write the command + commandObj = { + insert: col, documents: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'update') { // && !this.lastIsMaster().maxWireVersion) { + commandName = 'update'; + + // Re-write the command + commandObj = { + update: col, updates: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'remove') { //&& !this.lastIsMaster().maxWireVersion) { + commandName = 'delete'; + + // Re-write the command + commandObj = { + delete: col, deletes: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } + + // Get the callback + var callback = args.pop(); + // Set current callback operation id from the current context or create + // a new one + var ourOpId = callback.operationId || operationIdGenerator.next(); + + // Get a connection reference for this server instance + var connection = this.s.pool.get() + + // Emit the start event for the command + var command = { + // Returns the command. + command: commandObj, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: ourOpId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connection + }; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.commandObj = {}; + command.commandObj[commandName] = true; + } + + // Emit the started event + self.emit('started', command) + + // Start time + var startTime = timestampGenerator.current(); + + // Push our handler callback + args.push(function(err, r) { + var endTime = timestampGenerator.current(); + var command = { + duration: timestampGenerator.duration(startTime, endTime), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: connection + }; + + // If we have an error + if(err || (r && r.result && r.result.ok == 0)) { + command.failure = err || r.result.writeErrors || r.result; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.failure = {}; + } + + self.emit('failed', command); + } else if(commandObj && commandObj.writeConcern + && commandObj.writeConcern.w == 0) { + // If we have write concern 0 + command.reply = {ok:1}; + self.emit('succeeded', command); + } else { + command.reply = r && r.result ? r.result : r; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase()) != -1) { + command.reply = {}; + } + + self.emit('succeeded', command); + } + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } + }); + + // --------------------------------------------------------- + // + // Bulk Operations + // + // --------------------------------------------------------- + + // Inject ourselves into the Bulk methods + methods = ['execute']; + var prototypes = [ + require('./bulk/ordered').Bulk.prototype, + require('./bulk/unordered').Bulk.prototype + ] + + prototypes.forEach(function(proto) { + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + // Set an operation Id on the bulk object + this.operationId = operationIdGenerator.next(); + + // Get the callback + var callback = args.pop(); + // If we have a callback use this + if(typeof callback == 'function') { + args.push(function(err, r) { + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + return func.apply(this, args); + } + } + }); + }); + + // --------------------------------------------------------- + // + // Cursor + // + // --------------------------------------------------------- + + // Inject ourselves into the Cursor methods + methods = ['_find', '_getmore', '_killcursor']; + prototypes = [ + require('./cursor').prototype, + require('./command_cursor').prototype, + require('./aggregation_cursor').prototype + ] + + // Command name translation + var commandTranslation = { + '_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain' + } + + prototypes.forEach(function(proto) { + + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var cursor = this; + var requestId = core.Query.nextRequestId(); + var ourOpId = operationIdGenerator.next(); + var parts = this.ns.split('.'); + var db = parts[0]; + + // Get the collection + parts.shift(); + var collection = parts.join('.'); + + // Set the command + var command = this.query; + var cmd = this.s.cmd; + + // If we have a find method, set the operationId on the cursor + if(x == '_find') { + cursor.operationId = ourOpId; + } + + // Do we have a find command rewrite it + if(x == '_getmore') { + command = { + getMore: this.cursorState.cursorId, + collection: collection, + batchSize: cmd.batchSize + } + + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + } else if(x == '_killcursor') { + command = { + killCursors: collection, + cursors: [this.cursorState.cursorId] + } + } else if(cmd.find) { + command = { + find: collection, filter: cmd.query + } + + if(cmd.sort) command.sort = cmd.sort; + if(cmd.fields) command.projection = cmd.fields; + if(cmd.limit && cmd.limit < 0) { + command.limit = Math.abs(cmd.limit); + command.singleBatch = true; + } else if(cmd.limit) { + command.limit = Math.abs(cmd.limit); + } + + // Options + if(cmd.skip) command.skip = cmd.skip; + if(cmd.hint) command.hint = cmd.hint; + if(cmd.batchSize) command.batchSize = cmd.batchSize; + if(typeof cmd.returnKey == 'boolean') command.returnKey = cmd.returnKey; + if(cmd.comment) command.comment = cmd.comment; + if(cmd.min) command.min = cmd.min; + if(cmd.max) command.max = cmd.max; + if(cmd.maxScan) command.maxScan = cmd.maxScan; + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + + // Flags + if(typeof cmd.awaitData == 'boolean') command.awaitData = cmd.awaitData; + if(typeof cmd.snapshot == 'boolean') command.snapshot = cmd.snapshot; + if(typeof cmd.tailable == 'boolean') command.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') command.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') command.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.partial == 'boolean') command.partial = cmd.partial; + if(typeof cmd.showDiskLoc == 'boolean') command.showRecordId = cmd.showDiskLoc; + + // Read Concern + if(cmd.readConcern) command.readConcern = cmd.readConcern; + + // Override method + if(cmd.explain) command.explain = cmd.explain; + if(cmd.exhaust) command.exhaust = cmd.exhaust; + + // If we have a explain flag + if(cmd.explain) { + // Create fake explain command + command = { + explain: command, + verbosity: 'allPlansExecution' + } + + // Set readConcern on the command if available + if(cmd.readConcern) command.readConcern = cmd.readConcern + + // Set up the _explain name for the command + x = '_explain'; + } + } else { + command = cmd; + } + + // Set up the connection + var connectionId = null; + + // Set local connection + if(this.connection) connectionId = this.connection; + if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection(); + + // Get the command Name + var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x]; + + // Emit the start event for the command + command = { + // Returns the command. + command: command, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: this.operationId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connectionId + }; + + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + + // Get the callback + var callback = args.pop(); + + // We do not have a callback but a Promise + if(typeof callback == 'function' || command.commandName == 'killCursors') { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + + // Emit succeeded event with killcursor if we have a legacy protocol + if(command.commandName == 'killCursors' + && this.server.lastIsMaster() + && this.server.lastIsMaster().maxWireVersion < 4) { + // Emit the succeeded command + command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: [{ok:1}] + }; + + // Apply callback to the list of args + args.push(callback); + // Apply the call + func.apply(this, args); + // Emit the command + return self.emit('succeeded', command) + } + + // Add our callback handler + args.push(function(err, r) { + if(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + } else { + // Do we have a getMore + if(commandName.toLowerCase() == 'getmore' && r == null) { + r = { + cursor: { + id: cursor.cursorState.cursorId, + ns: cursor.ns, + nextBatch: cursor.cursorState.documents + }, ok:1 + } + } else if(commandName.toLowerCase() == 'find' && r == null) { + r = { + cursor: { + id: cursor.cursorState.cursorId, + ns: cursor.ns, + firstBatch: cursor.cursorState.documents + }, ok:1 + } + } else if(commandName.toLowerCase() == 'killcursors' && r == null) { + r = { + cursorsUnknown:[cursor.cursorState.lastCursorId], + ok:1 + } + } + + // cursor id is zero, we can issue success command + command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: r && r.result ? r.result : r + }; + + // Emit the command + self.emit('succeeded', command) + } + + // Return + if(!callback) return; + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + // Assume promise, push back the missing value + args.push(callback); + // Get the promise + var promise = func.apply(this, args); + // Return a new promise + return new cursor.s.promiseLibrary(function(resolve, reject) { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + // Execute the function + promise.then(function() { + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: cursor.cursorState.documents + }; + + // Emit the command + self.emit('succeeded', command) + }).catch(function(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + // reject the promise + reject(err); + }); + }); + } + } + }); + }); +} + +inherits(Instrumentation, EventEmitter); + +Instrumentation.prototype.uninstrument = function() { + for(var i = 0; i < this.overloads.length; i++) { + var obj = this.overloads[i]; + obj.proto[obj.name] = obj.func; + } + + // Remove all listeners + this.removeAllListeners('started'); + this.removeAllListeners('succeeded'); + this.removeAllListeners('failed'); +} + +module.exports = Instrumentation; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/common.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 00000000..ce90174e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,439 @@ +"use strict"; + +var Long = require('mongodb-core').BSON.Long, + Timestamp = require('mongodb-core').BSON.Timestamp; + +// Error codes +var UNKNOWN_ERROR = 8; +var INVALID_BSON_ERROR = 22; +var WRITE_CONCERN_ERROR = 64; +var MULTIPLE_ERROR = 65; + +// Insert types +var INSERT = 1; +var UPDATE = 2; +var REMOVE = 3 + + +// Get write concern +var writeConcern = function(target, col, options) { + var writeConcern = {}; + + // Collection level write concern + if(col.writeConcern && col.writeConcern.w != null) writeConcern.w = col.writeConcern.w; + if(col.writeConcern && col.writeConcern.j != null) writeConcern.j = col.writeConcern.j; + if(col.writeConcern && col.writeConcern.fsync != null) writeConcern.fsync = col.writeConcern.fsync; + if(col.writeConcern && col.writeConcern.wtimeout != null) writeConcern.wtimeout = col.writeConcern.wtimeout; + + // Options level write concern + if(options && options.w != null) writeConcern.w = options.w; + if(options && options.wtimeout != null) writeConcern.wtimeout = options.wtimeout; + if(options && options.j != null) writeConcern.j = options.j; + if(options && options.fsync != null) writeConcern.fsync = options.fsync; + + // Return write concern + return writeConcern; +} + +/** + * Helper function to define properties + * @ignore + */ +var defineReadOnlyProperty = function(self, name, value) { + Object.defineProperty(self, name, { + enumerable: true + , get: function() { + return value; + } + }); +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +var Batch = function(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; +} + +/** + * Wraps a legacy operation so we can correctly rewrite it's error + * @ignore + */ +var LegacyOp = function(batchType, operation, index) { + this.batchType = batchType; + this.index = index; + this.operation = operation; +} + +/** + * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {boolean} ok Did bulk operation correctly execute + * @property {number} nInserted number of inserted documents + * @property {number} nUpdated number of documents updated logically + * @property {number} nUpserted Number of upserted documents + * @property {number} nModified Number of documents updated physically on disk + * @property {number} nRemoved Number of removed documents + * @return {BulkWriteResult} a BulkWriteResult instance + */ +var BulkWriteResult = function(bulkResult) { + defineReadOnlyProperty(this, "ok", bulkResult.ok); + defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted); + defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted); + defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched); + defineReadOnlyProperty(this, "nModified", bulkResult.nModified); + defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved); + + /** + * Return an array of inserted ids + * + * @return {object[]} + */ + this.getInsertedIds = function() { + return bulkResult.insertedIds; + } + + /** + * Return an array of upserted ids + * + * @return {object[]} + */ + this.getUpsertedIds = function() { + return bulkResult.upserted; + } + + /** + * Return the upserted id at position x + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + this.getUpsertedIdAt = function(index) { + return bulkResult.upserted[index]; + } + + /** + * Return raw internal result + * + * @return {object} + */ + this.getRawResponse = function() { + return bulkResult; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + this.hasWriteErrors = function() { + return bulkResult.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + this.getWriteErrorCount = function() { + return bulkResult.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @return {WriteError} + */ + this.getWriteErrorAt = function(index) { + if(index < bulkResult.writeErrors.length) { + return bulkResult.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {object[]} + */ + this.getWriteErrors = function() { + return bulkResult.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + this.getLastOp = function() { + return bulkResult.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + this.getWriteConcernError = function() { + if(bulkResult.writeConcernErrors.length == 0) { + return null; + } else if(bulkResult.writeConcernErrors.length == 1) { + // Return the error + return bulkResult.writeConcernErrors[0]; + } else { + + // Combine the errors + var errmsg = ""; + for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) { + var err = bulkResult.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if(i == 0) errmsg = errmsg + " and "; + } + + return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR }); + } + } + + this.toJSON = function() { + return bulkResult; + } + + this.toString = function() { + return "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; + } + + this.isOk = function() { + return bulkResult.ok == 1; + } +} + +/** + * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +var WriteConcernError = function(err) { + if(!(this instanceof WriteConcernError)) return new WriteConcernError(err); + + // Define properties + defineReadOnlyProperty(this, "code", err.code); + defineReadOnlyProperty(this, "errmsg", err.errmsg); + + this.toJSON = function() { + return {code: err.code, errmsg: err.errmsg}; + } + + this.toString = function() { + return "WriteConcernError(" + err.errmsg + ")"; + } +} + +/** + * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {number} index Write concern error original bulk operation index. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +var WriteError = function(err) { + if(!(this instanceof WriteError)) return new WriteError(err); + + // Define properties + defineReadOnlyProperty(this, "code", err.code); + defineReadOnlyProperty(this, "index", err.index); + defineReadOnlyProperty(this, "errmsg", err.errmsg); + + // + // Define access methods + this.getOperation = function() { + return err.op; + } + + this.toJSON = function() { + return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op}; + } + + this.toString = function() { + return "WriteError(" + JSON.stringify(this.toJSON()) + ")"; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if(err) { + result = err; + } else if(result && result.result) { + result = result.result; + } else if(result == null) { + return; + } + + // Do we have a top level error stop processing and return + if(result.ok == 0 && bulkResult.ok == 1) { + bulkResult.ok = 0; + + var writeError = { + index: 0 + , code: result.code || 0 + , errmsg: result.message + , op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if(result.ok == 0 && bulkResult.ok == 0) { + return; + } + + // Deal with opTime if available + if(result.opTime || result.lastOp) { + var opTime = result.lastOp || result.opTime; + var lastOpTS = null; + var lastOpT = null; + + // We have a time stamp + if(opTime && opTime._bsontype == 'Timestamp') { + if(bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if(opTime.greaterThan(bulkResult.lastOp)) { + bulkResult.lastOp = opTime; + } + } else { + // Existing TS + if(bulkResult.lastOp) { + lastOpTS = typeof bulkResult.lastOp.ts == 'number' + ? Long.fromNumber(bulkResult.lastOp.ts) : bulkResult.lastOp.ts; + lastOpT = typeof bulkResult.lastOp.t == 'number' + ? Long.fromNumber(bulkResult.lastOp.t) : bulkResult.lastOp.t; + } + + // Current OpTime TS + var opTimeTS = typeof opTime.ts == 'number' + ? Long.fromNumber(opTime.ts) : opTime.ts; + var opTimeT = typeof opTime.t == 'number' + ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if(bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if(opTimeTS.greaterThan(lastOpTS)) { + bulkResult.lastOp = opTime; + } else if(opTimeTS.equals(lastOpTS)) { + if(opTimeT.greaterThan(lastOpT)) { + bulkResult.lastOp = opTime; + } + } + } + } + + // If we have an insert Batch type + if(batch.batchType == INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if(batch.batchType == REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + var nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if(Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for(var i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex + , _id: result.upserted[i]._id + }); + } + } else if(result.upserted) { + + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex + , _id: result.upserted + }); + } + + // If we have an update Batch type + if(batch.batchType == UPDATE && result.n) { + var nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if(typeof nModified == 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if(Array.isArray(result.writeErrors)) { + for(i = 0; i < result.writeErrors.length; i++) { + + writeError = { + index: batch.originalZeroIndex + result.writeErrors[i].index + , code: result.writeErrors[i].code + , errmsg: result.writeErrors[i].errmsg + , op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if(result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +// +// Clone the options +var cloneOptions = function(options) { + var clone = {}; + var keys = Object.keys(options); + for(var i = 0; i < keys.length; i++) { + clone[keys[i]] = options[keys[i]]; + } + + return clone; +} + +// Exports symbols +exports.BulkWriteResult = BulkWriteResult; +exports.WriteError = WriteError; +exports.Batch = Batch; +exports.LegacyOp = LegacyOp; +exports.mergeBatchResults = mergeBatchResults; +exports.cloneOptions = cloneOptions; +exports.writeConcern = writeConcern; +exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; +exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; +exports.MULTIPLE_ERROR = MULTIPLE_ERROR; +exports.UNKNOWN_ERROR = UNKNOWN_ERROR; +exports.INSERT = INSERT; +exports.UPDATE = UPDATE; +exports.REMOVE = REMOVE; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/ordered.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 00000000..42ee10e3 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,532 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , handleCallback = require('../utils').handleCallback + , shallowClone = utils.shallowClone + , BulkWriteResult = common.BulkWriteResult + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , BSON = require('mongodb-core').BSON + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +var bson = new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, + BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, + BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]); + +/** + * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. + */ +var FindOperatorsOrdered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +FindOperatorsOrdered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.deleteOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.delete = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; + +// Add to internal list of documents +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = bson.calculateObjectSize(document, { + checkKeys: false, + }); + + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) { + throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + } + + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Reset the current size trackers + _self.s.currentBatchSize = 0; + _self.s.currentBatchSizeBytes = 0; + } else { + // Update current batch size + _self.s.currentBatchSize = _self.s.currentBatchSize + 1; + _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; + } + + if(docType == common.INSERT) { + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentBatch.operations.push(document) + _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Return self + return _self; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +function OrderedBulkOperation(topology, collection, options) { + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + var executed = false; + + // Current item + var currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + var bson = topology.bson; + + // Namespace for the operation + var namespace = collection.collectionName; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize + ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16); + var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize + ? topology.isMasterDoc.maxWriteBatchSize : 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentBatch: null + , currentIndex: 0 + , currentBatchSize: 0 + , currentBatchSizeBytes: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Fundamental error + , err: null + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false); + +OrderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + operation.upsert = op[key].upsert ? true: false; + if(op.collation) operation.collation = op.collation; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + operation = {q: op[key].filter, limit: limit} + if(op.collation) operation.collation = op.collation; + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +OrderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +OrderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsOrdered(this); +} + +Object.defineProperty(OrderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// +// Execute next write command in a chain +var executeCommands = function(self, callback) { + if(self.s.batches.length == 0) { + return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); + } + + // Ordered execution of the command + var batch = self.s.batches.shift(); + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return handleCallback(callback, err); + } + + // If we have and error + if(err) err.ok = 0; + // Merge the results together + var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); + if(mergeResult != null) { + return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); + } + + // If we are ordered and have errors and they are + // not all replication errors terminate the operation + if(self.s.bulkResult.writeErrors.length > 0) { + return handleCallback(callback, toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult)); + } + + // Execute the next command in line + executeCommands(self, callback); + } + + var finalOptions = {ordered: true} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Serialize functions + if(self.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +/** + * The callback format for results + * @callback OrderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {OrderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw new toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else if(_writeConcern && typeof _writeConcern == 'object') { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch) + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') { + return executeCommands(this, callback); + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommands(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeOrderedBulkOp = function(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/unordered.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 00000000..d2f16dce --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,534 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , handleCallback = require('../utils').handleCallback + , shallowClone = utils.shallowClone + , BulkWriteResult = common.BulkWriteResult + , ObjectID = require('mongodb-core').BSON.ObjectID + , BSON = require('mongodb-core').BSON + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +var bson = new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, + BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, + BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]); + +/** + * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. + */ +var FindOperatorsUnordered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.removeOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.remove = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// +// Add to the operations list +// +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = bson.calculateObjectSize(document, { + checkKeys: false, + }); + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Holds the current batch + _self.s.currentBatch = null; + // Get the right type of batch + if(docType == common.INSERT) { + _self.s.currentBatch = _self.s.currentInsertBatch; + } else if(docType == common.UPDATE) { + _self.s.currentBatch = _self.s.currentUpdateBatch; + } else if(docType == common.REMOVE) { + _self.s.currentBatch = _self.s.currentRemoveBatch; + } + + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.operations.push(document); + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Save back the current Batch to the right type + if(docType == common.INSERT) { + _self.s.currentInsertBatch = _self.s.currentBatch; + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } else if(docType == common.UPDATE) { + _self.s.currentUpdateBatch = _self.s.currentBatch; + } else if(docType == common.REMOVE) { + _self.s.currentRemoveBatch = _self.s.currentBatch; + } + + // Update current batch size + _self.s.currentBatch.size = _self.s.currentBatch.size + 1; + _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; + + // Return self + return _self; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +var UnorderedBulkOperation = function(topology, collection, options) { + options = options == null ? {} : options; + + // Get the namesspace for the write operations + var namespace = collection.collectionName; + // Used to mark operation as executed + var executed = false; + + // Current item + // var currentBatch = null; + var currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + var bson = topology.bson; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize + ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16); + var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize + ? topology.isMasterDoc.maxWriteBatchSize : 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentInsertBatch: null + , currentUpdateBatch: null + , currentRemoveBatch: null + , currentBatch: null + , currentIndex: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false); + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +UnorderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsUnordered} + */ +UnorderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsUnordered(this); +} + +Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +UnorderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +// +// Execute the command +var executeBatch = function(self, batch, callback) { + var finalOptions = {ordered: false} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return handleCallback(callback, err); + } + + // If we have and error + if(err) err.ok = 0; + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +// +// Execute all the commands +var executeBatches = function(self, callback) { + var numberOfCommandsToExecute = self.s.batches.length; + // Execute over all the batches + for(var i = 0; i < self.s.batches.length; i++) { + executeBatch(self, self.s.batches[i], function(err) { + // Driver layer error capture it + if(err) error = err; + // Count down the number of commands left to execute + numberOfCommandsToExecute = numberOfCommandsToExecute - 1; + + // Execute + if(numberOfCommandsToExecute == 0) { + // Driver level error + if(error) return handleCallback(callback, error); + // Treat write errors + var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null; + handleCallback(callback, error, new BulkWriteResult(self.s.bulkResult)); + } + }); + } +} + +/** + * The callback format for results + * @callback UnorderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else if(_writeConcern && typeof _writeConcern == 'object') { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') return executeBatches(this, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeBatches(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeUnorderedBulkOp = function(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/collection.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/collection.js new file mode 100644 index 00000000..994c8582 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/collection.js @@ -0,0 +1,3354 @@ +"use strict"; + +var checkCollectionName = require('./utils').checkCollectionName + , ObjectID = require('mongodb-core').BSON.ObjectID + , Long = require('mongodb-core').BSON.Long + , Code = require('mongodb-core').BSON.Code + , f = require('util').format + , AggregationCursor = require('./aggregation_cursor') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone + , isObject = require('./utils').isObject + , toError = require('./utils').toError + , normalizeHintField = require('./utils').normalizeHintField + , handleCallback = require('./utils').handleCallback + , decorateCommand = require('./utils').decorateCommand + , formattedOrderClause = require('./utils').formattedOrderClause + , ReadPreference = require('./read_preference') + , CoreReadPreference = require('mongodb-core').ReadPreference + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Cursor = require('./cursor') + , unordered = require('./bulk/unordered') + , ordered = require('./bulk/ordered') + , assign = require('./utils').assign; + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +var Collection = function(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + + // Unpack variables + var internalHint = null; + var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + var serializeFunctions = options == null || options.serializeFunctions == null ? db.s.options.serializeFunctions : options.serializeFunctions; + var raw = options == null || options.raw == null ? db.s.options.raw : options.raw; + var promoteLongs = options == null || options.promoteLongs == null ? db.s.options.promoteLongs : options.promoteLongs; + var promoteValues = options == null || options.promoteValues == null ? db.s.options.promoteValues : options.promoteValues; + var promoteBuffers = options == null || options.promoteBuffers == null ? db.s.options.promoteBuffers : options.promoteBuffers; + var readPreference = null; + var collectionHint = null; + var namespace = f("%s.%s", dbName, name); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Assign the right collection level readPreference + if(options && options.readPreference) { + readPreference = options.readPreference; + } else if(db.options.readPreference) { + readPreference = db.options.readPreference; + } + + // Set custom primary key factory if provided + pkFactory = pkFactory == null + ? ObjectID + : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory + // Db + , db: db + // Topology + , topology: topology + // dbName + , dbName: dbName + // Options + , options: options + // Namespace + , namespace: namespace + // Read preference + , readPreference: readPreference + // SlaveOK + , slaveOk: slaveOk + // Serialize functions + , serializeFunctions: serializeFunctions + // Raw + , raw: raw + // promoteLongs + , promoteLongs: promoteLongs + // promoteValues + , promoteValues: promoteValues + // promoteBuffers + , promoteBuffers: promoteBuffers + // internalHint + , internalHint: internalHint + // collectionHint + , collectionHint: collectionHint + // Name + , name: name + // Promise library + , promiseLibrary: promiseLibrary + // Read Concern + , readConcern: options.readConcern + } +} + +var define = Collection.define = new Define('Collection', Collection, false); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, get: function() { return this.s.name; } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, get: function() { return this.s.namespace; } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(this.s.options.w != null) ops.w = this.s.options.w; + if(this.s.options.j != null) ops.j = this.s.options.j; + if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, "hint", { + enumerable: true + , get: function () { return this.s.collectionHint; } + , set: function (v) { this.s.collectionHint = normalizeHintField(v); } +}); + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} query The cursor query object. + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = function() { + var options + , args = Array.prototype.slice.call(arguments, 0) + , has_callback = typeof args[args.length - 1] === 'function' + , has_weird_callback = typeof args[0] === 'function' + , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) + , len = args.length + , selector = len >= 1 ? args[0] : {} + , fields = len >= 2 ? args[1] : undefined; + + if(len === 1 && has_weird_callback) { + // backwards compat for callback?, options case + selector = {}; + options = args[0]; + } + + if(len === 2 && fields !== undefined && !Array.isArray(fields)) { + var fieldKeys = Object.keys(fields); + var is_option = false; + + for(var i = 0; i < fieldKeys.length; i++) { + if(testForFields[fieldKeys[i]] != null) { + is_option = true; + break; + } + } + + if(is_option) { + options = fields; + fields = undefined; + } else { + options = {}; + } + } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { + var newFields = {}; + // Rewrite the array + for(i = 0; i < fields.length; i++) { + newFields[fields[i]] = 1; + } + // Set the fields + fields = newFields; + } + + if(3 === len) { + options = args[2]; + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + var object = selector; + if(Buffer.isBuffer(object)) { + var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; + if(object_size != object.length) { + var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); + error.name = 'MongoError'; + throw error; + } + } + + // Validate correctness of the field selector + object = fields; + if(Buffer.isBuffer(object)) { + object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; + if(object_size != object.length) { + error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if(selector != null && selector._bsontype == 'ObjectID') { + selector = {_id:selector}; + } + + // If it's a serialized fields field we need to just let it through + // user be warned it better be good + if(options && options.fields && !(Buffer.isBuffer(options.fields))) { + fields = {}; + + if(Array.isArray(options.fields)) { + if(!options.fields.length) { + fields['_id'] = 1; + } else { + var l = options.fields.length; + + for (i = 0; i < l; i++) { + fields[options.fields[i]] = 1; + } + } + } else { + fields = options.fields; + } + } + + if (!options) options = {}; + + var newOptions = {}; + // Make a shallow copy of options + for (var key in options) { + newOptions[key] = options[key]; + } + + // Unpack options + newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; + newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; + newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions = getReadPreference(this, newOptions, this.s.db, this); + + // Set slave ok to true if read preference different from primary + if(newOptions.readPreference != null + && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if(selector != null && typeof selector != 'object') { + throw MongoError.create({message: "query selector must be an object", driver:true }); + } + + // Build the find command + var findCommand = { + find: this.s.namespace + , limit: newOptions.limit + , skip: newOptions.skip + , query: selector + } + + // Ensure we use the right await data option + if(typeof newOptions.awaitdata == 'boolean') { + newOptions.awaitData = newOptions.awaitdata + } + + // Translate to new command option noCursorTimeout + if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + // Merge in options to command + for(var name in newOptions) { + if(newOptions[name] != null) findCommand[name] = newOptions[name]; + } + + // Format the fields + var formatFields = function(fields) { + var object = {}; + if(Array.isArray(fields)) { + for(var i = 0; i < fields.length; i++) { + if(Array.isArray(fields[i])) { + object[fields[i][0]] = fields[i][1]; + } else { + object[fields[i][0]] = 1; + } + } + } else { + object = fields; + } + + return object; + } + + // Special treatment for the fields selector + if(fields) findCommand.fields = formatFields(fields); + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if(newOptions.raw == null && typeof this.s.raw == 'boolean') newOptions.raw = this.s.raw; + // Set promoteLongs if available at collection level + if(newOptions.promoteLongs == null && typeof this.s.promoteLongs == 'boolean') newOptions.promoteLongs = this.s.promoteLongs; + if(newOptions.promoteValues == null && typeof this.s.promoteValues == 'boolean') newOptions.promoteValues = this.s.promoteValues; + if(newOptions.promoteBuffers == null && typeof this.s.promoteBuffers == 'boolean') newOptions.promoteBuffers = this.s.promoteBuffers; + + // Sort options + if(findCommand.sort) { + findCommand.sort = formattedOrderClause(findCommand.sort); + } + + // Set the readConcern + if(this.s.readConcern) { + findCommand.readConcern = this.s.readConcern; + } + + // Decorate find command with collation options + decorateWithCollation(findCommand, this, options); + + // Create the cursor + if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); + return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); +} + +define.classMethod('find', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object} doc Document to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + if(Array.isArray(doc) && typeof callback == 'function') { + return callback(MongoError.create({message: 'doc parameter must be an object', driver:true })); + } else if(Array.isArray(doc)) { + return new this.s.promiseLibrary(function(resolve, reject) { + reject(MongoError.create({message: 'doc parameter must be an object', driver:true })); + }); + } + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return insertOne(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + insertOne(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var insertOne = function(self, doc, options, callback) { + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + // Workaround for pre 2.6 servers + if(r == null) return callback(null, {result: {ok:1}}); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if(callback) callback(null, r); + }); +} + +var mapInserManyResults = function(docs, r) { + var ids = r.getInsertedIds(); + var keys = Object.keys(ids); + var finalIds = new Array(keys.length); + + for(var i = 0; i < keys.length; i++) { + if(ids[keys[i]]._id) { + finalIds[ids[keys[i]].index] = ids[keys[i]]._id; + } + } + + var finalResult = { + result: {ok: 1, n: r.insertedCount}, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: finalIds + }; + + if(r.getLastOp()) { + finalResult.result.opTime = r.getLastOp(); + } + + return finalResult; +} + +define.classMethod('insertOne', {callback: true, promise:true}); + +/** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + if(!Array.isArray(docs) && typeof callback == 'function') { + return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); + } else if(!Array.isArray(docs)) { + return new this.s.promiseLibrary(function(resolve, reject) { + reject(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); + }); + } + + // Get the write concern options + if(typeof options.checkKeys != 'boolean') { + options.checkKeys = true; + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Do we want to force the server to assign the _id key + if(forceServerObjectId !== true) { + // Add _id if not specified + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // Generate the bulk write operations + var operations = [{ + insertMany: docs + }]; + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) { + if(err) return callback(err, r); + callback(null, mapInserManyResults(docs, r)); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(mapInserManyResults(docs, r)); + }); + }); +} + +define.classMethod('insertMany', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + + if(!Array.isArray(operations)) { + throw MongoError.create({message: "operations must be an array of documents", driver:true }); + } + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err && r == null) return reject(err); + resolve(r); + }); + }); +} + +var bulkWrite = function(self, operations, options, callback) { + // Add ignoreUndfined + if(self.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = self.s.options.ignoreUndefined; + } + + // Create the bulk operation + var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); + + // Do we have a collation + var collation = false; + + // for each op go through and add to the bulk + try { + for(var i = 0; i < operations.length; i++) { + // Get the operation type + var key = Object.keys(operations[i])[0]; + // Check if we have a collation + if(operations[i][key].collation) { + collation = true; + } + + // Pass to the raw bulk + bulk.raw(operations[i]); + } + } catch(err) { + return callback(err, null); + } + + // Final options for write concern + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + var capabilities = self.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if(collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError(f('server/primary/mongos does not support collation'))); + } + + // Execute the bulk + bulk.execute(writeCon, function(err, r) { + // We have connection level error + if(!r && err) return callback(err, null); + // We have single error + if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) { + return callback(toError(r.getWriteErrorAt(0)), r); + } + + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + var inserted = r.getInsertedIds(); + // Map inserted ids + for(var i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + var upserted = r.getUpsertedIds(); + // Map upserted ids + for(i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Check if we have write errors + if(r.hasWriteErrors()) { + // Get all the errors + var errors = r.getWriteErrors(); + // Return the MongoError object + return callback(toError({ + message: 'write operation failed', code: errors[0].code, writeErrors: errors + }), r); + } + + // Check if we have a writeConcern error + if(r.getWriteConcernError()) { + // Return the MongoError object + return callback(toError(r.getWriteConcernError()), r); + } + + // Return the results + callback(null, r); + }); +} + +var insertDocuments = function(self, docs, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; + + // If keep going set unordered + if(finalOptions.keepGoing == true) finalOptions.ordered = false; + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Add _id if not specified + if(forceServerObjectId !== true){ + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // File inserts + self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('bulkWrite', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = function(docs, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:false}; + docs = !Array.isArray(docs) ? [docs] : docs; + + if(options.keepGoing == true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +} + +define.classMethod('insert', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateOne', {callback: true, promise:true}); + +/** + * Replace a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} doc The Document that replaces the matching document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return replaceOne(self, filter, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replaceOne(self, filter, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var replaceOne = function(self, filter, doc, options, callback) { + // Set single document update + options.multi = false; + + // Execute update + updateDocuments(self, filter, doc, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + r.ops = [doc]; + if(callback) callback(null, r); + }); +} + +define.classMethod('replaceOne', {callback: true, promise:true}); + +/** + * Update multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateMany(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateMany(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateMany = function(self, filter, update, options, callback) { + // Set single document update + options.multi = true; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateMany', {callback: true, promise:true}); + +var updateDocuments = function(self, selector, document, options, callback) { + if('function' === typeof options) callback = options, options = null; + if(options == null) options = {}; + if(!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); + if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Execute the operation + var op = {q: selector, u: document}; + op.upsert = typeof options.upsert == 'boolean' ? options.upsert : false; + op.multi = typeof options.multi == 'boolean' ? options.multi : false; + + // Have we specified collation + decorateWithCollation(finalOptions, self, options); + + // Update options + self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} document The update document. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = function(selector, document, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateDocuments(self, selector, document, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('update', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteOne(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteOne(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteOne = function(self, filter, options, callback) { + options.single = true; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +define.classMethod('deleteOne', {callback: true, promise:true}); + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +define.classMethod('removeOne', {callback: true, promise:true}); + +/** + * Delete multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteMany(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteMany(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteMany = function(self, filter, options, callback) { + options.single = false; + + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +var removeDocuments = function(self, selector, options, callback) { + if(typeof options == 'function') { + callback = options, options = {}; + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // If selector is null set empty + if(selector == null) selector = {}; + + // Build the op + var op = {q: selector, limit: 0}; + if(options.single) op.limit = 1; + + // Have we specified collation + decorateWithCollation(finalOptions, self, options); + + // Execute the remove + self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('deleteMany', {callback: true, promise:true}); + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +define.classMethod('removeMany', {callback: true, promise:true}); + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = function(selector, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return removeDocuments(self, selector, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeDocuments(self, selector, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('remove', {callback: true, promise:true}); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return save(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + save(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var save = function(self, doc, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + // Establish if we need to perform an insert or update + if(doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(doc == null) return handleCallback(callback, null, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, r); + }); +} + +define.classMethod('save', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options=null] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan=null] Limit the number of items to scan. + * @param {number} [options.min=null] Set index bounds. + * @param {number} [options.max=null] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOne = function() { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return findOne(self, args, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findOne(self, args, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOne = function(self, args, callback) { + var cursor = self.find.apply(self, args).limit(-1).batchSize(1); + // Return the item + cursor.next(function(err, item) { + if(err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); +} + +define.classMethod('findOne', {callback: true, promise:true}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, opt, callback) { + var self = this; + if(typeof opt == 'function') callback = opt, opt = {}; + opt = assign({}, opt, {readPreference: ReadPreference.PRIMARY}); + + // Execute using callback + if(typeof callback == 'function') return rename(self, newName, opt, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + rename(self, newName, opt, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var rename = function(self, newName, opt, callback) { + // Check the collection name + checkCollectionName(newName); + // Build the command + var renameCollection = f("%s.%s", self.s.dbName, self.s.name); + var toCollection = f("%s.%s", self.s.dbName, newName); + var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; + var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; + + // Decorate command with writeConcern if supported + decorateWithWriteConcern(cmd, self, opt); + + // Execute against admin + self.s.db.admin().command(cmd, opt, function(err, doc) { + if(err) return handleCallback(callback, err, null); + // We have an error + if(doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); + } catch(err) { + return handleCallback(callback, toError(err), null); + } + }); +} + +define.classMethod('rename', {callback: true, promise:true}); + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, options, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.dropCollection(self.s.name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('drop', {callback: true, promise:true}); + +/** + * Returns the options of the collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return options(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var options = function(self, callback) { + self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) { + if(err) return handleCallback(callback, err); + if(collections.length == 0) { + return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true })); + } + + handleCallback(callback, err, collections[0].options || null); + }); +} + +define.classMethod('options', {callback: true, promise:true}); + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return isCapped(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + isCapped(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var isCapped = function(self, callback) { + self.options(function(err, document) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, document && document.capped); + }); +} + +define.classMethod('isCapped', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + + // Execute using callback + if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * @method + * @param {array} indexSpecs An array of index specifications to be created + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndexes = function(indexSpecs, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndexes(self, indexSpecs, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndexes = function(self, indexSpecs, callback) { + var capabilities = self.s.topology.capabilities(); + + // Ensure we generate the correct name if the parameter is not set + for(var i = 0; i < indexSpecs.length; i++) { + if(indexSpecs[i].name == null) { + var keys = []; + + // Did the user pass in a collation, check if our write server supports it + if(indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError(f('server/primary/mongos does not support collation'))); + } + + for(var name in indexSpecs[i].key) { + keys.push(f('%s_%s', name, indexSpecs[i].key[name])); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + // Execute the index + self.s.db.command({ + createIndexes: self.s.name, indexes: indexSpecs + }, { readPreference: ReadPreference.PRIMARY }, callback); +} + +define.classMethod('createIndexes', {callback: true, promise:true}); + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return dropIndex(self, indexName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndex(self, indexName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndex = function(self, indexName, options, callback) { + // Delete index command + var cmd = {'dropIndexes':self.s.name, 'index':indexName}; + + // Decorate command with writeConcern if supported + decorateWithWriteConcern(cmd, self, options); + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(typeof callback != 'function') return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +define.classMethod('dropIndex', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(options, callback) { + var self = this; + + // Do we have options + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return dropIndexes(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndexes = function(self, options, callback) { + self.dropIndex('*', options, function(err) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); +} + +define.classMethod('dropIndexes', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; + +define.classMethod('dropAllIndexes', {callback: true, promise:true}); + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return reIndex(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + reIndex(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var reIndex = function(self, options, callback) { + // Reindex + var cmd = {'reIndex':self.s.name}; + + // Decorate command with writeConcern if supported + decorateWithWriteConcern(cmd, self, options); + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +define.classMethod('reIndex', {callback: true, promise:true}); + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + options = options || {}; + // Clone the options + options = shallowClone(options); + // Determine the read preference in the options. + options = getReadPreference(this, options, this.s.db, this); + // Set the CommandCursor constructor + options.cursorFactory = CommandCursor; + // Set the promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if(!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + // We have a list collections command + if(this.s.topology.capabilities().hasListIndexesCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listIndexes: this.s.name, cursor: cursor }; + // Execute the cursor + cursor = this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // Return the cursor + return cursor; + } + + // Get the namespace + var ns = f('%s.system.indexes', this.s.dbName); + // Get the query + cursor = this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // Set the passed in batch size if one was provided + if(options.batchSize) cursor = cursor.batchSize(options.batchSize); + // Return the cursor + return cursor; +}; + +define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var ensureIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return indexExists(self, indexes, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexExists(self, indexes, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexExists = function(self, indexes, callback) { + self.indexInformation(function(err, indexInformation) { + // If we have an error return + if(err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for(var i = 0; i < indexes.length; i++) { + if(indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +define.classMethod('indexExists', {callback: true, promise:true}); + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + var self = this; + // Unpack calls + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return indexInformation(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexInformation = function(self, options, callback) { + self.s.db.indexInformation(self.s.name, options, callback); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * Count number of matching documents in the db to a query. + * @method + * @param {object} query The query for the count. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.limit=null] The limit of documents to count. + * @param {boolean} [options.skip=null] The number of documents to skip for the count. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.count = function(query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback); + + // Check if query is empty + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, query, options, callback) { + var skip = options.skip; + var limit = options.limit; + var hint = options.hint; + var maxTimeMS = options.maxTimeMS; + + // Final query + var cmd = { + 'count': self.s.name, 'query': query + }; + + // Add limit, skip and maxTimeMS if defined + if(typeof skip == 'number') cmd.skip = skip; + if(typeof limit == 'number') cmd.limit = limit; + if(typeof maxTimeMS == 'number') cmd.maxTimeMS = maxTimeMS; + if(hint) options.hint = hint; + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Have we specified collation + decorateWithCollation(cmd, self, options); + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.n); + }); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * The distinct command returns returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback); + + // Ensure the query and options are set + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + distinct(self, key, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var distinct = function(self, key, query, options, callback) { + // maxTimeMS option + var maxTimeMS = options.maxTimeMS; + + // Distinct command + var cmd = { + 'distinct': self.s.name, 'key': key, 'query': query + }; + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Add maxTimeMS if defined + if(typeof maxTimeMS == 'number') + cmd.maxTimeMS = maxTimeMS; + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Have we specified collation + decorateWithCollation(cmd, self, options); + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.values); + }); +} + +define.classMethod('distinct', {callback: true, promise:true}); + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return indexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexes = function(self, callback) { + self.s.db.indexInformation(self.s.name, {full:true}, callback); +} + +define.classMethod('indexes', {callback: true, promise:true}); + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return stats(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + stats(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var stats = function(self, options, callback) { + // Build command object + var commandObject = { + collStats:self.s.name + } + + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Execute the command + self.s.db.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from findAndModify command. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Basic validation + if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object'); + + // Execute using callback + if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndDelete(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndDelete = function(self, filter, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['remove'] = true; + // Execute find and Modify + self.findAndModify( + filter + , options.sort + , null + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndDelete', {callback: true, promise:true}); + +/** + * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} replacement Document replacing the matching document. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Basic validation + if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object'); + if(replacement == null || typeof replacement != 'object') throw toError('replacement parameter must be an object'); + + // Execute using callback + if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndReplace(self, filter, replacement, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndReplace = function(self, filter, replacement, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , replacement + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndReplace', {callback: true, promise:true}); + +/** + * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} update Update operations to be performed on the document + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Basic validation + if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object'); + if(update == null || typeof update != 'object') throw toError('update parameter must be an object'); + + // Execute using callback + if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndUpdate(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndUpdate = function(self, filter, update, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , update + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndUpdate', {callback: true, promise:true}); + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + options = shallowClone(options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findAndModify(self, query, sort, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndModify = function(self, query, sort, doc, options, callback) { + // Create findAndModify command object + var queryObject = { + 'findandmodify': self.s.name + , 'query': query + }; + + sort = formattedOrderClause(sort); + if(sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + if(options.fields) { + queryObject.fields = options.fields; + } + + if(doc && !options.remove) { + queryObject.update = doc; + } + + if(options.maxTimeMS) + queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + if(options['serializeFunctions'] != null) { + options['serializeFunctions'] = options['serializeFunctions']; + } else { + options['serializeFunctions'] = self.s.serializeFunctions; + } + + // No check on the documents + options.checkKeys = false; + + // Get the write concern settings + var finalOptions = writeConcern(options, self.s.db, self, options); + + // Decorate the findAndModify command with the write Concern + if(finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if(typeof finalOptions.bypassDocumentValidation == 'boolean') { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + // Have we specified collation + decorateWithCollation(queryObject, self, options); + + // Execute the command + self.s.db.command(queryObject + , options, function(err, result) { + if(err) return handleCallback(callback, err, null); + return handleCallback(callback, null, result); + }); +} + +define.classMethod('findAndModify', {callback: true, promise:true}); + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = function(query, sort, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findAndRemove(self, query, sort, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndRemove = function(self, query, sort, options, callback) { + // Add the remove option + options['remove'] = true; + // Execute the callback + self.findAndModify(query, sort, null, options, callback); +} + +define.classMethod('findAndRemove', {callback: true, promise:true}); + +function decorateWithWriteConcern(command, self, options) { + // Do we support collation 3.4 and higher + var capabilities = self.s.topology.capabilities(); + // Do we support write concerns 3.4 and higher + if(capabilities && capabilities.commandsTakeWriteConcern) { + // Get the write concern settings + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + // Add the write concern to the command + if(finalOptions.writeConcern) { + command.writeConcern = finalOptions.writeConcern; + } + } +} + +function decorateWithCollation(command, self, options) { + // Do we support collation 3.4 and higher + var capabilities = self.s.topology.capabilities(); + // Do we support write concerns 3.4 and higher + if(capabilities && capabilities.commandsTakeCollation) { + if(options.collation && typeof options.collation == 'object') { + command.collation = options.collation; + } + } +} + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} pipeline Array containing all the aggregation framework commands for the execution. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Collection~resultCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + var self = this; + + if(Array.isArray(pipeline)) { + // Set up callback if one is provided + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if(options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + var args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + var opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = opts && (opts.readPreference + || opts.explain || opts.cursor || opts.out + || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + // Ignore readConcern option + var ignoreReadConcern = false; + + // Build the command + var command = { aggregate : this.s.name, pipeline : pipeline}; + + // If out was specified + if(typeof options.out == 'string') { + pipeline.push({$out: options.out}); + // Ignore read concern + ignoreReadConcern = true; + } else if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { + ignoreReadConcern = true; + } + + // Decorate command with writeConcern if out has been specified + if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { + decorateWithWriteConcern(command, self, options); + } + + // Have we specified collation + decorateWithCollation(command, self, options); + + // If we have bypassDocumentValidation set + if(typeof options.bypassDocumentValidation == 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if(!ignoreReadConcern && this.s.readConcern) { + command.readConcern = this.s.readConcern; + } + + // If we have allowDiskUse defined + if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // If explain has been specified add it + if(options.explain) command.explain = options.explain; + + // Validate that cursor options is valid + if(options.cursor != null && typeof options.cursor != 'object') { + throw toError('cursor options must be an object'); + } + + // promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Set the AggregationCursor constructor + options.cursorFactory = AggregationCursor; + if(typeof callback != 'function') { + if(!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + if(this.s.topology.capabilities().hasAggregationCursor) { + options.cursor = options.cursor || { batchSize : 1000 }; + command.cursor = options.cursor; + } + + // Allow disk usage command + if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Execute the cursor + return this.s.topology.cursor(this.s.namespace, command, options); + } + + // We do not allow cursor + if(options.cursor) { + return this.s.topology.cursor(this.s.namespace, command, options); + } + + // Execute the command + this.s.db.command(command, options, function(err, result) { + if(err) { + handleCallback(callback, err); + } else if(result['err'] || result['errmsg']) { + handleCallback(callback, toError(result)); + } else if(typeof result == 'object' && result['serverPipeline']) { + handleCallback(callback, null, result['serverPipeline']); + } else if(typeof result == 'object' && result['stages']) { + handleCallback(callback, null, result['stages']); + } else { + handleCallback(callback, null, result.result); + } + }); +} + +define.classMethod('aggregate', {callback: true, promise:false}); + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {numCursors: 1}; + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Execute using callback + if(typeof callback == 'function') return parallelCollectionScan(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + parallelCollectionScan(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var parallelCollectionScan = function(self, options, callback) { + // Create command object + var commandObject = { + parallelCollectionScan: self.s.name + , numCursors: options.numCursors + } + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Store the raw value + var raw = options.raw; + delete options['raw']; + + // Execute the command + self.s.db.command(commandObject, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); + + var cursors = []; + // Add the raw back to the option + if(raw) options.raw = raw; + // Create command cursors for each item + for(var i = 0; i < result.cursors.length; i++) { + var rawId = result.cursors[i].cursor.id + // Convert cursorId to Long if needed + var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId; + // Add a command cursor + cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +define.classMethod('parallelCollectionScan', {callback: true, promise:true}); + +/** + * Execute the geoNear command to search for items in the collection + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.num=null] Max number of results to return. + * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. + * @param {object} [options.query=null] Filter the results by a query. + * @param {boolean} [options.spherical=false] Perform query using a spherical model. + * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. + * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoNear = function(x, y, options, callback) { + var self = this; + var point = typeof(x) == 'object' && x + , args = Array.prototype.slice.call(arguments, point?1:2); + + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoNear(self, x, y, point, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoNear = function(self, x, y, point, options, callback) { + // Build command object + var commandObject = { + geoNear:self.s.name, + near: point || [x, y] + } + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Exclude readPreference and existing options to prevent user from + // shooting themselves in the foot + var exclude = { + readPreference: true, + geoNear: true, + near: true + }; + + // Filter out any excluded objects + commandObject = decorateCommand(commandObject, options, exclude); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Have we specified collation + decorateWithCollation(commandObject, self, options); + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) return handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoNear', {callback: true, promise:true}); + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {object} [options.search=null] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoHaystackSearch(self, x, y, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoHaystackSearch = function(self, x, y, options, callback) { + // Build command object + var commandObject = { + geoSearch: self.s.name, + near: [x, y] + } + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, {readPreference: true}); + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoHaystackSearch', {callback: true, promise:true}); + +/** + * Group function helper + * @ignore + */ +// var groupFunction = function () { +// var c = db[ns].find(condition); +// var map = new Map(); +// var reduce_function = reduce; +// +// while (c.hasNext()) { +// var obj = c.next(); +// var key = {}; +// +// for (var i = 0, len = keys.length; i < len; ++i) { +// var k = keys[i]; +// key[k] = obj[k]; +// } +// +// var aggObj = map.get(key); +// +// if (aggObj == null) { +// var newObj = Object.extend({}, key); +// aggObj = Object.extend(newObj, initial); +// map.put(key, aggObj); +// } +// +// reduce_function(obj, aggObj); +// } +// +// return { "result": map.values() }; +// }.toString(); +var groupFunction = 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 3); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if(!(typeof finalize == 'function')) { + command = finalize; + finalize = null; + } + + if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys._bsontype == 'Code')) { + keys = Object.keys(keys); + } + + if(typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if(typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + // Execute using callback + if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if(command) { + var reduceFunction = reduce && reduce._bsontype == 'Code' + ? reduce + : new Code(reduce); + + var selector = { + group: { + 'ns': self.s.name + , '$reduce': reduceFunction + , 'cond': condition + , 'initial': initial + , 'out': "inline" + } + }; + + // if finalize is defined + if(finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || (keys && keys._bsontype == 'Code')) { + selector.group.$keyf = keys && keys._bsontype == 'Code' + ? keys + : new Code(keys); + } else { + var hash = {}; + keys.forEach(function (key) { + hash[key] = 1; + }); + selector.group.key = hash; + } + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + selector.readConcern = self.s.readConcern; + } + + // Have we specified collation + decorateWithCollation(selector, self, options); + + // Execute command + self.s.db.command(selector, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + var scope = reduce != null && reduce._bsontype == 'Code' + ? reduce.scope + : {}; + + scope.ns = self.s.name; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + self.s.db.eval(new Code(groupfn, scope), function (err, results) { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +define.classMethod('group', {callback: true, promise:true}); + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope (scope) { + if(!isObject(scope) || scope._bsontype == 'ObjectID') { + return scope; + } + + var keys = Object.keys(scope); + var i = keys.length; + var key; + var new_scope = {}; + + while (i--) { + key = keys[i]; + if ('function' == typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query=null] Query filter object. + * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit=null] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize=null] Finalize function. + * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + var self = this; + if('function' === typeof options) callback = options, options = {}; + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if(null == options.out) { + throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); + } + + if('function' === typeof map) { + map = map.toString(); + } + + if('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + + // Execute using callback + if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + mapReduce(self, map, reduce, options, function(err, r, r1) { + if(err) return reject(err); + if(!r1) return resolve(r); + resolve({results: r, stats: r1}); + }); + }); +} + +var mapReduce = function(self, map, reduce, options, callback) { + var mapCommandHash = { + mapreduce: self.s.name + , map: map + , reduce: reduce + }; + + // Add any other options passed in + for(var n in options) { + if('scope' == n) { + mapCommandHash[n] = processScope(options[n]); + } else { + mapCommandHash[n] = options[n]; + } + } + + options = shallowClone(options); + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // If we have a read preference and inline is not set as output fail hard + if((options.readPreference != false && options.readPreference != 'primary') + && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { + // Force readPreference to primary + options.readPreference = 'primary'; + // Decorate command with writeConcern if supported + decorateWithWriteConcern(mapCommandHash, self, options); + } else if(self.s.readConcern) { + mapCommandHash.readConcern = self.s.readConcern; + } + + // Is bypassDocumentValidation specified + if(typeof options.bypassDocumentValidation == 'boolean') { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Have we specified collation + decorateWithCollation(mapCommandHash, self, options); + + // Execute command + self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { + if(err) return handleCallback(callback, err); + // Check if we have an error + if(1 != result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + var stats = {}; + if(result.timeMillis) stats['processtime'] = result.timeMillis; + if(result.counts) stats['counts'] = result.counts; + if(result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if(result.results) { + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, result.results, stats); + } + + // The returned collection + var collection = null; + + // If we have an object it's a different db + if(result.result != null && typeof result.result == 'object') { + var doc = result.result; + collection = self.s.db.db(doc.db).collection(doc.collection); + } else { + // Create a collection object that wraps the result collection + collection = self.s.db.collection(result.result) + } + + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, collection, stats); + }); +} + +define.classMethod('mapReduce', {callback: true, promise:true}); + +/** + * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +} + +define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]}); + +/** + * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +} + +define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]}); + +// Get write concern +var writeConcern = function(target, db, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w != null) opts.w = options.w; + if(options.wtimeout != null) opts.wtimeout = options.wtimeout; + if(options.j != null) opts.j = options.j; + if(options.fsync != null) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Figure out the read preference +var getReadPreference = function(self, options, db) { + var r = null + if(options.readPreference) { + r = options.readPreference + } else if(self.s.readPreference) { + r = self.s.readPreference + } else if(db.s.readPreference) { + r = db.s.readPreference; + } + + if(r instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); + } else if(typeof r == 'string') { + options.readPreference = new CoreReadPreference(r); + } else if(r && !(r instanceof ReadPreference) && typeof r == 'object') { + var mode = r.mode || r.preference; + if (mode && typeof mode == 'string') { + options.readPreference = new CoreReadPreference(mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); + } + } + + return options; +} + +var testForFields = { + limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 + , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 + , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1 + , collation: 1 +} + +module.exports = Collection; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/command_cursor.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 00000000..7f07f126 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,311 @@ +"use strict"; + +var inherits = require('util').inherits + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var state = CommandCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(CommandCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled']; + +// Only inherit the types we need +for(var i = 0; i < methodsToInherit.length; i++) { + CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; +} + +var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true); + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +CommandCursor.prototype.setReadPreference = function(r) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(this.s.state != CommandCursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); + + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); + } else if(typeof r == 'string') { + this.s.options.readPreference = new CoreReadPreference(r); + } else if(r instanceof CoreReadPreference) { + this.s.options.readPreference = r; + } + + return this; +} + +define.classMethod('setReadPreference', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {CommandCursor} + */ +CommandCursor.prototype.batchSize = function(value) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ +CommandCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]}); + +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +define.classMethod('get', {callback: true, promise:false}); + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +CommandCursor.INIT = 0; +CommandCursor.OPEN = 1; +CommandCursor.CLOSED = 2; + +module.exports = CommandCursor; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/cursor.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/cursor.js new file mode 100644 index 00000000..8dd7edd6 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1181 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('mongodb-core').Cursor + , Map = require('mongodb-core').BSON.Map + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the mongodb-core and node.js + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +var fields = ['numberOfRetries', 'tailableRetryInterval']; +var push = Array.prototype.push; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor maxScan + * collection.find({}).maxScan(10) // Set the cursor maxScan + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(10) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).snapshot(true) // Set the cursor snapshot + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = Cursor.INIT; + var streamOptions = {}; + + // Tailable cursor options + var numberOfRetries = options.numberOfRetries || 5; + var tailableRetryInterval = options.tailableRetryInterval || 500; + var currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries + , tailableRetryInterval: tailableRetryInterval + , currentNumberOfRetries: currentNumberOfRetries + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespace + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + // Current doc + , currentDoc: null + } + + // Translate correctly + if(self.s.options.noCursorTimeout == true) { + self.addCursorFlag('noCursorTimeout', true); + } + + // Set the sort value + this.sortValue = self.s.cmd.sort; +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(Cursor, Readable); + +// Map core cursor _next method so we can apply mapping +CoreCursor.prototype._next = CoreCursor.prototype.next; + +for(var name in CoreCursor.prototype) { + Cursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = Cursor.define = new Define('Cursor', Cursor, true); + +/** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.hasNext = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + if(self.s.currentDoc){ + return callback(null, true); + } else { + return nextObject(self, function(err, doc) { + if(!doc) return callback(null, false); + self.s.currentDoc = doc; + callback(null, true); + }); + } + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + if(self.s.currentDoc){ + resolve(true); + } else { + nextObject(self, function(err, doc) { + if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false); + if(err) return reject(err); + if(!doc) return resolve(false); + self.s.currentDoc = doc; + resolve(true); + }); + } + }); +} + +define.classMethod('hasNext', {callback: true, promise:true}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.next = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + return nextObject(self, callback) + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return resolve(doc); + } + + nextObject(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('next', {callback: true, promise:true}); + +/** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ +Cursor.prototype.filter = function(filter) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.query = filter; + return this; +} + +define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @return {Cursor} + */ +Cursor.prototype.maxScan = function(maxScan) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxScan = maxScan; + return this; +} + +define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ +Cursor.prototype.hint = function(hint) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.hint = hint; + return this; +} + +define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.min = function(min) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.min = min; + return this; +} + +define.classMethod('min', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.max = function(max) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.max = max; + return this; +} + +define.classMethod('max', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor returnKey + * @method + * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: + * @return {Cursor} + */ +Cursor.prototype.returnKey = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.returnKey = value; + return this; +} + +define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ +Cursor.prototype.showRecordId = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.showDiskLoc = value; + return this; +} + +define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @return {Cursor} + */ +Cursor.prototype.snapshot = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.snapshot = value; + return this; +} + +define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setCursorOption = function(field, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true }); + this.s[field] = value; + if(field == 'numberOfRetries') + this.s.currentNumberOfRetries = value; + return this; +} + +define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addCursorFlag = function(flag, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true }); + if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true}); + this.s.cmd[flag] = value; + return this; +} + +define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addQueryModifier = function(name, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true}); + // Strip of the $ + var field = name.substr(1); + // Set on the command + this.s.cmd[field] = value; + // Deal with the special case for sort + if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; + return this; +} + +define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.comment = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.comment = value; + return this; +} + +define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * @method + * @param {number} value Number of milliseconds to wait before aborting the tailed query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxAwaitTimeMS = function(value) { + if(typeof value != 'number') throw MongoError.create({message: "maxAwaitTimeMS must be a number", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxAwaitTimeMS = value; + return this; +} + +define.classMethod('maxAwaitTimeMS', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxTimeMS = function(value) { + if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxTimeMS = value; + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]}); + +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.project = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.fields = value; + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.sort = function(keyOrList, direction) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + var order = keyOrList; + + // We have an array of arrays, we need to preserve the order of the sort + // so we will us a Map + if(Array.isArray(order) && Array.isArray(order[0])) { + order = new Map(order.map(function(x) { + var value = [x[0], null]; + if(x[1] == 'asc') { + value[1] = 1; + } else if(x[1] == 'desc') { + value[1] = -1; + } else if(x[1] == 1 || x[1] == -1) { + value[1] = x[1]; + } else { + throw new MongoError("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); + } + + return value; + })); + } + + if(direction != null) { + order = [[keyOrList, direction]]; + } + + this.s.cmd.sort = order; + this.sortValue = order; + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.batchSize = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true}); + if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + this.s.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the collation options for the cursor. + * @method + * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.collation = function(value) { + this.s.cmd.collation = value; + return this; +} + +define.classMethod('collation', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.limit = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true}); + this.s.cmd.limit = value; + // this.cursorLimit = value; + this.setCursorLimit(value); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.skip = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true}); + this.s.cmd.skip = value; + this.setCursorSkip(value); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + +/** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + +/** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @deprecated + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.nextObject = Cursor.prototype.next; + +var nextObject = function(self, callback) { + if(self.s.state == Cursor.CLOSED || self.isDead && self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + if(self.s.state == Cursor.INIT && self.s.cmd.sort) { + try { + self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); + } catch(err) { + return handleCallback(callback, err); + } + } + + // Get the next object + self._next(function(err, doc) { + self.s.state = Cursor.OPEN; + if(err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +define.classMethod('nextObject', {callback: true, promise:true}); + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +var loop = function(self, callback) { + // No more items we are done + if(self.bufferedCount() == 0) return; + // Get the next document + self._next(callback); + // Loop + return loop; +} + +Cursor.prototype.next = Cursor.prototype.nextObject; + +define.classMethod('next', {callback: true, promise:true}); + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.each = function(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = Cursor.INIT; + // Run the query + _each(this, callback); +}; + +define.classMethod('each', {callback: true, promise:false}); + +// Run the each loop +var _each = function(self, callback) { + if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true}); + if(self.isNotified()) return; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + } + + if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; + + // Define function to avoid global scope escape + var fn = null; + // Trampoline all the entries + if(self.bufferedCount() > 0) { + while(fn = loop(self, callback)) fn(self, callback); + _each(self, callback); + } else { + self.next(function(err, item) { + if(err) return handleCallback(callback, err); + if(item == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, null); + } + + if(handleCallback(callback, null, item) == false) return; + _each(self, callback); + }) + } +} + +/** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.forEach = function(iterator, callback) { + this.each(function(err, doc){ + if(err) { callback(err); return false; } + if(doc != null) { iterator(doc); return true; } + if(doc == null && callback) { + var internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); +} + +define.classMethod('forEach', {callback: true, promise:false}); + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setReadPreference = function(r) { + if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); + } else if(typeof r == 'string'){ + this.s.options.readPreference = new CoreReadPreference(r); + } else if(r instanceof CoreReadPreference) { + this.s.options.readPreference = r; + } + + return this; +} + +define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.toArray = function(callback) { + var self = this; + if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true}); + + // Execute using callback + if(typeof callback == 'function') return toArray(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + toArray(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var toArray = function(self, callback) { + var items = []; + + // Reset cursor + self.rewind(); + self.s.state = Cursor.INIT; + + // Fetch all the documents + var fetchDocs = function() { + self._next(function(err, doc) { + if(err) return handleCallback(callback, err); + if(doc == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, items); + } + + // Add doc to items + items.push(doc) + + // Get all buffered objects + if(self.bufferedCount() > 0) { + var docs = self.readBufferedDocuments(self.bufferedCount()) + + // Transform the doc if transform method added + if(self.s.transforms && typeof self.s.transforms.doc == 'function') { + docs = docs.map(self.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }) + } + + fetchDocs(); +} + +define.classMethod('toArray', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + +/** + * Get the count of documents for this cursor + * @method + * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options=null] Optional settings. + * @param {number} [options.skip=null] The number of documents to skip. + * @param {number} [options.limit=null] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.count = function(applySkipLimit, opts, callback) { + var self = this; + if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true}); + if(typeof opts == 'function') callback = opts, opts = {}; + opts = opts || {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, applySkipLimit, opts, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, applySkipLimit, opts, callback) { + if(typeof applySkipLimit == 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if(applySkipLimit) { + if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip(); + if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit(); + } + + // Command + var delimiter = self.s.ns.indexOf('.'); + + var command = { + 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query + } + + if(typeof opts.maxTimeMS == 'number') { + command.maxTimeMS = opts.maxTimeMS; + } else if(self.s.cmd && typeof self.s.cmd.maxTimeMS == 'number') { + command.maxTimeMS = self.s.cmd.maxTimeMS; + } + + // Merge in any options + if(opts.skip) command.skip = opts.skip; + if(opts.limit) command.limit = opts.limit; + if(self.s.options.hint) command.hint = self.s.options.hint; + + // Execute the command + self.topology.command(f("%s.$cmd", self.s.ns.substr(0, delimiter)) + , command, function(err, result) { + callback(err, result ? result.result.n : null) + }); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.close = function(callback) { + this.s.state = Cursor.CLOSED; + // Kill the cursor + this.kill(); + // Emit the close event for the cursor + this.emit('close'); + // Callback if provided + if(typeof callback == 'function') return handleCallback(callback, null, this); + // Return a Promise + return new this.s.promiseLibrary(function(resolve) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {Cursor} + */ +Cursor.prototype.map = function(transform) { + this.cursorState.transforms = { doc: transform }; + return this; +} + +define.classMethod('map', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Is the cursor closed + * @method + * @return {boolean} + */ +Cursor.prototype.isClosed = function() { + return this.isDead(); +} + +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); + +Cursor.prototype.destroy = function(err) { + if(err) this.emit('error', err); + this.pause(); + this.close(); +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options=null] Optional settings. + * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ +Cursor.prototype.stream = function(options) { + this.s.streamOptions = options || {}; + return this; +} + +define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.explain = function(callback) { + var self = this; + this.s.cmd.explain = true; + + // Do we have a readConcern + if(this.s.cmd.readConcern) { + delete this.s.cmd['readConcern']; + } + + // Execute using callback + if(typeof callback == 'function') return this._next(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self._next(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('explain', {callback: true, promise:true}); + +Cursor.prototype._read = function() { + var self = this; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return self.push(null); + } + + // Get the next item + self.nextObject(function(err, result) { + if(err) { + if(self.listeners('error') && self.listeners('error').length > 0) { + self.emit('error', err); + } + if(!self.isDead()) self.close(); + + // Emit end event + self.emit('end'); + return self.emit('finish'); + } + + // If we provided a transformation method + if(typeof self.s.streamOptions.transform == 'function' && result != null) { + return self.push(self.s.streamOptions.transform(result)); + } + + // If we provided a map function + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { + return self.push(self.cursorState.transforms.doc(result)); + } + + // Return the result + self.push(result); + }); +} + +Object.defineProperty(Cursor.prototype, 'readPreference', { + enumerable:true, + get: function() { + if (!this || !this.s) { + return null; + } + + return this.s.options.readPreference; + } +}); + +Object.defineProperty(Cursor.prototype, 'namespace', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + // TODO: refactor this logic into core + var ns = this.s.ns || ''; + var firstDot = ns.indexOf('.'); + if (firstDot < 0) { + return { + database: this.s.ns, + collection: '' + }; + } + return { + database: ns.substr(0, firstDot), + collection: ns.substr(firstDot + 1) + }; + } +}); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +Cursor.INIT = 0; +Cursor.OPEN = 1; +Cursor.CLOSED = 2; +Cursor.GET_MORE = 3; + +module.exports = Cursor; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/db.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/db.js new file mode 100644 index 00000000..c4d30b2f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/db.js @@ -0,0 +1,1881 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , getSingleProperty = require('./utils').getSingleProperty + , shallowClone = require('./utils').shallowClone + , parseIndexOptions = require('./utils').parseIndexOptions + , debugOptions = require('./utils').debugOptions + , CommandCursor = require('./command_cursor') + , handleCallback = require('./utils').handleCallback + , filterOptions = require('./utils').filterOptions + , toError = require('./utils').toError + , ReadPreference = require('./read_preference') + , f = require('util').format + , Admin = require('./admin') + , Code = require('mongodb-core').BSON.Code + , CoreReadPreference = require('mongodb-core').ReadPreference + , MongoError = require('mongodb-core').MongoError + , ObjectID = require('mongodb-core').ObjectID + , Define = require('./metadata') + , Logger = require('mongodb-core').Logger + , Collection = require('./collection') + , crypto = require('crypto') + , assign = require('./utils').assign; + +var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' + , 'serializeFunctions', 'raw', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' + , 'readPreference', 'pkFactory', 'parentDb', 'promiseLibrary', 'noListener']; + +// Filter out any write concern options +var illegalCommandFields = ['w', 'wtimeout', 'j', 'fsync', 'autoIndexId' + , 'strict', 'serializeFunctions', 'pkFactory', 'raw', 'readPreference']; + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * var testDb = db.db('test'); + * db.close(); + * }); + */ + +// Allowed parameters +var legalOptionNames = ['w', 'wtimeout', 'fsync', 'j', 'readPreference', 'readPreferenceTags', 'native_parser' + , 'forceServerObjectId', 'pkFactory', 'serializeFunctions', 'raw', 'bufferMaxEntries', 'authSource' + , 'ignoreUndefined', 'promoteLongs', 'promiseLibrary', 'readConcern', 'retryMiliSeconds', 'numberOfRetries' + , 'parentDb', 'noListener', 'loggerLevel', 'logger', 'promoteBuffers', 'promoteLongs', 'promoteValues']; + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @property {object} topology Access the topology object (single server, replicaset or mongos). + * @fires Db#close + * @fires Db#authenticated + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +var Db = function(databaseName, topology, options) { + options = options || {}; + if(!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + var self = this; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // var self = this; // Internal state of the db object + this.s = { + // Database name + databaseName: databaseName + // DbCache + , dbCache: {} + // Children db's + , children: [] + // Topology + , topology: topology + // Options + , options: options + // Logger instance + , logger: Logger('Db', options) + // Get the bson parser + , bson: topology ? topology.bson : null + // Authsource if any + , authSource: options.authSource + // Unpack read preference + , readPreference: options.readPreference + // Set buffermaxEntries + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 + // Parent db (if chained) + , parentDb: options.parentDb || null + // Set up the primary key factory or fallback to ObjectID + , pkFactory: options.pkFactory || ObjectID + // Get native parser + , nativeParser: options.nativeParser || options.native_parser + // Promise library + , promiseLibrary: promiseLibrary + // No listener + , noListener: typeof options.noListener == 'boolean' ? options.noListener : false + // ReadConcern + , readConcern: options.readConcern + } + + // Ensure we have a valid db name + validateDatabaseName(self.s.databaseName); + + // Add a read Only property + getSingleProperty(this, 'serverConfig', self.s.topology); + getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', self.s.databaseName); + + // This is a child db, do not register any listeners + if(options.parentDb) return; + if(this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(self, 'error', self)); + topology.on('timeout', createListener(self, 'timeout', self)); + topology.on('close', createListener(self, 'close', self)); + topology.on('parseError', createListener(self, 'parseError', self)); + topology.once('open', createListener(self, 'open', self)); + topology.once('fullsetup', createListener(self, 'fullsetup', self)); + topology.once('all', createListener(self, 'all', self)); + topology.on('reconnect', createListener(self, 'reconnect', self)); +} + +inherits(Db, EventEmitter); + +var define = Db.define = new Define('Db', Db, false); + +// Topology +Object.defineProperty(Db.prototype, 'topology', { + enumerable:true, + get: function() { return this.s.topology; } +}); + +// Options +Object.defineProperty(Db.prototype, 'options', { + enumerable:true, + get: function() { return this.s.options; } +}); + +// slaveOk specified +Object.defineProperty(Db.prototype, 'slaveOk', { + enumerable:true, + get: function() { + if(this.s.options.readPreference != null + && (this.s.options.readPreference != 'primary' || this.s.options.readPreference.mode != 'primary')) { + return true; + } + return false; + } +}); + +// get the write Concern +Object.defineProperty(Db.prototype, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(this.s.options.w != null) ops.w = this.s.options.w; + if(this.s.options.j != null) ops.j = this.s.options.j; + if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * The callback format for the Db.open method + * @callback Db~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The Db instance if the open method was successful. + */ + +// Internal method +var open = function(self, callback) { + self.s.topology.connect(self, self.s.options, function(err) { + if(callback == null) return; + var internalCallback = callback; + callback == null; + + if(err) { + self.close(); + return internalCallback(err); + } + + internalCallback(null, self); + }); +} + +/** + * Open the database + * @method + * @param {Db~openCallback} [callback] Callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.open = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + open(self, function(err, db) { + if(err) return reject(err); + resolve(db); + }) + }); +} + +define.classMethod('open', {callback: true, promise:true}); + +/** + * Converts provided read preference to CoreReadPreference + * @param {(ReadPreference|string|object)} readPreference the user provided read preference + * @return {CoreReadPreference} + */ +var convertReadPreference = function(readPreference) { + if(readPreference && typeof readPreference == 'string') { + return new CoreReadPreference(readPreference); + } else if(readPreference instanceof ReadPreference) { + return new CoreReadPreference(readPreference.mode, readPreference.tags, {maxStalenessSeconds: readPreference.maxStalenessSeconds}); + } else if(readPreference && typeof readPreference == 'object') { + var mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode == 'string') { + readPreference = new CoreReadPreference(mode, readPreference.tags, {maxStalenessSeconds: readPreference.maxStalenessSeconds}); + } + } + return readPreference; +} + +/** + * The callback format for results + * @callback Db~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +var executeCommand = function(self, command, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Get the db name we are executing against + var dbName = options.dbName || options.authdb || self.s.databaseName; + + // If we have a readPreference set + if(options.readPreference == null && self.s.readPreference) { + options.readPreference = self.s.readPreference; + } + + // Convert the readPreference if its not a write + if(options.readPreference) { + options.readPreference = convertReadPreference(options.readPreference); + } else { + options.readPreference = CoreReadPreference.primary; + } + + // Debug information + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' + , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); + + // Execute command + self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { + if(err) return handleCallback(callback, err); + if(options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); +} + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + var self = this; + // Change the callback + if(typeof options == 'function') callback = options, options = {}; + // Clone the options + options = shallowClone(options); + + // Do we have a callback + if(typeof callback == 'function') return executeCommand(self, command, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommand(self, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Db~noResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {null} result Is not set to a value + */ + +/** + * Close the db and its underlying connections + * @method + * @param {boolean} force Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.close = function(force, callback) { + if(typeof force == 'function') callback = force, force = false; + this.s.topology.close(force); + var self = this; + + // Fire close event if any listeners + if(this.listeners('close').length > 0) { + this.emit('close'); + + // If it's the top level db emit close on all children + if(this.parentDb == null) { + // Fire close on all children + for(var i = 0; i < this.s.children.length; i++) { + this.s.children[i].emit('close'); + } + } + + // Remove listeners after emit + self.removeAllListeners('close'); + } + + // Close parent db if set + if(this.s.parentDb) this.s.parentDb.close(); + // Callback after next event loop tick + if(typeof callback == 'function') return process.nextTick(function() { + handleCallback(callback, null); + }) + + // Return dummy promise + return new this.s.promiseLibrary(function(resolve) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +define.classMethod('admin', {callback: false, promise:false, returns: [Admin]}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can + * can use it without a callback in the following way: `var collection = db.collection('mycollection');` + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} callback The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern || this.s.readConcern; + + // Do we have ignoreUndefined set + if(this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute + if(options == null || !options.strict) { + try { + var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options); + if(callback) callback(null, collection); + return collection; + } catch(err) { + if(callback) return callback(err); + throw err; + } + } + + // Strict mode + if(typeof callback != 'function') { + throw toError(f("A callback is required in strict mode. While getting collection %s.", name)); + } + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + // Strict mode + this.listCollections({name:name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); + + try { + return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + } catch(err) { + return handleCallback(callback, err, null); + } + }); +} + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +function decorateWithWriteConcern(command, self, options) { + // Do we support write concerns 3.4 and higher + if(self.s.topology.capabilities().commandsTakeWriteConcern) { + // Get the write concern settings + var finalOptions = writeConcern(shallowClone(options), self, options); + // Add the write concern to the command + if(finalOptions.writeConcern) { + command.writeConcern = finalOptions.writeConcern; + } + } +} + +var createCollection = function(self, name, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self, options); + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Check if we have the name + self.listCollections({name: name}) + .setReadPreference(ReadPreference.PRIMARY) + .toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length > 0 && finalOptions.strict) { + return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null); + } else if (collections.length > 0) { + try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } + catch(err) { return handleCallback(callback, err); } + } + + // Create collection command + var cmd = {'create':name}; + + // Decorate command with writeConcern if supported + decorateWithWriteConcern(cmd, self, options); + // Add all optional parameters + for(var n in options) { + if(options[n] != null + && typeof options[n] != 'function' && illegalCommandFields.indexOf(n) == -1) { + cmd[n] = options[n]; + } + } + + // Force a primary read Preference + finalOptions.readPreference = ReadPreference.PRIMARY; + + // Execute command + self.command(cmd, finalOptions, function(err) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + }); + }); +} + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {number} [options.size=null] The size of the capped collection in bytes. + * @param {number} [options.max=null] The maximum number of documents in the capped collection. + * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. + * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = function(name, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + name = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Do we have a promisesLibrary + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + + // Check if the callback is in fact a string + if(typeof callback == 'string') name = callback; + + // Execute the fallback callback + if(typeof callback == 'function') return createCollection(self, name, options, callback); + return new this.s.promiseLibrary(function(resolve, reject) { + createCollection(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('createCollection', {callback: true, promise:true}); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Build command object + var commandObject = { dbStats:true }; + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + + // If we have a readPreference set + if(options.readPreference == null && this.s.readPreference) { + options.readPreference = this.s.readPreference; + } + + // Execute the command + return this.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +// Transformation methods for cursor results +var listCollectionsTranforms = function(databaseName) { + var matching = f('%s.', databaseName); + + return { + doc: function(doc) { + var index = doc.name.indexOf(matching); + // Remove database name if available + if(doc.name && index == 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + } +} + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} filter Query to filter collections by + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + // Shallow clone the object + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // Ensure valid readPreference + if(options.readPreference) { + options.readPreference = convertReadPreference(options.readPreference); + } + + // We have a list collections command + if(this.serverConfig.capabilities().hasListCollectionsCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listCollections : true, filter: filter, cursor: cursor }; + // Set the AggregationCursor constructor + options.cursorFactory = CommandCursor; + // Create the cursor + cursor = this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); + // Do we have a readPreference, apply it + if(options.readPreference) { + cursor.setReadPreference(options.readPreference); + } + // Return the cursor + return cursor; + } + + // We cannot use the listCollectionsCommand + if(!this.serverConfig.capabilities().hasListCollectionsCommand) { + // If we have legacy mode and have not provided a full db name filter it + if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { + filter = shallowClone(filter); + filter.name = f('%s.%s', this.s.databaseName, filter.name); + } + } + + // No filter, filter by current database + if(filter == null) { + filter.name = f('/%s/', this.s.databaseName); + } + + // Rewrite the filter to use $and to filter out indexes + if(filter.name) { + filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]}; + } else { + filter = {name:/^((?!\$).)*$/}; + } + + // Return options + var _options = {transforms: listCollectionsTranforms(this.s.databaseName)} + // Get the cursor + cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // Set the passed in batch size if one was provided + if(options.batchSize) cursor = cursor.batchSize(options.batchSize); + // We have a fallback mode using legacy systems collections + return cursor; +}; + +define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]}); + +var evaluate = function(self, code, parameters, options, callback) { + var finalCode = code; + var finalParameters = []; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // If not a code object translate to one + if(!(finalCode && finalCode._bsontype == 'Code')) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + var cmd = {'$eval':finalCode, 'args':finalParameters}; + // Check if the nolock parameter is passed in + if(options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY); + + // Execute the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result && result.ok == 1) return handleCallback(callback, null, result.retval); + if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null); + handleCallback(callback, err, result); + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = function(code, parameters, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback); + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + evaluate(self, code, parameters, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('eval', {callback: true, promise:true}); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Add return new collection + options.new_collection = true; + + // Check if the callback is in fact a string + if(typeof callback == 'function') { + return this.collection(fromCollection).rename(toCollection, options, callback); + } + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.collection(fromCollection).rename(toCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('renameCollection', {callback: true, promise:true}); + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Command to execute + var cmd = {'drop':name} + + // Decorate with write concern + decorateWithWriteConcern(cmd, self, options); + + // options + options = assign({}, this.s.options, {readPreference: ReadPreference.PRIMARY}); + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(err) return handleCallback(callback, err); + if(result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); + + // Clone the options + options = shallowClone(self.s.options); + // Set readPreference PRIMARY + options.readPreference = ReadPreference.PRIMARY; + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +}; + +define.classMethod('dropCollection', {callback: true, promise:true}); + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Drop database command + var cmd = {'dropDatabase':1}; + + // Decorate with write concern + decorateWithWriteConcern(cmd, self, options); + + // Ensure primary only + options = assign({}, this.s.options, {readPreference: ReadPreference.PRIMARY}); + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +} + +define.classMethod('dropDatabase', {callback: true, promise:true}); + +/** + * The callback format for the collections method. + * @callback Db~collectionsResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection[]} collections An array of all the collections objects for the db instance. + */ +var collections = function(self, callback) { + // Let's get the collection names + self.listCollections().toArray(function(err, documents) { + if(err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(function(doc) { + return doc.name.indexOf('$') == -1; + }); + + // Return the collection objects + handleCallback(callback, null, documents.map(function(d) { + return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options); + })); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(callback) { + var self = this; + + // Return the callback + if(typeof callback == 'function') return collections(self, callback); + // Return the promise + return new self.s.promiseLibrary(function(resolve, reject) { + collections(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('collections', {callback: true, promise:true}); + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Return the callback + if(typeof callback == 'function') { + // Convert read preference + if(options.readPreference) { + options.readPreference = convertReadPreference(options.readPreference) + } + + return self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); + } + + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + resolve(result.result); + }); + }); +}; + +define.classMethod('executeDbAdminCommand', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + // Shallow clone the options + options = shallowClone(options); + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // If we have a callback fallback + if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var createIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Ensure we have a callback + if(finalOptions.writeConcern && typeof callback != 'function') { + throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true}); + } + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { + if(err == null) return handleCallback(callback, err, result); + + // 67 = 'CannotCreateIndex' (malformed index options) + // 85 = 'IndexOptionsConflict' (index already exists with different options) + // 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) + // These errors mean that the server recognized `createIndex` as a command + // and so we don't need to fallback to an insert. + if(err.code === 67 || err.code == 11000 || err.code === 85) { + return handleCallback(callback, err, result); + } + + // Create command + var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + }); + }); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var ensureIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Create command + var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); + var index_name = selector.name; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Check if the index allready exists + self.indexInformation(name, finalOptions, function(err, indexInformation) { + if(err != null && err.code != 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if(indexInformation == null || !indexInformation[index_name]) { + self.createIndex(name, fieldOrSpec, options, callback); + } else { + if(typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +Db.prototype.addChild = function(db) { + if(this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +} + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} name The name of the database we want to use. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +Db.prototype.db = function(dbName, options) { + options = options || {}; + + // Copy the options and add out internal override of the not shared flag + var finalOptions = assign({}, this.options, options); + + // Do we have the db in the cache already + if(this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) { + return this.s.dbCache[dbName]; + } + + // Add current db as parentDb + if(finalOptions.noListener == null || finalOptions.noListener == false) { + finalOptions.parentDb = this; + } + + // Add promiseLibrary + finalOptions.promiseLibrary = this.s.promiseLibrary; + + // Return the db object + var db = new Db(dbName, this.s.topology, finalOptions) + + // Add as child + if(finalOptions.noListener == null || finalOptions.noListener == false) { + this.addChild(db); + } + + // Add the db to the cache + this.s.dbCache[dbName] = db; + // Return the database + return db; +}; + +define.classMethod('db', {callback: false, promise:false, returns: [Db]}); + +var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { + // Special case where there is no password ($external users) + if(typeof username == 'string' + && password != null && typeof password == 'object') { + options = password; + password = null; + } + + // Unpack all options + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Error out if we digestPassword set + if(options.digestPassword != null) { + throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); + } + + // Get additional values + var customData = options.customData != null ? options.customData : {}; + var roles = Array.isArray(options.roles) ? options.roles : []; + var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; + + // If not roles defined print deprecated message + if(roles.length == 0) { + console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); + } + + // Get the error options + var commandOptions = {writeCommand:true}; + if(options['dbName']) commandOptions.dbName = options['dbName']; + + // Add maxTimeMS to options if set + if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Check the db name and add roles if needed + if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { + roles = ['root'] + } else if(!Array.isArray(options.roles)) { + roles = ['dbOwner'] + } + + // Build the command to execute + var command = { + createUser: username + , customData: customData + , roles: roles + , digestPassword:false + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // No password + if(typeof password == 'string') { + command.pwd = userPassword; + } + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, !result.ok ? toError(result) : null + , result.ok ? [{user: username, pwd: ''}] : null); + }) +} + +var addUser = function(self, username, password, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Attempt to execute auth command + _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { + // We need to perform the backward compatible insert operation + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Check if we are inserting the first user + collection.count({}, function(err, count) { + // We got an error (f.ex not authorized) + if(err != null) return handleCallback(callback, err, null); + // Check if the user exists and update i + collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err) { + // We got an error (f.ex not authorized) + if(err != null) return handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err) { + if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); + if(err) return handleCallback(callback, err, null) + handleCallback(callback, null, [{user:username, pwd:userPassword}]); + }); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return addUser(self, username, password, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + addUser(self, username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('addUser', {callback: true, promise:true}); + +var _executeAuthRemoveUserCommand = function(self, username, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Get the error options + var commandOptions = {writeCommand:true}; + if(options['dbName']) commandOptions.dbName = options['dbName']; + + // Get additional values + var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; + + // Add maxTimeMS to options if set + if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Build the command to execute + var command = { + dropUser: username + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }) +} + +var removeUser = function(self, username, options, callback) { + // Attempt to execute command + _executeAuthRemoveUserCommand(self, username, options, function(err, result) { + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Locate the user + collection.findOne({user: username}, {}, function(err, user) { + if(user == null) return handleCallback(callback, err, false); + collection.remove({user: username}, finalOptions, function(err) { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return removeUser(self, username, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeUser(self, username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var authenticate = function(self, username, password, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + var authdb = options.dbName ? options.dbName : self.databaseName; + authdb = self.authSource ? self.authSource : authdb; + authdb = options.authdb ? options.authdb : authdb; + authdb = options.authSource ? options.authSource : authdb; + + // Callback + var _callback = function(err, result) { + if(self.listeners('authenticated').length > 0) { + self.emit('authenticated', err, result); + } + + // Return to caller + handleCallback(callback, err, result); + } + + // authMechanism + var authMechanism = options.authMechanism || ''; + authMechanism = authMechanism.toUpperCase(); + + // If classic auth delegate to auth command + if(authMechanism == 'MONGODB-CR') { + self.s.topology.auth('mongocr', authdb, username, password, function(err) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'PLAIN') { + self.s.topology.auth('plain', authdb, username, password, function(err) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'MONGODB-X509') { + self.s.topology.auth('x509', authdb, username, password, function(err) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'SCRAM-SHA-1') { + self.s.topology.auth('scram-sha-1', authdb, username, password, function(err) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'GSSAPI') { + if(process.platform == 'win32') { + self.s.topology.auth('sspi', authdb, username, password, options, function(err) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + self.s.topology.auth('gssapi', authdb, username, password, options, function(err) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } + } else if(authMechanism == 'DEFAULT') { + self.s.topology.auth('default', authdb, username, password, function(err) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true})); + } +} + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.authenticate = function(username, password, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + // Shallow copy the options + options = shallowClone(options); + + // Set default mechanism + if(!options.authMechanism) { + options.authMechanism = 'DEFAULT'; + } else if(options.authMechanism != 'GSSAPI' + && options.authMechanism != 'DEFAULT' + && options.authMechanism != 'MONGODB-CR' + && options.authMechanism != 'MONGODB-X509' + && options.authMechanism != 'SCRAM-SHA-1' + && options.authMechanism != 'PLAIN') { + return handleCallback(callback, MongoError.create({message: "only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true})); + } + + // If we have a callback fallback + if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return callback(err, r); + callback(null, r); + }); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {object} [options=null] Optional settings. + * @param {string} [options.dbName=null] Logout against different database than current. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.logout = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Establish the correct database name + var dbName = this.s.authSource ? this.s.authSource : this.s.databaseName; + dbName = options.dbName ? options.dbName : dbName; + + // If we have a callback + if(typeof callback == 'function') { + return self.s.topology.logout(dbName, function(err) { + if(err) return callback(err); + callback(null, true); + }); + } + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.topology.logout(dbName, function(err) { + if(err) return reject(err); + resolve(true); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return indexInformation(self, name, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var indexInformation = function(self, name, options, callback) { + // If we specified full information + var full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Process all the results from the index command and collection + var processResults = function(indexes) { + // Contains all the information + var info = {}; + // Process all the indexes + for(var i = 0; i < indexes.length; i++) { + var index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for(var name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + self.collection(name).listIndexes().toArray(function(err, indexes) { + if(err) return callback(toError(err)); + if(!Array.isArray(indexes)) return handleCallback(callback, null, []); + if(full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { + var indexParameters = parseIndexOptions(fieldOrSpec); + var fieldHash = indexParameters.fieldHash; + + // Generate the index name + var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; + var selector = { + 'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName + } + + // Ensure we have a correct finalUnique + var finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options == 'boolean' ? {} : options; + + // Add all the options + var keysToOmit = Object.keys(selector); + for(var optionName in options) { + if(keysToOmit.indexOf(optionName) == -1) { + selector[optionName] = options[optionName]; + } + } + + if(selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { + // Build the index + var indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; + // Set up the index + var indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + var keysToOmit = Object.keys(indexes[0]); + for(var optionName in options) { + if(keysToOmit.indexOf(optionName) == -1) { + indexes[0][optionName] = options[optionName]; + } + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete indexes[0][removeKeys[i]]; + } + } + + // Get capabilities + var capabilities = self.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if(indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { + // Create a new error + var error = new MongoError(f('server/primary/mongos does not support collation')); + error.code = 67; + // Return the error + return callback(error); + } + + // Create command, apply write concern to command + var cmd = writeConcern({createIndexes: name, indexes: indexes}, self, options); + + // Decorate command with writeConcern if supported + decorateWithWriteConcern(cmd, self, options); + + // ReadPreference primary + options.readPreference = ReadPreference.PRIMARY; + + // Build the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result.ok == 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +// Validate the database name +var validateDatabaseName = function(databaseName) { + if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true}); + if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true}); + if(databaseName == '$external') return; + + var invalidChars = [" ", ".", "$", "/", "\\"]; + for(var i = 0; i < invalidChars.length; i++) { + if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true}); + } +} + +// Get write concern +var writeConcern = function(target, db, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w) opts.w = options.w; + if(options.wtimeout) opts.wtimeout = options.wtimeout; + if(options.j) opts.j = options.j; + if(options.fsync) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Add listeners to topology +var createListener = function(self, e, object) { + var listener = function(err) { + if(object.listeners(e).length > 0) { + object.emit(e, err, self); + + // Emit on all associated db's if available + for(var i = 0; i < self.s.children.length; i++) { + self.s.children[i].emit(e, err, self.s.children[i]); + } + } + } + return listener; +} + + +/** + * Unref all sockets + * @method + */ +Db.prototype.unref = function() { + this.s.topology.unref(); +} + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db authenticated event + * + * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated. + * + * @event Db#authenticated + * @type {object} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; +Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; +Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; +Db.SYSTEM_USER_COLLECTION = "system.users"; +Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; +Db.SYSTEM_JS_COLLECTION = "system.js"; + +module.exports = Db; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/download.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/download.js new file mode 100644 index 00000000..7262ffdd --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/download.js @@ -0,0 +1,398 @@ +var stream = require('stream'), + util = require('util'); + +module.exports = GridFSBucketReadStream; + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * + * @class + * @param {Collection} chunks Handle for chunks collection + * @param {Collection} files Handle for files collection + * @param {Object} readPreference The read preference to use + * @param {Object} filter The query to use to find the file document + * @param {Object} [options=null] Optional settings. + * @param {Number} [options.sort=null] Optional sort for the file find query + * @param {Number} [options.skip=null] Optional skip for the file find query + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @fires GridFSBucketReadStream#error + * @fires GridFSBucketReadStream#file + * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. + */ + +function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { + this.s = { + bytesRead: 0, + chunks: chunks, + cursor: null, + expected: 0, + files: files, + filter: filter, + init: false, + expectedEnd: 0, + file: null, + options: options, + readPreference: readPreference + }; + + stream.Readable.call(this); +} + +util.inherits(GridFSBucketReadStream, stream.Readable); + +/** + * An error occurred + * + * @event GridFSBucketReadStream#error + * @type {Error} + */ + +/** + * Fires when the stream loaded the file document corresponding to the + * provided id. + * + * @event GridFSBucketReadStream#file + * @type {object} + */ + +/** + * Emitted when a chunk of data is available to be consumed. + * + * @event GridFSBucketReadStream#data + * @type {object} + */ + +/** + * Fired when the stream is exhausted (no more data events). + * + * @event GridFSBucketReadStream#end + * @type {object} + */ + +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * + * @event GridFSBucketReadStream#close + * @type {object} + */ + +/** + * Reads from the cursor and pushes to the stream. + * @method + */ + +GridFSBucketReadStream.prototype._read = function() { + var _this = this; + if (this.destroyed) { + return; + } + + waitForFile(_this, function() { + doRead(_this); + }); +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} start Offset in bytes to start reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.start = function(start) { + throwIfInitialized(this); + this.s.options.start = start; + return this; +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} end Offset in bytes to stop reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.end = function(end) { + throwIfInitialized(this); + this.s.options.end = end; + return this; +}; + +/** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @method + * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. + * @fires GridFSBucketWriteStream#close + * @fires GridFSBucketWriteStream#end + */ + +GridFSBucketReadStream.prototype.abort = function(callback) { + var _this = this; + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(function(error) { + _this.emit('close'); + callback && callback(error); + }); + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + _this.emit('close'); + } + callback && callback(); + } +}; + +/** + * @ignore + */ + +function throwIfInitialized(self) { + if (self.s.init) { + throw new Error('You cannot change options after the stream has entered' + + 'flowing mode!'); + } +} + +/** + * @ignore + */ + +function doRead(_this) { + if (_this.destroyed) { + return; + } + + _this.s.cursor.next(function(error, doc) { + if (_this.destroyed) { + return; + } + if (error) { + return __handleError(_this, error); + } + if (!doc) { + _this.push(null); + return _this.s.cursor.close(function(error) { + if (error) { + return __handleError(_this, error); + } + _this.emit('close'); + }); + } + + var bytesRemaining = _this.s.file.length - _this.s.bytesRead; + var expectedN = _this.s.expected++; + var expectedLength = Math.min(_this.s.file.chunkSize, + bytesRemaining); + + if (doc.n > expectedN) { + var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + if (doc.n < expectedN) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + if (doc.data.length() !== expectedLength) { + if (bytesRemaining <= 0) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; + return __handleError(_this, new Error(errmsg)); + } + + errmsg = 'ChunkIsWrongSize: Got unexpected length: ' + + doc.data.length() + ', expected: ' + expectedLength; + return __handleError(_this, new Error(errmsg)); + } + + _this.s.bytesRead += doc.data.length(); + + if (doc.data.buffer.length === 0) { + return _this.push(null); + } + + var sliceStart = null; + var sliceEnd = null; + var buf = doc.data.buffer; + + if (_this.s.bytesToSkip != null) { + sliceStart = _this.s.bytesToSkip; + _this.s.bytesToSkip = 0; + } + + if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) { + sliceEnd = _this.s.bytesToTrim; + } + + // If the remaining amount of data left is < chunkSize read the right amount of data + if (_this.s.options.end && ( + (_this.s.options.end - _this.s.bytesToSkip) < doc.data.length() + )) { + sliceEnd = (_this.s.options.end - _this.s.bytesToSkip); + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); + } + + _this.push(buf); + }) +} + +/** + * @ignore + */ + +function init(self) { + var findOneOptions = {}; + if (self.s.readPreference) { + findOneOptions.readPreference = self.s.readPreference; + } + if (self.s.options && self.s.options.sort) { + findOneOptions.sort = self.s.options.sort; + } + if (self.s.options && self.s.options.skip) { + findOneOptions.skip = self.s.options.skip; + } + + self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { + if (error) { + return __handleError(self, error); + } + if (!doc) { + var identifier = self.s.filter._id ? + self.s.filter._id.toString() : self.s.filter.filename; + var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; + var err = new Error(errmsg); + err.code = 'ENOENT'; + return __handleError(self, err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + self.push(null); + return; + } + + if (self.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + self.emit('close'); + return; + } + + self.s.cursor = self.s.chunks.find({ files_id: doc._id }).sort({ n: 1 }); + if (self.s.readPreference) { + self.s.cursor.setReadPreference(self.s.readPreference); + } + + self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + self.s.file = doc; + self.s.bytesToSkip = handleStartOption(self, doc, self.s.cursor, + self.s.options); + self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, + self.s.options); + self.emit('file', doc); + }); +} + +/** + * @ignore + */ + +function waitForFile(_this, callback) { + if (_this.s.file) { + return callback(); + } + + if (!_this.s.init) { + init(_this); + _this.s.init = true; + } + + _this.once('file', function() { + callback(); + }) +} + +/** + * @ignore + */ + +function handleStartOption(stream, doc, cursor, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'more than the length of the file (' + doc.length +')') + } + if (options.start < 0) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'negative'); + } + if (options.end != null && options.end < options.start) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'greater than stream end (' + options.end + ')'); + } + + cursor.skip(Math.floor(options.start / doc.chunkSize)); + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * + doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } +} + +/** + * @ignore + */ + +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new Error('Stream end (' + options.end + ') must not be ' + + 'more than the length of the file (' + doc.length +')') + } + if (options.start < 0) { + throw new Error('Stream end (' + options.end + ') must not be ' + + 'negative'); + } + + var start = options.start != null ? + Math.floor(options.start / doc.chunkSize) : + 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return (Math.ceil(options.end / doc.chunkSize) * doc.chunkSize) - + options.end; + } +} + +/** + * @ignore + */ + +function __handleError(_this, error) { + _this.emit('error', error); +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/index.js new file mode 100644 index 00000000..e0e02c0a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/index.js @@ -0,0 +1,367 @@ +var Emitter = require('events').EventEmitter; +var GridFSBucketReadStream = require('./download'); +var GridFSBucketWriteStream = require('./upload'); +var shallowClone = require('../utils').shallowClone; +var toError = require('../utils').toError; +var util = require('util'); + +var DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +module.exports = GridFSBucket; + +/** + * Constructor for a streaming GridFS interface + * @class + * @param {Db} db A db handle + * @param {object} [options=null] Optional settings. + * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. + * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB + * @param {object} [options.writeConcern=null] Optional write concern to be passed to write operations, for instance `{ w: 1 }` + * @param {object} [options.readPreference=null] Optional read preference to be passed to read operations + * @fires GridFSBucketWriteStream#index + * @return {GridFSBucket} + */ + +function GridFSBucket(db, options) { + Emitter.apply(this); + this.setMaxListeners(0); + + if (options && typeof options === 'object') { + options = shallowClone(options); + var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); + for (var i = 0; i < keys.length; ++i) { + if (!options[keys[i]]) { + options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; + } + } + } else { + options = DEFAULT_GRIDFS_BUCKET_OPTIONS; + } + + this.s = { + db: db, + options: options, + _chunksCollection: db.collection(options.bucketName + '.chunks'), + _filesCollection: db.collection(options.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false, + promiseLibrary: db.s.promiseLibrary || + (typeof global.Promise == 'function' ? global.Promise : require('es6-promise').Promise) + }; +} + +util.inherits(GridFSBucket, Emitter); + +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * + * @event GridFSBucket#index + * @type {Error} + */ + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options=null] Optional settings. + * @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStream = function(filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string|number|object} id A custom id used to identify the file + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options=null] Optional settings. + * @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + + options.id = id; + + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming file + * data from GridFS. + * @method + * @param {ObjectId} id The id of the file doc + * @param {Object} [options=null] Optional settings. + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStream = function(id, options) { + var filter = { _id: id }; + options = { + start: options && options.start, + end: options && options.end + }; + + return new GridFSBucketReadStream(this.s._chunksCollection, + this.s._filesCollection, this.s.options.readPreference, filter, options); +}; + +/** + * Deletes a file with the given id + * @method + * @param {ObjectId} id The id of the file doc + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.delete = function(id, callback) { + if (typeof callback === 'function') { + return _delete(this, id, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _delete(_this, id, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _delete(_this, id, callback) { + _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { + if (error) { + return callback(error); + } + + _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res.result.n) { + var errmsg = 'FileNotFound: no file with id ' + id + ' found'; + return callback(new Error(errmsg)); + } + + callback(); + }); + }); +} + +/** + * Convenience wrapper around find on the files collection + * @method + * @param {Object} filter + * @param {Object} [options=null] Optional settings for cursor + * @param {number} [options.batchSize=null] Optional batch size for cursor + * @param {number} [options.limit=null] Optional limit for cursor + * @param {number} [options.maxTimeMS=null] Optional maxTimeMS for cursor + * @param {boolean} [options.noCursorTimeout=null] Optionally set cursor's `noCursorTimeout` flag + * @param {number} [options.skip=null] Optional skip for cursor + * @param {object} [options.sort=null] Optional sort for cursor + * @return {Cursor} + */ + +GridFSBucket.prototype.find = function(filter, options) { + filter = filter || {}; + options = options || {}; + + var cursor = this.s._filesCollection.find(filter); + + if (options.batchSize != null) { + cursor.batchSize(options.batchSize); + } + if (options.limit != null) { + cursor.limit(options.limit); + } + if (options.maxTimeMS != null) { + cursor.maxTimeMS(options.maxTimeMS); + } + if (options.noCursorTimeout != null) { + cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); + } + if (options.skip != null) { + cursor.skip(options.skip); + } + if (options.sort != null) { + cursor.sort(options.sort); + } + + return cursor; +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + * @method + * @param {String} filename The name of the file to stream + * @param {Object} [options=null] Optional settings + * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { + var sort = { uploadDate: -1 }; + var skip = null; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + + var filter = { filename: filename }; + options = { + sort: sort, + skip: skip, + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream(this.s._chunksCollection, + this.s._filesCollection, this.s.options.readPreference, filter, options); +}; + +/** + * Renames the file with the given _id to the given string + * @method + * @param {ObjectId} id the id of the file to rename + * @param {String} filename new name for the file + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.rename = function(id, filename, callback) { + if (typeof callback === 'function') { + return _rename(this, id, filename, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _rename(_this, id, filename, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _rename(_this, id, filename, callback) { + var filter = { _id: id }; + var update = { $set: { filename: filename } }; + _this.s._filesCollection.updateOne(filter, update, function(error, res) { + if (error) { + return callback(error); + } + if (!res.result.n) { + return callback(toError('File with id ' + id + ' not found')); + } + callback(); + }); +} + +/** + * Removes this bucket's files collection, followed by its chunks collection. + * @method + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.drop = function(callback) { + if (typeof callback === 'function') { + return _drop(this, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _drop(_this, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _drop(_this, callback) { + _this.s._filesCollection.drop(function(error) { + if (error) { + return callback(error); + } + _this.s._chunksCollection.drop(function(error) { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} + +/** + * Callback format for all GridFSBucket methods that can accept a callback. + * @callback GridFSBucket~errorCallback + * @param {MongoError} error An error instance representing any errors that occurred + */ diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/upload.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/upload.js new file mode 100644 index 00000000..1ce36164 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs-stream/upload.js @@ -0,0 +1,520 @@ +var core = require('mongodb-core'); +var crypto = require('crypto'); +var stream = require('stream'); +var util = require('util'); + +var ERROR_NAMESPACE_NOT_FOUND = 26; + +module.exports = GridFSBucketWriteStream; + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * + * @class + * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options=null] Optional settings. + * @param {string|number|object} [options.id=null] Custom file id for the GridFS file. + * @param {number} [options.chunkSizeBytes=null] The chunk size to use, in bytes + * @param {number} [options.w=null] The write concern + * @param {number} [options.wtimeout=null] The write concern timeout + * @param {number} [options.j=null] The journal write concern + * @fires GridFSBucketWriteStream#error + * @fires GridFSBucketWriteStream#finish + * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. + */ + +function GridFSBucketWriteStream(bucket, filename, options) { + options = options || {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + + this.id = options.id ? options.id : core.BSON.ObjectId(); + this.chunkSizeBytes = this.options.chunkSizeBytes; + this.bufToStore = new Buffer(this.chunkSizeBytes); + this.length = 0; + this.md5 = crypto.createHash('md5'); + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false, + promiseLibrary: this.bucket.s.promiseLibrary + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + var _this = this; + checkIndexes(this, function() { + _this.bucket.s.checkedIndexes = true; + _this.bucket.emit('index'); + }); + } +} + +util.inherits(GridFSBucketWriteStream, stream.Writable); + +/** + * An error occurred + * + * @event GridFSBucketWriteStream#error + * @type {Error} + */ + +/** + * `end()` was called and the write stream successfully wrote the file + * metadata and all the chunks to MongoDB. + * + * @event GridFSBucketWriteStream#finish + * @type {object} + */ + +/** + * Write a buffer to the stream. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. + */ + +GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { + var _this = this; + return waitForIndexes(this, function() { + return doWrite(_this, chunk, encoding, callback); + }); +}; + +/** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @method + * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred + * @return {Promise} if no callback specified + */ + +GridFSBucketWriteStream.prototype.abort = function(callback) { + if (this.state.streamEnd) { + var error = new Error('Cannot abort a stream that has already completed'); + if (typeof callback == 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + if (this.state.aborted) { + error = new Error('Cannot call abort() on a stream twice'); + if (typeof callback == 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, function(error) { + if(typeof callback == 'function') callback(error); + }); +}; + +/** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB + */ + +GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { + var _this = this; + if(typeof chunk == 'function') { + callback = chunk, chunk = null, encoding = null; + } else if(typeof encoding == 'function') { + callback = encoding, encoding = null; + } + + if (checkAborted(this, callback)) { + return; + } + this.state.streamEnd = true; + + if (callback) { + this.once('finish', function(result) { + callback(null, result); + }); + } + + if (!chunk) { + waitForIndexes(this, function() { + writeRemnant(_this); + }); + return; + } + + this.write(chunk, encoding, function() { + writeRemnant(_this); + }); +}; + +/** + * @ignore + */ + +function __handleError(_this, error, callback) { + if (_this.state.errored) { + return; + } + _this.state.errored = true; + if (callback) { + return callback(error); + } + _this.emit('error', error); +} + +/** + * @ignore + */ + +function createChunkDoc(filesId, n, data) { + return { + _id: core.BSON.ObjectId(), + files_id: filesId, + n: n, + data: data + }; +} + +/** + * @ignore + */ + +function checkChunksIndex(_this, callback) { + _this.chunks.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { files_id: 1, n: 1 }; + _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + var hasChunksIndex = false; + indexes.forEach(function(index) { + if (index.key) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && + index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + + if (hasChunksIndex) { + callback(); + } else { + index = { files_id: 1, n: 1 }; + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + indexOptions.unique = true; + + _this.chunks.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + } + }); +} + +/** + * @ignore + */ + +function checkDone(_this, callback) { + if (_this.state.streamEnd && + _this.state.outstandingRequests === 0 && + !_this.state.errored) { + var filesDoc = createFilesDoc(_this.id, _this.length, _this.chunkSizeBytes, + _this.md5.digest('hex'), _this.filename, _this.options.contentType, + _this.options.aliases, _this.options.metadata); + + if (checkAborted(_this, callback)) { + return false; + } + + _this.files.insert(filesDoc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error, callback); + } + _this.emit('finish', filesDoc); + }); + + return true; + } + + return false; +} + +/** + * @ignore + */ + +function checkIndexes(_this, callback) { + _this.files.findOne({}, { _id: 1 }, function(error, doc) { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + _this.files.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { filename: 1, uploadDate: 1 }; + _this.files.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + return; + } + return callback(error); + } + + var hasFileIndex = false; + indexes.forEach(function(index) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && + index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + + if (hasFileIndex) { + checkChunksIndex(_this, callback); + } else { + index = { filename: 1, uploadDate: 1 }; + + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + + _this.files.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + } + }); + }); +} + +/** + * @ignore + */ + +function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, + aliases, metadata) { + var ret = { + _id: _id, + length: length, + chunkSize: chunkSize, + uploadDate: new Date(), + md5: md5, + filename: filename + }; + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +/** + * @ignore + */ + +function doWrite(_this, chunk, encoding, callback) { + if (checkAborted(_this, callback)) { + return false; + } + + var inputBuf = (Buffer.isBuffer(chunk)) ? + chunk : new Buffer(chunk, encoding); + + _this.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { + inputBuf.copy(_this.bufToStore, _this.pos); + _this.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + var inputBufRemaining = inputBuf.length; + var spaceRemaining = _this.chunkSizeBytes - _this.pos; + var numToCopy = Math.min(spaceRemaining, inputBuf.length); + var outstandingRequests = 0; + while (inputBufRemaining > 0) { + var inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(_this.bufToStore, _this.pos, + inputBufPos, inputBufPos + numToCopy); + _this.pos += numToCopy; + spaceRemaining -= numToCopy; + if (spaceRemaining === 0) { + _this.md5.update(_this.bufToStore); + var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); + ++_this.state.outstandingRequests; + ++outstandingRequests; + + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insert(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + _this.emit('drain', doc); + callback && callback(); + checkDone(_this); + } + }); + + spaceRemaining = _this.chunkSizeBytes; + _this.pos = 0; + ++_this.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +/** + * @ignore + */ + +function getWriteOptions(_this) { + var obj = {}; + if (_this.options.writeConcern) { + obj.w = _this.options.writeConcern.w; + obj.wtimeout = _this.options.writeConcern.wtimeout; + obj.j = _this.options.writeConcern.j; + } + return obj; +} + +/** + * @ignore + */ + +function waitForIndexes(_this, callback) { + if (_this.bucket.s.checkedIndexes) { + return callback(false); + } + + _this.bucket.once('index', function() { + callback(true); + }); + + return true; +} + +/** + * @ignore + */ + +function writeRemnant(_this, callback) { + // Buffer is empty, so don't bother to insert + if (_this.pos === 0) { + return checkDone(_this, callback); + } + + ++_this.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + var remnant = new Buffer(_this.pos); + _this.bufToStore.copy(remnant, 0, 0, _this.pos); + _this.md5.update(remnant); + var doc = createChunkDoc(_this.id, _this.n, remnant); + + // If the stream was aborted, do not write remnant + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insert(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + checkDone(_this); + }); +} + +/** + * @ignore + */ + +function checkAborted(_this, callback) { + if (_this.state.aborted) { + if(typeof callback == 'function') { + callback(new Error('this stream has been aborted')); + } + return true; + } + return false; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs/chunk.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 00000000..9100197d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,230 @@ +"use strict"; + +var Binary = require('mongodb-core').BSON.Binary, + ObjectID = require('mongodb-core').BSON.ObjectID; + +/** + * Class for representing a single chunk in GridFS. + * + * @class + * + * @param file {GridStore} The {@link GridStore} object holding this chunk. + * @param mongoObject {object} The mongo object representation of this chunk. + * + * @throws Error when the type of data field for {@link mongoObject} is not + * supported. Currently supported types for data field are instances of + * {@link String}, {@link Array}, {@link Binary} and {@link Binary} + * from the bson module + * + * @see Chunk#buildMongoObject + */ +var Chunk = function(file, mongoObject, writeConcern) { + if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || {w:1}; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if(typeof mongoObjectFinal.data == "string") { + var buffer = new Buffer(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if(Array.isArray(mongoObjectFinal.data)) { + buffer = new Buffer(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if(mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if(!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)){ + throw Error("Illegal chunk format"); + } + + // Update position + this.internalPosition = 0; +}; + +/** + * Writes a data to this object and advance the read/write head. + * + * @param data {string} the data to write + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.write = function(data, callback) { + this.data.write(data, this.internalPosition, data.length, 'binary'); + this.internalPosition = this.data.length(); + if(callback != null) return callback(null, this); + return this; +}; + +/** + * Reads data and advances the read/write head. + * + * @param length {number} The length of data to read. + * + * @return {string} The data read if the given length will not exceed the end of + * the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.read = function(length) { + // Default to full read if no index defined + length = length == null || length == 0 ? this.length() : length; + + if(this.length() - this.internalPosition + 1 >= length) { + var data = this.data.read(this.internalPosition, length); + this.internalPosition = this.internalPosition + length; + return data; + } else { + return ''; + } +}; + +Chunk.prototype.readSlice = function(length) { + if ((this.length() - this.internalPosition) >= length) { + var data = null; + if (this.data.buffer != null) { //Pure BSON + data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); + } else { //Native BSON + data = new Buffer(length); + length = this.data.readInto(data, this.internalPosition); + } + this.internalPosition = this.internalPosition + length; + return data; + } else { + return null; + } +}; + +/** + * Checks if the read/write head is at the end. + * + * @return {boolean} Whether the read/write head has reached the end of this + * chunk. + */ +Chunk.prototype.eof = function() { + return this.internalPosition == this.length() ? true : false; +}; + +/** + * Reads one character from the data of this chunk and advances the read/write + * head. + * + * @return {string} a single character data read if the the read/write head is + * not at the end of the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.getc = function() { + return this.read(1); +}; + +/** + * Clears the contents of the data in this chunk and resets the read/write head + * to the initial position. + */ +Chunk.prototype.rewind = function() { + this.internalPosition = 0; + this.data = new Binary(); +}; + +/** + * Saves this chunk to the database. Also overwrites existing entries having the + * same id as this chunk. + * + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.save = function(options, callback) { + var self = this; + if(typeof options == 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if(err) return callback(err); + + // Merge the options + var writeOptions = { upsert: true }; + for(var name in options) writeOptions[name] = options[name]; + for(name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + if(self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = {forceServerObjectId:true}; + for(var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.replaceOne({'_id':self.objectId}, mongoObject, writeOptions, function(err) { + callback(err, self); + }); + }); + } else { + callback(null, self); + } + // }); + }); +}; + +/** + * Creates a mongoDB object representation of this chunk. + * + * @param callback {function(Object)} This will be called after executing this + * method. The object will be passed to the first parameter and will have + * the structure: + * + * <pre><code> + * { + * '_id' : , // {number} id for this chunk + * 'files_id' : , // {number} foreign key to the file collection + * 'n' : , // {number} chunk number + * 'data' : , // {bson#Binary} the chunk data itself + * } + * </code></pre> + * + * @see <a href="http://www.mongodb.org/display/DOCS/GridFS+Specification#GridFSSpecification-{{chunks}}">MongoDB GridFS Chunk Object Structure</a> + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + 'files_id': this.file.fileId, + 'n': this.chunkNumber, + 'data': this.data}; + // If we are saving using a specific ObjectId + if(this.objectId != null) mongoObject._id = this.objectId; + + callback(mongoObject); +}; + +/** + * @return {number} the length of the data + */ +Chunk.prototype.length = function() { + return this.data.length(); +}; + +/** + * The position of the read/write head + * @name position + * @lends Chunk# + * @field + */ +Object.defineProperty(Chunk.prototype, "position", { enumerable: true + , get: function () { + return this.internalPosition; + } + , set: function(value) { + this.internalPosition = value; + } +}); + +/** + * The default chunk size + * @constant + */ +Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; + +module.exports = Chunk; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs/grid_store.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 00000000..27dd8ce0 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1951 @@ +"use strict"; + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found <a href="http://www.mongodb.org/display/DOCS/GridFS">here</a>. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * GridStore = require('mongodb').GridStore, + * ObjectID = require('mongodb').ObjectID, + * test = require('assert'); + * + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * var gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * db.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +var Chunk = require('./chunk'), + ObjectID = require('mongodb-core').BSON.ObjectID, + ReadPreference = require('../read_preference'), + Buffer = require('buffer').Buffer, + Collection = require('../collection'), + fs = require('fs'), + f = require('util').format, + util = require('util'), + Define = require('../metadata'), + MongoError = require('mongodb-core').MongoError, + inherits = util.inherits, + Duplex = require('stream').Duplex || require('readable-stream').Duplex, + shallowClone = require('../utils').shallowClone; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +/** + * Namespace provided by the mongodb-core and node.js + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwriten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata=null] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + this.db = db; + + // Handle options + if(typeof options === 'undefined') options = {}; + // Handle mode + if(typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if(typeof mode == 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if(id && id._bsontype == 'ObjectID') { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if(typeof filename == 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? "r" : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.PRIMARY; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, "chunkSize", { enumerable: true + , get: function () { + return this.internalChunkSize; + } + , set: function(value) { + if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, "md5", { enumerable: true + , get: function () { + return this.internalMd5; + } + }); + + Object.defineProperty(this, "chunkNumber", { enumerable: true + , get: function () { + return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; + } + }); +} + +var define = GridStore.define = new Define('Gridstore', GridStore, true); + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.open = function(callback) { + var self = this; + if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ + throw MongoError.create({message: "Illegal mode " + this.mode, driver:true}); + } + + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + open(self, function(err, store) { + if(err) return reject(err); + resolve(store); + }) + }); +}; + +var open = function(self, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if((self.mode == "w" || self.mode == "w+")) { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function() { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Make an unique index for compatibility with mongo-cxx-driver:legacy + var chunkIndexOptions = shallowClone(writeConcern); + chunkIndexOptions.unique = true; + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { + // Open the connection + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +} + +// Push the definition for open +define.classMethod('open', {callback: true, promise:true}); + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.eof = function() { + return this.position == this.length ? true : false; +} + +define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]}); + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.getc = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return eof(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + eof(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var eof = function(self, callback) { + if(self.eof()) { + callback(null, null); + } else if(self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +} + +define.classMethod('getc', {callback: true, promise:true}); + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.puts = function(string, callback) { + var self = this; + var finalString = string.match(/\n$/) == null ? string + "\n" : string; + // We provided a callback leg + if(typeof callback == 'function') return this.write(finalString, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + self.write(finalString, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('puts', {callback: true, promise:true}); + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +} + +define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]}); + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.write = function write(data, close, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return _writeNormal(this, data, close, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + _writeNormal(self, data, close, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('write', {callback: true, promise:true}); + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if(!this.writable) return; + this.readable = false; + if(this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.writeFile = function (file, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return writeFile(self, file, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + writeFile(self, file, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var writeFile = function(self, file, callback) { + if (typeof file === 'string') { + fs.open(file, 'r', function (err, fd) { + if(err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function (err, self) { + if(err) return callback(err, self); + + fs.fstat(file, function (err, stats) { + if(err) return callback(err, self); + + var offset = 0; + var index = 0; + + // Write a chunk + var writeChunk = function() { + fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { + if(err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, {n:index++}, self.writeConcern); + chunk.write(data, function(err, chunk) { + if(err) return callback(err, self); + + chunk.save({}, function(err) { + if(err) return callback(err, self); + + self.position = self.position + data.length; + + // Point to current chunk + self.currentChunk = chunk; + + if(offset >= stats.size) { + fs.close(file); + self.close(function(err) { + if(err) return callback(err, self); + return callback(null, self); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + } + + // Process the first write + process.nextTick(writeChunk); + }); + }); +} + +define.classMethod('writeFile', {callback: true, promise:true}); + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.close = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return close(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + close(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var close = function(self, callback) { + if(self.mode[0] == "w") { + // Set up options + var options = self.writeConcern; + + if(self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err) { + if(err && typeof callback == 'function') return callback(err); + + self.collection(function(err, files) { + if(err && typeof callback == 'function') return callback(err); + + // Build the mongo object + if(self.uploadDate != null) { + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if(err && typeof callback == 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + }); + } + } else if(self.mode[0] == "r") { + if(typeof callback == 'function') + callback(null, null); + } else { + if(typeof callback == 'function') + callback(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true})); + } +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.chunkCollection = function(callback) { + if(typeof callback == 'function') + return this.db.collection((this.root + ".chunks"), callback); + return this.db.collection((this.root + ".chunks")); +}; + +define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]}); + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.unlink = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return unlink(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + unlink(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlink = function(self, callback) { + deleteChunks(self, function(err) { + if(err!==null) { + err.message = "at deleteChunks: " + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if(err!==null) { + err.message = "at collection: " + err.message; + return callback(err); + } + + collection.remove({'_id':self.fileId}, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +} + +define.classMethod('unlink', {callback: true, promise:true}); + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.collection = function(callback) { + if(typeof callback == 'function') + this.db.collection(this.root + ".files", callback); + return this.db.collection(this.root + ".files"); +}; + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.readlines = function(separator, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : "\n"; + separator = separator || "\n"; + + // We provided a callback leg + if(typeof callback == 'function') return readlines(self, separator, callback); + + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + readlines(self, separator, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlines = function(self, separator, callback) { + self.read(function(err, data) { + if(err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for(var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +} + +define.classMethod('readlines', {callback: true, promise:true}); + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.rewind = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return rewind(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + rewind(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var rewind = function(self, callback) { + if(self.currentChunk.chunkNumber != 0) { + if(self.mode[0] == "w") { + deleteChunks(self, function(err) { + if(err) return callback(err); + self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if(err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +} + +define.classMethod('rewind', {callback: true, promise:true}); + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.read = function(length, buffer, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + // We provided a callback leg + if(typeof callback == 'function') return read(self, length, buffer, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + read(self, length, buffer, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var read = function(self, length, buffer, callback) { + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if(finalLength == 0 && finalBuffer.length == 0) return callback(MongoError.create({message: "File does not exist", driver:true}), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if(err) return callback(err); + + if(chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if(finalBuffer._index > 0) { + callback(null, finalBuffer) + } else { + callback(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null); + } + } + }); +} + +define.classMethod('read', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve) { + resolve(self.position); + }); +}; + +define.classMethod('tell', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.seek = function(position, seekLocation, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + seekLocation = args.length ? args.shift() : null; + + // We provided a callback leg + if(typeof callback == 'function') return seek(self, position, seekLocation, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + seek(self, position, seekLocation, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var seek = function(self, position, seekLocation, callback) { + // Seek only supports read mode + if(self.mode != 'r') { + return callback(MongoError.create({message: "seek is only supported for mode r", driver:true})) + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if(seekLocationFinal == GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if(seekLocationFinal == GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition/self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + if(err) return callback(err, null); + if(chunk == null) return callback(new Error('no chunk found')); + + // Set the current chunk + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = (self.position % self.chunkSize); + callback(err, self); + }); + }; + + seekChunk(); +} + +define.classMethod('seek', {callback: true, promise:true}); + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if(query != null) { + collection.findOne(query, options, function(err, doc) { + if(err) return error(err); + + // Check if the collection for the files exists otherwise prepare the new one + if(doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode != 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId._bsontype == "ObjectID" ? self.fileId.toHexString() : self.fileId; + return error(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), self); + } + + // Process the mode of the object + if(self.mode == "r") { + nthChunk(self, 0, options, function(err, chunk) { + if(err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w" && doc) { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if(err) return error(err); + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w") { + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + } else if(self.mode == "w+") { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if(err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + // No file exists set up write mode + if(self.mode == "w") { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if(err) return error(err); + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w+") { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if(err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error (err) { + if(error.err) return; + callback(error.err = err); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if(typeof close === "function") { callback = close; close = null; } + var finalClose = typeof close == 'boolean' ? close : false; + + if(self.mode != "w") { + callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), null); + } else { + if(self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while(leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); + firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); + // If we have left over data write it + if(leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for(var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err) { + if(err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if(numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if(finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if(finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + * <pre><code> + * { + * '_id' : , // {number} id for this file + * 'filename' : , // {string} name for this file + * 'contentType' : , // {string} mime type for this file + * 'length' : , // {number} size of this file? + * 'chunksize' : , // {number} chunk size used by this file + * 'uploadDate' : , // {Date} + * 'aliases' : , // {array of string} + * 'metadata' : , // {string} + * } + * </code></pre> + * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + '_id': self.fileId, + 'filename': self.filename, + 'contentType': self.contentType, + 'length': self.position ? self.position : 0, + 'chunkSize': self.chunkSize, + 'uploadDate': self.uploadDate, + 'aliases': self.aliases, + 'metadata': self.metadata + }; + + var md5Command = {filemd5:self.fileId, root:self.root}; + self.db.command(md5Command, function(err, results) { + if(err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) { + if(err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if(self.fileId != null) { + self.chunkCollection().remove({'files_id':self.fileId}, options, function(err) { + if(err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** +* The collection to be used for holding the files and chunks collection. +* +* @classconstant DEFAULT_ROOT_COLLECTION +**/ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** +* Default file mime type +* +* @classconstant DEFAULT_CONTENT_TYPE +**/ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** +* Seek mode where the given length is absolute. +* +* @classconstant IO_SEEK_SET +**/ +GridStore.IO_SEEK_SET = 0; + +/** +* Seek mode where the given length is an offset to the current read/write head. +* +* @classconstant IO_SEEK_CUR +**/ +GridStore.IO_SEEK_CUR = 1; + +/** +* Seek mode where the given length is an offset to the end of the file. +* +* @classconstant IO_SEEK_END +**/ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + exists(db, fileIdObject, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + ".files", function(err, collection) { + if(err) return callback(err); + + // Build query + var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) + ? {'filename':fileIdObject} + : {'_id':fileIdObject}; // Attempt to locate file + + // We have a specific query + if(fileIdObject != null + && typeof fileIdObject == 'object' + && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, {readPreference:readPreference}, function(err, item) { + if(err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +} + +define.staticMethod('exist', {callback: true, promise:true}); + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return list(db, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + list(db, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if(rootCollection != null && typeof rootCollection == 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection((rootCollectionFinal + ".files"), function(err, collection) { + if(err) return callback(err); + + collection.find({}, {readPreference:readPreference}, function(err, cursor) { + if(err) return callback(err); + + cursor.each(function(err, item) { + if(item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +} + +define.staticMethod('list', {callback: true, promise:true}); + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readStatic(db, name, length, offset, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + new GridStore(db, name, "r", options).open(function(err, gridStore) { + if(err) return callback(err); + // Make sure we are not reading out of bounds + if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); + if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); + if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); + + if(offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if(err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +} + +define.staticMethod('read', {callback: true, promise:true}); + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readlinesStatic(db, name, separator, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + var finalSeperator = separator == null ? "\n" : separator; + new GridStore(db, name, "r", options).open(function(err, gridStore) { + if(err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +} + +define.staticMethod('readlines', {callback: true, promise:true}); + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options=null] Optional settings. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.unlink = function(db, names, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback); + + // Return promise + return new promiseLibrary(function(resolve, reject) { + unlinkStatic(self, db, names, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if(names.constructor == Array) { + var tc = 0; + for(var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function() { + if(--tc == 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, "w", options).open(function(err, gridStore) { + if(err) return callback(err); + deleteChunks(gridStore, function(err) { + if(err) return callback(err); + gridStore.collection(function(err, collection) { + if(err) return callback(err); + collection.remove({'_id':gridStore.fileId}, writeConcern, function(err) { + callback(err, self); + }); + }); + }); + }); + } +} + +define.staticMethod('unlink', {callback: true, promise:true}); + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, callback) { + // If we have a buffer write it using the writeBuffer method + if(Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, new Buffer(data, 'binary'), close, callback); + } +} + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if(options.w != null) finalOptions.w = options.w; + if(options.journal == true) finalOptions.j = options.journal; + if(options.j == true) finalOptions.j = options.j; + if(options.fsync == true) finalOptions.fsync = options.fsync; + if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +} + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = {w:1}; + options = options || {}; + + // Local options verification + if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { + finalOptions = _setWriteConcernHash(options); + } else if(options.safe != null && typeof options.safe == 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if(typeof options.safe == "boolean") { + finalOptions = {w: (options.safe ? 1 : 0)}; + } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { + finalOptions = _setWriteConcernHash(self.options); + } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) { + finalOptions = _setWriteConcernHash(self.safe); + } else if(typeof self.safe == "boolean") { + finalOptions = {w: (self.safe ? 1 : 0)}; + } + + // Ensure we don't have an invalid combination of write concerns + if(finalOptions.w < 1 + && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true}); + + // Return the options + return finalOptions; +} + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStoreStream = function(gs) { + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +} + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if(!self.gs.isOpen) { + self.gs.open(function(err) { + if(err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } + + return destination; +} + +// Called by stream +GridStoreStream.prototype._read = function() { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if(err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if(self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if(buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if(buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if(self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + } + + // Set read length + var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if(!self.gs.isOpen) { + self.gs.open(function(err) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if(err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +} + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +} + +GridStoreStream.prototype.write = function(chunk) { + var self = this; + if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true})) + // Do we have to open the gridstore + if(!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +} + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if(chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); + }); + } + + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); +} + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/metadata.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/metadata.js new file mode 100644 index 00000000..2c6fe94d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/metadata.js @@ -0,0 +1,64 @@ +var f = require('util').format; + +var Define = function(name, object, stream) { + this.name = name; + this.object = object; + this.stream = typeof stream == 'boolean' ? stream : false; + this.instrumentations = {}; +} + +Define.prototype.classMethod = function(name, options) { + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +var generateKey = function(keys, options) { + var parts = []; + for(var i = 0; i < keys.length; i++) { + parts.push(f('%s=%s', keys[i], options[keys[i]])); + } + + return parts.join(); +} + +Define.prototype.staticMethod = function(name, options) { + options.static = true; + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +Define.prototype.generate = function() { + // Generate the return object + var object = { + name: this.name, obj: this.object, stream: this.stream, + instrumentations: [] + } + + for(var name in this.instrumentations) { + object.instrumentations.push(this.instrumentations[name]); + } + + return object; +} + +module.exports = Define; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/mongo_client.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 00000000..55421d91 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,327 @@ +"use strict"; + +var parse = require('./url_parser') + , Server = require('./server') + , Mongos = require('./mongos') + , ReplSet = require('./replset') + , Define = require('./metadata') + , ReadPreference = require('./read_preference') + , Logger = require('mongodb-core').Logger + , MongoError = require('mongodb-core').MongoError + , Db = require('./db') + , f = require('util').format + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new MongoClient instance + * @class + * @return {MongoClient} a MongoClient instance. + */ +function MongoClient() { + /** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The connected database. + */ + + /** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ + this.connect = MongoClient.connect; +} + +var define = MongoClient.define = new Define('MongoClient', MongoClient, false); + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.connect = function(url, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Return a promise + if(typeof callback != 'function') { + return new promiseLibrary(function(resolve, reject) { + connect(url, options, function(err, db) { + if(err) return reject(err); + resolve(db); + }); + }); + } + + // Fallback to callback based connect + connect(url, options, callback); +} + +define.staticMethod('connect', {callback: true, promise:true}); + +var mergeOptions = function(target, source, flatten) { + for(var name in source) { + if(source[name] && typeof source[name] == 'object' && flatten) { + target = mergeOptions(target, source[name], flatten); + } else { + target[name] = source[name]; + } + } + + return target; +} + +var createUnifiedOptions = function(finalOptions, options) { + var childOptions = ['mongos', 'server', 'db' + , 'replset', 'db_options', 'server_options', 'rs_options', 'mongos_options']; + var noMerge = []; + + for(var name in options) { + if(noMerge.indexOf(name.toLowerCase()) != -1) { + finalOptions[name] = options[name]; + } else if(childOptions.indexOf(name.toLowerCase()) != -1) { + finalOptions = mergeOptions(finalOptions, options[name], false); + } else { + if(options[name] && typeof options[name] == 'object' && !Buffer.isBuffer(options[name]) && !Array.isArray(options[name])) { + finalOptions = mergeOptions(finalOptions, options[name], true); + } else { + finalOptions[name] = options[name]; + } + } + } + + return finalOptions; +} + +function translateOptions(options) { + // If we have a readPreference passed in by the db options + if(typeof options.readPreference == 'string' || typeof options.read_preference == 'string') { + options.readPreference = new ReadPreference(options.readPreference || options.read_preference); + } + + // Do we have readPreference tags, add them + if(options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { + options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; + } + + // Do we have maxStalenessSeconds + if(options.maxStalenessSeconds) { + options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; + } + + // Set the socket and connection timeouts + if(options.socketTimeoutMS == null) options.socketTimeoutMS = 30000; + if(options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; + + // Create server instances + return options.servers.map(function(serverObj) { + return serverObj.domain_socket ? + new Server(serverObj.domain_socket, 27017, options) + : new Server(serverObj.host, serverObj.port, options); + }); +} + +function createReplicaset(options, callback) { + // Set default options + var servers = translateOptions(options); + // Create Db instance + new Db(options.dbName, new ReplSet(servers, options), options).open(callback); +} + +function createMongos(options, callback) { + // Set default options + var servers = translateOptions(options); + // Create Db instance + new Db(options.dbName, new Mongos(servers, options), options).open(callback); +} + +function createServer(options, callback) { + // Set default options + var servers = translateOptions(options); + // Create Db instance + new Db(options.dbName, servers[0], options).open(function(err, db) { + if(err) return callback(err); + // Check if we are really speaking to a mongos + var ismaster = db.serverConfig.lastIsMaster(); + + // Do we actually have a mongos + if(ismaster && ismaster.msg == 'isdbgrid') { + // Destroy the current connection + db.close(); + // Create mongos connection instead + return createMongos(options, callback); + } + + // Otherwise callback + callback(err, db); + }); +} + +function connectHandler(options, callback) { + return function (err, db) { + if(err) { + return process.nextTick(function() { + try { + callback(err, null); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + + // No authentication just reconnect + if(!options.auth) { + return process.nextTick(function() { + try { + callback(err, db); + } catch (err) { + if(db) db.close(); + throw err + } + }) + } + + // What db to authenticate against + var authentication_db = db; + if(options.authSource) { + authentication_db = db.db(options.authSource); + } + + // Authenticate + authentication_db.authenticate(options.user, options.password, options, function(err, success){ + if(success){ + process.nextTick(function() { + try { + callback(null, db); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } else { + if(db) db.close(); + process.nextTick(function() { + try { + callback(err ? err : new Error('Could not authenticate user ' + options.auth[0]), null); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + }); + } +} + +/* + * Connect using MongoClient + */ +var connect = function(url, options, callback) { + options = options || {}; + options = shallowClone(options); + + // If callback is null throw an exception + if(callback == null) { + throw new Error("no callback function provided"); + } + + // Get a logger for MongoClient + var logger = Logger('MongoClient', options); + + // Parse the string + var object = parse(url, options); + var _finalOptions = createUnifiedOptions({}, object); + _finalOptions = mergeOptions(_finalOptions, object, false); + _finalOptions = createUnifiedOptions(_finalOptions, options); + + // Check if we have connection and socket timeout set + if(_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 30000; + if(_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; + + // Failure modes + if(object.servers.length == 0) { + throw new Error("connection string must contain at least one seed host"); + } + + function connectCallback(err, db) { + if(err && err.message == 'no mongos proxies found in seed list') { + if(logger.isWarn()) { + logger.warn(f('seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name')); + } + + // Return a more specific error message for MongoClient.connect + return callback(new MongoError('seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name')); + } + + // Return the error and db instance + callback(err, db); + } + + // Do we have a replicaset then skip discovery and go straight to connectivity + if(_finalOptions.replicaSet || _finalOptions.rs_name) { + return createReplicaset(_finalOptions, connectHandler(_finalOptions, connectCallback)); + } else if(object.servers.length > 1) { + return createMongos(_finalOptions, connectHandler(_finalOptions, connectCallback)); + } else { + return createServer(_finalOptions, connectHandler(_finalOptions, connectCallback)); + } +} + +module.exports = MongoClient diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/mongos.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/mongos.js new file mode 100644 index 00000000..4b83eef5 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/mongos.js @@ -0,0 +1,514 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , MongoError = require('mongodb-core').MongoError + , CMongos = require('mongodb-core').Mongos + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Server = require('./server') + , Store = require('./topology_base').Store + , MAX_JS_INT = require('./utils').MAX_JS_INT + , translateOptions = require('./utils').translateOptions + , filterOptions = require('./utils').filterOptions + , mergeOptions = require('./utils').mergeOptions + , os = require('os'); + +// Get package.json variable +var driverVersion = require(__dirname + '/../package.json').version; +var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); +var type = os.type(); +var name = process.platform; +var architecture = process.arch; +var release = os.release(); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Mongos = require('mongodb').Mongos, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using Mongos + * var server = new Server('localhost', 27017); + * var db = new Db('test', new Mongos([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + + // Allowed parameters + var legalOptionNames = ['ha', 'haInterval', 'acceptableLatencyMS' + , 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate' + , 'sslCA', 'sslCert', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries' + , 'store', 'auto_reconnect', 'autoReconnect', 'emitError' + , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS' + , 'loggerLevel', 'logger', 'reconnectTries', 'appname', 'domainsEnabled' + , 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers']; + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @property {string} parserType the parser type used (c++ or js). + * @return {Mongos} a Mongos instance. + */ +var Mongos = function(servers, options) { + if(!(this instanceof Mongos)) return new Mongos(servers, options); + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Stored options + var storeOptions = { + force: false + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : MAX_JS_INT + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions({}, { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError == 'boolean' ? options.emitError : true, + size: typeof options.poolSize == 'number' ? options.poolSize : 5 + }); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + if(typeof clonedOptions.keepAlive == 'number') { + clonedOptions.keepAliveInitialDelay = clonedOptions.keepAlive; + clonedOptions.keepAlive = clonedOptions.keepAlive > 0; + } + + // Build default client information + this.clientInfo = { + driver: { + name: "nodejs", + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + }, + platform: nodejsversion + } + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if(options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Create the Mongos + var mongos = new CMongos(seedlist, clonedOptions) + // Server capabilities + var sCapabilities = null; + + // Internal state + this.s = { + // Create the Mongos + mongos: mongos + // Server capabilities + , sCapabilities: sCapabilities + // Debug turned on + , debug: clonedOptions.debug + // Store option defaults + , storeOptions: storeOptions + // Cloned options + , clonedOptions: clonedOptions + // Actual store of callbacks + , store: store + // Options + , options: options + } +} + +var define = Mongos.define = new Define('Mongos', Mongos, false); + +/** + * @ignore + */ +inherits(Mongos, EventEmitter); + +// Last ismaster +Object.defineProperty(Mongos.prototype, 'isMasterDoc', { + enumerable:true, get: function() { return this.s.mongos.lastIsMaster(); } +}); + +Object.defineProperty(Mongos.prototype, 'parserType', { + enumerable:true, get: function() { + return this.s.mongos.parserType; + } +}); + +// BSON property +Object.defineProperty(Mongos.prototype, 'bson', { + enumerable: true, get: function() { + return this.s.mongos.s.bson; + } +}); + +Object.defineProperty(Mongos.prototype, 'haInterval', { + enumerable:true, get: function() { return this.s.mongos.s.haInterval; } +}); + +// Connect +Mongos.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.mongos.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect'); + self.s.store.execute(); + } + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', + 'topologyClosed', 'topologyDescriptionChanged'].forEach(function(e) { + self.s.mongos.removeAllListeners(e); + }); + + // Set up listeners + self.s.mongos.once('timeout', errorHandler('timeout')); + self.s.mongos.once('error', errorHandler('error')); + self.s.mongos.once('close', errorHandler('close')); + + // Set up SDAM listeners + self.s.mongos.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.mongos.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.mongos.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.mongos.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.mongos.on('serverOpening', relay('serverOpening')); + self.s.mongos.on('serverClosed', relay('serverClosed')); + self.s.mongos.on('topologyOpening', relay('topologyOpening')); + self.s.mongos.on('topologyClosed', relay('topologyClosed')); + self.s.mongos.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + + // Set up serverConfig listeners + self.s.mongos.on('fullsetup', relay('fullsetup')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + self.s.mongos.once('timeout', connectErrorHandler('timeout')); + self.s.mongos.once('error', connectErrorHandler('error')); + self.s.mongos.once('close', connectErrorHandler('close')); + self.s.mongos.once('connect', connectHandler); + // Join and leave events + self.s.mongos.on('joined', relay('joined')); + self.s.mongos.on('left', relay('left')); + + // Reconnect server + self.s.mongos.on('reconnect', reconnectHandler); + + // Start connection + self.s.mongos.connect(_options); +} + +// Server capabilities +Mongos.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.mongos.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Mongos.prototype.command = function(ns, cmd, options, callback) { + this.s.mongos.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Mongos.prototype.insert = function(ns, ops, options, callback) { + this.s.mongos.insert(ns, ops, options, function(e, m) { + callback(e, m) + }); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Mongos.prototype.update = function(ns, ops, options, callback) { + this.s.mongos.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Mongos.prototype.remove = function(ns, ops, options, callback) { + this.s.mongos.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// Destroyed +Mongos.prototype.isDestroyed = function() { + return this.s.mongos.isDestroyed(); +} + +// IsConnected +Mongos.prototype.isConnected = function() { + return this.s.mongos.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Mongos.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.mongos.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Mongos.prototype.lastIsMaster = function() { + return this.s.mongos.lastIsMaster(); +} + +Mongos.prototype.close = function(forceClosed) { + this.s.mongos.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Mongos.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.mongos.auth.apply(this.s.mongos, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +Mongos.prototype.logout = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.mongos.logout.apply(this.s.mongos, args); +} + +define.classMethod('logout', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Mongos.prototype.connections = function() { + return this.s.mongos.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +module.exports = Mongos; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/read_preference.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 00000000..dde9d8aa --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,131 @@ +"use strict"; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * ReadPreference = require('mongodb').ReadPreference, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * test.equal(null, err); + * // Perform a read + * var cursor = db.collection('t').find({}); + * cursor.setReadPreference(ReadPreference.PRIMARY); + * cursor.toArray(function(err, docs) { + * test.equal(null, err); + * db.close(); + * }); + * }); + */ + +/** + * Creates a new ReadPreference instance + * + * Read Preferences + * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). + * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. + * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. + * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. + * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. + * + * @class + * @param {string} mode The ReadPreference mode as listed above. + * @param {array|object} tags An object representing read preference tags. + * @param {object} [options] Additional read preference options + * @param {number} [options.maxStalenessSeconds] Max Secondary Read Stalleness in Seconds + * @return {ReadPreference} a ReadPreference instance. + */ +var ReadPreference = function(mode, tags, options) { + if(!(this instanceof ReadPreference)) { + return new ReadPreference(mode, tags, options); + } + + this._type = 'ReadPreference'; + this.mode = mode; + this.tags = tags; + this.options = options; + + // If no tags were passed in + if(tags && typeof tags == 'object' && !Array.isArray(tags)) { + if(tags.maxStalenessSeconds) { + this.options = tags; + this.tags = null; + } + } + + // Add the maxStalenessSeconds value to the read Preference + if(this.options && this.options.maxStalenessSeconds) { + this.maxStalenessSeconds = this.options.maxStalenessSeconds; + } +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +ReadPreference.isValid = function(_mode) { + return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED + || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED + || _mode == ReadPreference.NEAREST + || _mode == true || _mode == false || _mode == null); +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +ReadPreference.prototype.isValid = function(mode) { + var _mode = typeof mode == 'string' ? mode : this.mode; + return ReadPreference.isValid(_mode); +} + +/** + * @ignore + */ +ReadPreference.prototype.toObject = function() { + var object = {mode:this.mode}; + + if(this.tags != null) { + object['tags'] = this.tags; + } + + if(this.maxStalenessSeconds) { + object['maxStalenessSeconds'] = this.maxStalenessSeconds; + } + + return object; +} + +/** + * @ignore + */ +ReadPreference.prototype.toJSON = function() { + return this.toObject(); +} + +/** + * @ignore + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest' + +/** + * @ignore + */ +module.exports = ReadPreference; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/replset.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/replset.js new file mode 100644 index 00000000..5214b4ce --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/replset.js @@ -0,0 +1,568 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , Server = require('./server') + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , CReplSet = require('mongodb-core').ReplSet + , CoreReadPreference = require('mongodb-core').ReadPreference + , MAX_JS_INT = require('./utils').MAX_JS_INT + , translateOptions = require('./utils').translateOptions + , filterOptions = require('./utils').filterOptions + , mergeOptions = require('./utils').mergeOptions + , os = require('os'); +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +// Allowed parameters +var legalOptionNames = ['ha', 'haInterval', 'replicaSet', 'rs_name', 'secondaryAcceptableLatencyMS' + , 'connectWithNoPrimary', 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate' + , 'sslCA', 'sslCert', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries' + , 'store', 'auto_reconnect', 'autoReconnect', 'emitError' + , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS', 'strategy', 'debug' + , 'loggerLevel', 'logger', 'reconnectTries', 'appname', 'domainsEnabled' + , 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers']; + +// Get package.json variable +var driverVersion = require(__dirname + '/../package.json').version; +var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); +var type = os.type(); +var name = process.platform; +var architecture = process.arch; +var release = os.release(); + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=10000] Time between each replicaset status check. + * @param {string} [options.replicaSet] The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @property {string} parserType the parser type used (c++ or js). + * @return {ReplSet} a ReplSet instance. + */ +var ReplSet = function(servers, options) { + if(!(this instanceof ReplSet)) return new ReplSet(servers, options); + options = options || {}; + var self = this; + // Set up event emitter + EventEmitter.call(this); + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Stored options + var storeOptions = { + force: false + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : MAX_JS_INT + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Clone options + var clonedOptions = mergeOptions({}, { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError == 'boolean' ? options.emitError : true, + size: typeof options.poolSize == 'number' ? options.poolSize : 5 + }); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + if(typeof clonedOptions.keepAlive == 'number') { + clonedOptions.keepAliveInitialDelay = clonedOptions.keepAlive; + clonedOptions.keepAlive = clonedOptions.keepAlive > 0; + } + + // Client info + this.clientInfo = { + driver: { + name: "nodejs", + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + }, + platform: nodejsversion + } + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if(options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Create the ReplSet + var replset = new CReplSet(seedlist, clonedOptions); + + // Listen to reconnect event + replset.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + replset: replset + // Server capabilities + , sCapabilities: null + // Debug tag + , tag: options.tag + // Store options + , storeOptions: storeOptions + // Cloned options + , clonedOptions: clonedOptions + // Store + , store: store + // Options + , options: options + } + + // Debug + if(clonedOptions.debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable:true, get: function() { return replset; } + }); + } +} + +/** + * @ignore + */ +inherits(ReplSet, EventEmitter); + +// Last ismaster +Object.defineProperty(ReplSet.prototype, 'isMasterDoc', { + enumerable:true, get: function() { return this.s.replset.lastIsMaster(); } +}); + +Object.defineProperty(ReplSet.prototype, 'parserType', { + enumerable:true, get: function() { + return this.s.replset.parserType; + } +}); + +// BSON property +Object.defineProperty(ReplSet.prototype, 'bson', { + enumerable: true, get: function() { + return this.s.replset.s.bson; + } +}); + +Object.defineProperty(ReplSet.prototype, 'haInterval', { + enumerable:true, get: function() { return this.s.replset.s.haInterval; } +}); + +var define = ReplSet.define = new Define('ReplSet', ReplSet, false); + +// Ensure the right read Preference object +var translateReadPreference = function(options) { + if(typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags, {maxStalenessSeconds: options.readPreference.maxStalenessSeconds}); + } + + return options; +} + +// Connect method +ReplSet.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', + 'topologyClosed', 'topologyDescriptionChanged'].forEach(function(e) { + self.s.replset.removeAllListeners(e); + }); + + // Set up listeners + self.s.replset.once('timeout', errorHandler('timeout')); + self.s.replset.once('error', errorHandler('error')); + self.s.replset.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + } + } + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if(t == 'start') { + self.emit('ha_connect', t, state); + } else if(t == 'end') { + self.emit('ha_ismaster', t, state); + } + } + + // Set up serverConfig listeners + self.s.replset.on('joined', replsetRelay('joined')); + self.s.replset.on('left', relay('left')); + self.s.replset.on('ping', relay('ping')); + self.s.replset.on('ha', relayHa); + + // Set up SDAM listeners + self.s.replset.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.replset.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.replset.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.replset.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.replset.on('serverOpening', relay('serverOpening')); + self.s.replset.on('serverClosed', relay('serverClosed')); + self.s.replset.on('topologyOpening', relay('topologyOpening')); + self.s.replset.on('topologyClosed', relay('topologyClosed')); + self.s.replset.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + + self.s.replset.on('fullsetup', function() { + self.emit('fullsetup', null, self); + }); + + self.s.replset.on('all', function() { + self.emit('all', null, self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Error handler + var connectErrorHandler = function() { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.replset.removeListener(e, connectErrorHandler); + }); + + self.s.replset.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.replset.destroy(); + + // Try to callback + try { + callback(err); + } catch(err) { + if(!self.s.replset.isConnected()) + process.nextTick(function() { throw err; }) + } + } + } + + // Set up listeners + self.s.replset.once('timeout', connectErrorHandler('timeout')); + self.s.replset.once('error', connectErrorHandler('error')); + self.s.replset.once('close', connectErrorHandler('close')); + self.s.replset.once('connect', connectHandler); + + // Start connection + self.s.replset.connect(_options); +} + +// Server capabilities +ReplSet.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.replset.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +ReplSet.prototype.command = function(ns, cmd, options, callback) { + options = translateReadPreference(options); + this.s.replset.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +ReplSet.prototype.insert = function(ns, ops, options, callback) { + this.s.replset.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +ReplSet.prototype.update = function(ns, ops, options, callback) { + this.s.replset.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +ReplSet.prototype.remove = function(ns, ops, options, callback) { + this.s.replset.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// Destroyed +ReplSet.prototype.isDestroyed = function() { + return this.s.replset.isDestroyed(); +} + +// IsConnected +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + + // If we passed in a readPreference, translate to + // a CoreReadPreference instance + if(options.readPreference) { + options.readPreference = translateReadPreference(options.readPreference); + } + + return this.s.replset.isConnected(options); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + return this.s.replset.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +ReplSet.prototype.lastIsMaster = function() { + return this.s.replset.lastIsMaster(); +} + +ReplSet.prototype.close = function(forceClosed) { + var self = this; + this.s.replset.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +define.classMethod('close', {callback: false, promise:false}); + +ReplSet.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.replset.auth.apply(this.s.replset, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +ReplSet.prototype.logout = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.replset.logout.apply(this.s.replset, args); +} + +define.classMethod('logout', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +ReplSet.prototype.connections = function() { + return this.s.replset.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +module.exports = ReplSet; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/server.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/server.js new file mode 100644 index 00000000..2fc17dad --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/server.js @@ -0,0 +1,511 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , CServer = require('mongodb-core').Server + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , MongoError = require('mongodb-core').MongoError + , MAX_JS_INT = require('./utils').MAX_JS_INT + , translateOptions = require('./utils').translateOptions + , filterOptions = require('./utils').filterOptions + , mergeOptions = require('./utils').mergeOptions + , os = require('os'); + +// Get package.json variable +var driverVersion = require(__dirname + '/../package.json').version; +var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); +var type = os.type(); +var name = process.platform; +var architecture = process.arch; +var release = os.release(); + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using single Server + * var db = new Db('test', new Server('localhost', 27017);); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + + // Allowed parameters + var legalOptionNames = ['ha', 'haInterval', 'acceptableLatencyMS' + , 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate' + , 'sslCA', 'sslCert', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries' + , 'store', 'auto_reconnect', 'autoReconnect', 'emitError' + , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS' + , 'loggerLevel', 'logger', 'reconnectTries', 'reconnectInterval', 'monitoring' + , 'appname', 'domainsEnabled' + , 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers']; + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options=null] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Triggers the server instance to call ismaster + * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @property {string} parserType the parser type used (c++ or js). + * @return {Server} a Server instance. + */ +var Server = function(host, port, options) { + options = options || {}; + if(!(this instanceof Server)) return new Server(host, port, options); + EventEmitter.call(this); + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Stored options + var storeOptions = { + force: false + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : MAX_JS_INT + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if(host.indexOf('\/') != -1) { + if(port != null && typeof port == 'object') { + options = port; + port = null; + } + } else if(port == null) { + throw MongoError.create({message: 'port must be specified', driver:true}); + } + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions({}, { + host: host, port: port, disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError == 'boolean' ? options.emitError : true, + size: typeof options.poolSize == 'number' ? options.poolSize : 5 + }); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + if(typeof clonedOptions.keepAlive == 'number') { + clonedOptions.keepAliveInitialDelay = clonedOptions.keepAlive; + clonedOptions.keepAlive = clonedOptions.keepAlive > 0; + } + + // Build default client information + this.clientInfo = { + driver: { + name: "nodejs", + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + }, + platform: nodejsversion + } + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if(options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Create an instance of a server instance from mongodb-core + var server = new CServer(clonedOptions); + + // Define the internal properties + this.s = { + // Create an instance of a server instance from mongodb-core + server: server + // Server capabilities + , sCapabilities: null + // Cloned options + , clonedOptions: clonedOptions + // Reconnect + , reconnect: clonedOptions.reconnect + // Emit error + , emitError: clonedOptions.emitError + // Pool size + , poolSize: clonedOptions.size + // Store Options + , storeOptions: storeOptions + // Store + , store: store + // Host + , host: host + // Port + , port: port + // Options + , options: options + } +} + +inherits(Server, EventEmitter); + +var define = Server.define = new Define('Server', Server, false); + +// BSON property +Object.defineProperty(Server.prototype, 'bson', { + enumerable: true, get: function() { + return this.s.server.s.bson; + } +}); + +// Last ismaster +Object.defineProperty(Server.prototype, 'isMasterDoc', { + enumerable:true, get: function() { + return this.s.server.lastIsMaster(); + } +}); + +Object.defineProperty(Server.prototype, 'parserType', { + enumerable:true, get: function() { + return this.s.server.parserType; + } +}); + +// Last ismaster +Object.defineProperty(Server.prototype, 'poolSize', { + enumerable:true, get: function() { return this.s.server.connections().length; } +}); + +Object.defineProperty(Server.prototype, 'autoReconnect', { + enumerable:true, get: function() { return this.s.reconnect; } +}); + +Object.defineProperty(Server.prototype, 'host', { + enumerable:true, get: function() { return this.s.host; } +}); + +Object.defineProperty(Server.prototype, 'port', { + enumerable:true, get: function() { return this.s.port; } +}); + +// Connect +Server.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.server.removeListener(e, connectHandlers[e]); + }); + + self.s.server.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect', self); + self.s.store.execute(); + } + + // Reconnect failed + var reconnectFailedHandler = function(err) { + self.emit('reconnectFailed', err); + self.s.store.flush(err); + } + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', + 'topologyClosed', 'topologyDescriptionChanged'].forEach(function(e) { + self.s.server.removeAllListeners(e); + }); + + // Set up listeners + self.s.server.on('timeout', errorHandler('timeout')); + self.s.server.once('error', errorHandler('error')); + self.s.server.on('close', errorHandler('close')); + // Only called on destroy + self.s.server.on('destroy', destroyHandler); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Set up SDAM listeners + self.s.server.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.server.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.server.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.server.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.server.on('serverOpening', relay('serverOpening')); + self.s.server.on('serverClosed', relay('serverClosed')); + self.s.server.on('topologyOpening', relay('topologyOpening')); + self.s.server.on('topologyClosed', relay('topologyClosed')); + self.s.server.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.server.on('attemptReconnect', relay('attemptReconnect')); + self.s.server.on('monitoring', relay('monitoring')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + console.log(err.stack) + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Add the event handlers + self.s.server.once('timeout', connectHandlers.timeout); + self.s.server.once('error', connectHandlers.error); + self.s.server.once('close', connectHandlers.close); + self.s.server.once('connect', connectHandler); + // Reconnect server + self.s.server.on('reconnect', reconnectHandler); + self.s.server.on('reconnectFailed', reconnectFailedHandler); + + // Start connection + self.s.server.connect(_options); +} + +// Server capabilities +Server.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.server.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Server.prototype.command = function(ns, cmd, options, callback) { + this.s.server.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Server.prototype.insert = function(ns, ops, options, callback) { + this.s.server.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Server.prototype.update = function(ns, ops, options, callback) { + this.s.server.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Server.prototype.remove = function(ns, ops, options, callback) { + this.s.server.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +Server.prototype.isConnected = function() { + return this.s.server.isConnected(); +} + +Server.prototype.isDestroyed = function() { + return this.s.server.isDestroyed(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Server.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.server.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Server.prototype.lastIsMaster = function() { + return this.s.server.lastIsMaster(); +} + +/** + * Unref all sockets + * @method + */ +Server.prototype.unref = function() { + this.s.server.unref(); +} + +Server.prototype.close = function(forceClosed) { + this.s.server.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Server.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.server.auth.apply(this.s.server, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +Server.prototype.logout = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.server.logout.apply(this.s.server, args); +} + +define.classMethod('logout', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Server.prototype.connections = function() { + return this.s.server.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +module.exports = Server; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/topology_base.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/topology_base.js new file mode 100644 index 00000000..ebfd616e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/topology_base.js @@ -0,0 +1,191 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError + , f = require('util').format; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} + + // Internal state + this.s = { + storedOps: storedOps + , storeOptions: storeOptions + , topology: topology + } + + Object.defineProperty(this, 'length', { + enumerable:true, get: function() { return self.s.storedOps.length; } + }); +} + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true})); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) +} + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) +} + +Store.prototype.flush = function(err) { + while(this.s.storedOps.length > 0) { + this.s.storedOps.shift().c(err || MongoError.create({message: f("no connection available for operation"), driver:true })); + } +} + +var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; +var secondaryOptions = ['secondary', 'secondaryPreferred']; + +Store.prototype.execute = function(options) { + options = options || {}; + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Unpack options + var executePrimary = typeof options.executePrimary === 'boolean' + ? options.executePrimary : true; + var executeSecondary = typeof options.executeSecondary === 'boolean' + ? options.executeSecondary : true; + + // Execute all the stored ops + while(ops.length > 0) { + var op = ops.shift(); + + if(op.t == 'cursor') { + if(executePrimary && executeSecondary) { + op.o[op.m].apply(op.o, op.p); + } else if(executePrimary && op.o.options + && op.o.options.readPreference + && primaryOptions.indexOf(op.o.options.readPreference.mode) != -1) { + op.o[op.m].apply(op.o, op.p); + } else if(!executePrimary && executeSecondary && op.o.options + && op.o.options.readPreference + && secondaryOptions.indexOf(op.o.options.readPreference.mode) != -1) { + op.o[op.m].apply(op.o, op.p); + } + } else if(op.t == 'auth') { + this.s.topology[op.t].apply(this.s.topology, op.o); + } else { + if(executePrimary && executeSecondary) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if(executePrimary && op.op && op.op.readPreference + && primaryOptions.indexOf(op.op.readPreference.mode) != -1) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if(!executePrimary && executeSecondary && op.op && op.op.readPreference + && secondaryOptions.indexOf(op.op.readPreference.mode) != -1) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } + } +} + +Store.prototype.all = function() { + return this.s.storedOps; +} + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true + , get: function () { return value; } + }); + } + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + var commandsTakeWriteConcern = false; + var commandsTakeCollation = false; + + if(ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if(ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if(ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if(ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + if(ismaster.maxWireVersion >= 5) { + commandsTakeWriteConcern = true; + commandsTakeCollation = true; + } + + // If no min or max wire version set to 0 + if(ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if(ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, "hasAggregationCursor", aggregationCursor); + setup_get_property(this, "hasWriteCommands", writeCommands); + setup_get_property(this, "hasTextSearch", textSearch); + setup_get_property(this, "hasAuthCommands", authCommands); + setup_get_property(this, "hasListCollectionsCommand", listCollections); + setup_get_property(this, "hasListIndexesCommand", listIndexes); + setup_get_property(this, "minWireVersion", ismaster.minWireVersion); + setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); + setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); + setup_get_property(this, "commandsTakeWriteConcern", commandsTakeWriteConcern); + setup_get_property(this, "commandsTakeCollation", commandsTakeCollation); +} + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/url_parser.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 00000000..e419bcb7 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,405 @@ +"use strict"; + +var ReadPreference = require('./read_preference'), + parser = require('url'), + f = require('util').format; + +module.exports = function(url) { + // Variables + var connection_part = ''; + var auth_part = ''; + var query_string_part = ''; + var dbName = 'admin'; + + // Url parser result + var result = parser.parse(url, true); + + if(result.protocol != 'mongodb:') { + throw new Error('invalid schema, expected mongodb'); + } + + if((result.hostname == null || result.hostname == '') && url.indexOf('.sock') == -1) { + throw new Error('no hostname or hostnames provided in connection string'); + } + + if(result.port == '0') { + throw new Error('invalid port (zero) with hostname'); + } + + if(!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { + throw new Error('invalid port (larger than 65535) with hostname'); + } + + if(result.path + && result.path.length > 0 + && result.path[0] != '/' + && url.indexOf('.sock') == -1) { + throw new Error('missing delimiting slash between hosts and options'); + } + + if(result.query) { + for(var name in result.query) { + if(name.indexOf('::') != -1) { + throw new Error('double colon in host identifier'); + } + + if(result.query[name] == '') { + throw new Error('query parameter ' + name + ' is an incomplete value pair'); + } + } + } + + if(result.auth) { + var parts = result.auth.split(':'); + if(url.indexOf(result.auth) != -1 && parts.length > 2) { + throw new Error('Username with password containing an unescaped colon'); + } + + if(url.indexOf(result.auth) != -1 && result.auth.indexOf('@') != -1) { + throw new Error('Username containing an unescaped at-sign'); + } + } + + // Remove query + var clean = url.split('?').shift(); + + // Extract the list of hosts + var strings = clean.split(','); + var hosts = []; + + for(var i = 0; i < strings.length; i++) { + var hostString = strings[i]; + + if(hostString.indexOf('mongodb') != -1) { + if(hostString.indexOf('@') != -1) { + hosts.push(hostString.split('@').pop()) + } else { + hosts.push(hostString.substr('mongodb://'.length)); + } + } else if(hostString.indexOf('/') != -1) { + hosts.push(hostString.split('/').shift()); + } else if(hostString.indexOf('/') == -1) { + hosts.push(hostString.trim()); + } + } + + for(i = 0; i < hosts.length; i++) { + var r = parser.parse(f('mongodb://%s', hosts[i].trim())); + if(r.path && r.path.indexOf(':') != -1) { + throw new Error('double colon in host identifier'); + } + } + + // If we have a ? mark cut the query elements off + if(url.indexOf("?") != -1) { + query_string_part = url.substr(url.indexOf("?") + 1); + connection_part = url.substring("mongodb://".length, url.indexOf("?")) + } else { + connection_part = url.substring("mongodb://".length); + } + + // Check if we have auth params + if(connection_part.indexOf("@") != -1) { + auth_part = connection_part.split("@")[0]; + connection_part = connection_part.split("@")[1]; + } + + // Check if the connection string has a db + if(connection_part.indexOf(".sock") != -1) { + if(connection_part.indexOf(".sock/") != -1) { + dbName = connection_part.split(".sock/")[1]; + // Check if multiple database names provided, or just an illegal trailing backslash + if (dbName.indexOf("/") != -1) { + if (dbName.split("/").length == 2 && dbName.split("/")[1].length == 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); + } + } else if(connection_part.indexOf("/") != -1) { + // Check if multiple database names provided, or just an illegal trailing backslash + if (connection_part.split("/").length > 2) { + if (connection_part.split("/")[2].length == 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + dbName = connection_part.split("/")[1]; + connection_part = connection_part.split("/")[0]; + } + + // Result object + var object = {}; + + // Pick apart the authentication part of the string + var authPart = auth_part || ''; + var auth = authPart.split(':', 2); + + // Decode the URI components + auth[0] = decodeURIComponent(auth[0]); + if(auth[1]){ + auth[1] = decodeURIComponent(auth[1]); + } + + // Add auth to final object if we have 2 elements + if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; + + // Variables used for temporary storage + var hostPart; + var urlOptions; + var servers; + var serverOptions = {socketOptions: {}}; + var dbOptions = {read_preference_tags: []}; + var replSetServersOptions = {socketOptions: {}}; + var mongosOptions = {socketOptions: {}}; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = mongosOptions; + + // Let's check if we are using a domain socket + if(url.match(/\.sock/)) { + // Split out the socket part + var domainSocket = url.substring( + url.indexOf("mongodb://") + "mongodb://".length + , url.lastIndexOf(".sock") + ".sock".length); + // Clean out any auth stuff if any + if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; + servers = [{domain_socket: domainSocket}]; + } else { + // Split up the db + hostPart = connection_part; + // Deduplicate servers + var deduplicatedServers = {}; + + // Parse all server results + servers = hostPart.split(',').map(function(h) { + var _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + var hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; + } + + // No entry returned for duplicate servr + if(deduplicatedServers[_host + "_" + _port]) return null; + deduplicatedServers[_host + "_" + _port] = 1; + + // Return the mapped object + return {host: _host, port: _port}; + }).filter(function(x) { + return x != null; + }); + } + + // Get the db name + object.dbName = dbName || 'admin'; + // Split up all the options + urlOptions = (query_string_part || '').split(/[&;]/); + // Ugh, we have to figure out which options go to which constructor manually. + urlOptions.forEach(function(opt) { + if(!opt) return; + var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; + // Options implementations + switch(name) { + case 'slaveOk': + case 'slave_ok': + serverOptions.slave_ok = (value == 'true'); + dbOptions.slaveOk = (value == 'true'); + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'appname': + object.appname = decodeURIComponent(value); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = (value == 'true'); + break; + case 'minPoolSize': + throw new Error("minPoolSize not supported"); + case 'maxIdleTimeMS': + throw new Error("maxIdleTimeMS not supported"); + case 'waitQueueMultiple': + throw new Error("waitQueueMultiple not supported"); + case 'waitQueueTimeoutMS': + throw new Error("waitQueueTimeoutMS not supported"); + case 'uuidRepresentation': + throw new Error("uuidRepresentation not supported"); + case 'ssl': + if(value == 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + mongosOptions.ssl = value; + break; + } + serverOptions.ssl = (value == 'true'); + replSetServersOptions.ssl = (value == 'true'); + mongosOptions.ssl = (value == 'true'); + break; + case 'sslValidate': + serverOptions.sslValidate = (value == 'true'); + replSetServersOptions.sslValidate = (value == 'true'); + mongosOptions.sslValidate = (value == 'true'); + break; + case 'replicaSet': + case 'rs_name': + replSetServersOptions.rs_name = value; + break; + case 'reconnectWait': + replSetServersOptions.reconnectWait = parseInt(value, 10); + break; + case 'retries': + replSetServersOptions.retries = parseInt(value, 10); + break; + case 'readSecondary': + case 'read_secondary': + replSetServersOptions.read_secondary = (value == 'true'); + break; + case 'fsync': + dbOptions.fsync = (value == 'true'); + break; + case 'journal': + dbOptions.j = (value == 'true'); + break; + case 'safe': + dbOptions.safe = (value == 'true'); + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = (value == 'true'); + break; + case 'readConcernLevel': + dbOptions.readConcern = {level: value}; + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if(isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if(value == 'GSSAPI') { + // If no password provided decode only the principal + if(object.auth == null) { + var urlDecodeAuthPart = decodeURIComponent(authPart); + if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); + object.auth = {user: urlDecodeAuthPart, password: null}; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if(value == 'MONGODB-X509') { + object.auth = {user: decodeURIComponent(authPart)}; + } + + // Only support GSSAPI or MONGODB-CR for now + if(value != 'GSSAPI' + && value != 'MONGODB-X509' + && value != 'MONGODB-CR' + && value != 'DEFAULT' + && value != 'SCRAM-SHA-1' + && value != 'PLAIN') + throw new Error("only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + // Split up into key, value pairs + var values = value.split(','); + var o = {}; + // For each value split into key, value + values.forEach(function(x) { + var v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + if(typeof o.SERVICE_REALM == 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; + if(typeof o.CANONICALIZE_HOST_NAME == 'string') dbOptions.gssapiCanonicalizeHostName = o.CANONICALIZE_HOST_NAME == 'true' ? true : false; + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); + dbOptions.readPreference = value; + break; + case 'maxStalenessSeconds': + dbOptions.maxStalenessSeconds = parseInt(value, 10); + break; + case 'readPreferenceTags': + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + var tagObject = {}; + if(value == null || value == '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + var tags = value.split(/\,/); + for(var i = 0; i < tags.length; i++) { + var parts = tags[i].trim().split(/\:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + break; + default: + break; + } + }); + + // No tags: should be null (not []) + if(dbOptions.read_preference_tags.length === 0) { + dbOptions.read_preference_tags = null; + } + + // Validate if there are an invalid write concern combinations + if((dbOptions.w == -1 || dbOptions.w == 0) && ( + dbOptions.journal == true + || dbOptions.fsync == true + || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") + + // If no read preference set it to primary + if(!dbOptions.readPreference) { + dbOptions.readPreference = 'primary'; + } + + // Add servers to result + object.servers = servers; + // Returned parsed object + return object; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/utils.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/utils.js new file mode 100644 index 00000000..c4c294c1 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/lib/utils.js @@ -0,0 +1,312 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError + +var shallowClone = function(obj) { + var copy = {}; + for(var name in obj) copy[name] = obj[name]; + return copy; +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +var formatSortValue = exports.formatSortValue = function(sortDirection) { + var value = ("" + sortDirection).toLowerCase(); + + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new Error("Illegal sort clause, must be of the form " + + "[['field1', '(ascending|descending)'], " + + "['field2', '(ascending|descending)']]"); + } +}; + +var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { + var orderBy = {}; + if(sortValue == null) return null; + if (Array.isArray(sortValue)) { + if(sortValue.length === 0) { + return null; + } + + for(var i = 0; i < sortValue.length; i++) { + if(sortValue[i].constructor == String) { + orderBy[sortValue[i]] = 1; + } else { + orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); + } + } + } else if(sortValue != null && typeof sortValue == 'object') { + orderBy = sortValue; + } else if (typeof sortValue == 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error("Illegal sort clause, must be of the form " + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); + } + + return orderBy; +}; + +var checkCollectionName = function checkCollectionName (collectionName) { + if('string' !== typeof collectionName) { + throw Error("collection name must be a String"); + } + + if(!collectionName || collectionName.indexOf('..') != -1) { + throw Error("collection names cannot be empty"); + } + + if(collectionName.indexOf('$') != -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { + throw Error("collection names must not contain '$'"); + } + + if(collectionName.match(/^\.|\.$/) != null) { + throw Error("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the colletion name + if(!!~collectionName.indexOf("\x00")) { + throw new Error("collection names cannot contain a null character"); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if(callback == null) return; + if(callback) { + return value2 ? callback(err, value1, value2) : callback(err, value1); + } + } catch(err) { + process.nextTick(function() { throw err; }); + return false; + } + + return true; +} + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = MongoError.create({message: msg, driver:true}); + + // Get all object keys + var keys = typeof error == 'object' + ? Object.keys(error) + : []; + + for(var i = 0; i < keys.length; i++) { + try { + e[keys[i]] = error[keys[i]]; + } catch(err) { + // continue + } + } + + return e; +} + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if(typeof hint == 'string') { + finalHint = hint; + } else if(Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if(hint != null && typeof hint == 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + var fieldHash = {}; + var indexes = []; + var keys; + + // Get all the fields accordingly + if('string' == typeof fieldOrSpec) { + // 'type' + indexes.push(fieldOrSpec + '_' + 1); + fieldHash[fieldOrSpec] = 1; + } else if(Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if('string' == typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if(Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if(isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(function(k) { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if(isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join("_"), keys: keys, fieldHash: fieldHash + } +} + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == toString.call(arg) +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +var decorateCommand = function(command, options, exclude) { + for(var name in options) { + if(exclude[name] == null) command[name] = options[name]; + } + + return command; +} + +var mergeOptions = function(target, source) { + for(var name in source) { + target[name] = source[name]; + } + + return target; +} + +// Merge options with translation +var translateOptions = function(target, source) { + var translations = { + // SSL translation options + 'sslCA': 'ca', 'sslValidate': 'rejectUnauthorized', 'sslKey': 'key', 'sslCert': 'cert', 'sslPass': 'passphrase', + // SocketTimeout translation options + 'socketTimeoutMS': 'socketTimeout', 'connectTimeoutMS': 'connectionTimeout', + // Replicaset options + 'replicaSet': 'setName', 'rs_name': 'setName', 'secondaryAcceptableLatencyMS': 'acceptableLatency', + 'connectWithNoPrimary': 'secondaryOnlyConnectionAllowed', + // Mongos options + 'acceptableLatencyMS': 'localThresholdMS' + } + + for(var name in source) { + if(translations[name]) { + target[translations[name]] = source[name]; + } else { + target[name] = source[name]; + } + } + + return target; +} + +var filterOptions = function(options, names) { + var filterOptions = {}; + + for(var name in options) { + if(names.indexOf(name) != -1) filterOptions[name] = options[name]; + } + + // Filtered options + return filterOptions; +} + +// Object.assign method or polyfille +var assign = Object.assign ? Object.assign : function assign(target) { + if (target === undefined || target === null) { + throw new TypeError('Cannot convert first argument to object'); + } + + var to = Object(target); + for (var i = 1; i < arguments.length; i++) { + var nextSource = arguments[i]; + if (nextSource === undefined || nextSource === null) { + continue; + } + + var keysArray = Object.keys(Object(nextSource)); + for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { + var nextKey = keysArray[nextIndex]; + var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); + if (desc !== undefined && desc.enumerable) { + to[nextKey] = nextSource[nextKey]; + } + } + } + return to; +} + +exports.filterOptions = filterOptions; +exports.mergeOptions = mergeOptions; +exports.translateOptions = translateOptions; +exports.shallowClone = shallowClone; +exports.getSingleProperty = getSingleProperty; +exports.checkCollectionName = checkCollectionName; +exports.toError = toError; +exports.formattedOrderClause = formattedOrderClause; +exports.parseIndexOptions = parseIndexOptions; +exports.normalizeHintField = normalizeHintField; +exports.handleCallback = handleCallback; +exports.decorateCommand = decorateCommand; +exports.isObject = isObject; +exports.debugOptions = debugOptions; +exports.MAX_JS_INT = 0x20000000000000; +exports.assign = assign; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md new file mode 100644 index 00000000..cc8aa107 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md @@ -0,0 +1,65 @@ +# Master + +# 3.2.0 + +* improve tamper resistence of Promise.all Promise.race and + Promise.prototype.then (note, this isn't complete, but addresses an exception + when used \w core-js, follow up work will address entirely) +* remove spec incompatible then chaining fast-path +* add eslint +* update build deps + +# 3.1.2 + +* fix node detection issues with NWJS/electron + +# 3.1.0 + +* improve performance of Promise.all when it encounters a non-promise input object input +* then/resolve tamper protection +* reduce AST size of promise constructor, to facilitate more inlining +* Update README.md with details about PhantomJS requirement for running tests +* Mangle and compress the minified version + +# 3.0.1 + +* no longer include dist/test in npm releases + +# 3.0.0 + +* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of + nodes are not affected as they were already using nextTick(). Note that using nextTick() might + trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410. + The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask + instead of a microtask and might result in a different scheduling. + If needed you can revert to the former behavior as follow: + + var Promise = require('es6-promise').Promise; + Promise._setScheduler(setImmediate); + +# 2.3.0 + +* #121: Ability to override the internal asap implementation +* #120: Use an ascii character for an apostrophe, for source maps + +# 2.2.0 + +* #116: Expose asap() and a way to override the scheduling mechanism on Promise +* Lock to v0.2.3 of ember-cli + +# 2.1.1 + +* Fix #100 via #105: tell browserify to ignore vertx require +* Fix #101 via #102: "follow thenable state, not own state" + +# 2.1.0 + +* ? (see the commit log) + +# 2.0.0 + +* re-sync with RSVP. Many large performance improvements and bugfixes. + +# 1.0.0 + +* first subset of RSVP diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/LICENSE new file mode 100644 index 00000000..954ec599 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/README.md new file mode 100644 index 00000000..16739ca5 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/README.md @@ -0,0 +1,74 @@ +# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) + +This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js) extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). + +For API details and how to use promises, see the <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises HTML5Rocks article</a>. + +## Downloads + +* [es6-promise](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.js) +* [es6-promise-min](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.min.js) + +## Node.js + +To install: + +```sh +npm install es6-promise +``` + +To use: + +```js +var Promise = require('es6-promise').Promise; +``` + +## Bower + +To install: + +```sh +bower install es6-promise --save +``` + + +## Usage in IE<9 + +`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. + +However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: + +```js +promise['catch'](function(err) { + // ... +}); +``` + +Or use `.then` instead: + +```js +promise.then(undefined, function(err) { + // ... +}); +``` + +## Auto-polyfill + +To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: + +```js +require('es6-promise').polyfill(); +``` + +Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. + +## Building & Testing + +You will need to have PhantomJS installed globally in order to run the tests. + +`npm install -g phantomjs` + +* `npm run build` to build +* `npm test` to run tests +* `npm start` to run a build watcher, and webserver to test +* `npm run test:server` for a testem test runner and watching builder diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js new file mode 100644 index 00000000..0755e9b7 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js @@ -0,0 +1,959 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.2.1 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; + + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + } + + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } + + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + function lib$es6$promise$then$$then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + + if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) { + lib$es6$promise$$internal$$makePromise(child); + } + + var state = parent._state; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + } + var lib$es6$promise$then$$default = lib$es6$promise$then$$then; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16); + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { + if (maybeThenable.constructor === promise.constructor && + then === lib$es6$promise$then$$default && + constructor.resolve === lib$es6$promise$promise$resolve$$default) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + var lib$es6$promise$$internal$$id = 0; + function lib$es6$promise$$internal$$nextId() { + return lib$es6$promise$$internal$$id++; + } + + function lib$es6$promise$$internal$$makePromise(promise) { + promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; + } + + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!lib$es6$promise$utils$$isArray(entries)) { + return new Constructor(function(resolve, reject) { + reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function(resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); + this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: lib$es6$promise$then$$default, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) { + lib$es6$promise$$internal$$makePromise(this.promise); + } + + if (lib$es6$promise$utils$$isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + lib$es6$promise$$internal$$fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + lib$es6$promise$$internal$$fulfill(this.promise, this._result); + } + } + } else { + lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError()); + } + } + + function lib$es6$promise$enumerator$$validationError() { + return new Error('Array Methods must be provided an Array'); + } + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var length = this.length; + var input = this._input; + + for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + this._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var c = this._instanceConstructor; + var resolve = c.resolve; + + if (resolve === lib$es6$promise$promise$resolve$$default) { + var then = lib$es6$promise$$internal$$getThen(entry); + + if (then === lib$es6$promise$then$$default && + entry._state !== lib$es6$promise$$internal$$PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === lib$es6$promise$promise$$default) { + var promise = new c(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); + } + } else { + this._willSettleAt(resolve(entry), i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var promise = this.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + this._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, this._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js new file mode 100644 index 00000000..13151c2d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js @@ -0,0 +1,9 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.2.1 + */ + +(function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function n(t){G=t}function r(t){Q=t}function o(){return function(){process.nextTick(a)}}function i(){return function(){B(a)}}function s(){var t=0,e=new X(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){t.port2.postMessage(0)}}function c(){return function(){setTimeout(a,1)}}function a(){for(var t=0;J>t;t+=2){var e=tt[t],n=tt[t+1];e(n),tt[t]=void 0,tt[t+1]=void 0}J=0}function f(){try{var t=require,e=t("vertx");return B=e.runOnLoop||e.runOnContext,i()}catch(n){return c()}}function l(t,e){var n=this,r=new this.constructor(p);void 0===r[rt]&&k(r);var o=n._state;if(o){var i=arguments[o-1];Q(function(){x(o,r,i,n._result)})}else E(n,r,t,e);return r}function h(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return g(n,t),n}function p(){}function _(){return new TypeError("You cannot resolve a promise with itself")}function d(){return new TypeError("A promises callback cannot return that same promise.")}function v(t){try{return t.then}catch(e){return ut.error=e,ut}}function y(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){Q(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?g(t,n):S(t,n))},function(e){r||(r=!0,j(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,j(t,o))},t)}function b(t,e){e._state===it?S(t,e._result):e._state===st?j(t,e._result):E(e,void 0,function(e){g(t,e)},function(e){j(t,e)})}function w(t,n,r){n.constructor===t.constructor&&r===et&&constructor.resolve===nt?b(t,n):r===ut?j(t,ut.error):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function g(e,n){e===n?j(e,_()):t(n)?w(e,n,v(n)):S(e,n)}function A(t){t._onerror&&t._onerror(t._result),T(t)}function S(t,e){t._state===ot&&(t._result=e,t._state=it,0!==t._subscribers.length&&Q(T,t))}function j(t,e){t._state===ot&&(t._state=st,t._result=e,Q(A,t))}function E(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+it]=n,o[i+st]=r,0===i&&t._state&&Q(T,t)}function T(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r,o,i=t._result,s=0;s<e.length;s+=3)r=e[s],o=e[s+n],r?x(n,r,o,i):o(i);t._subscribers.length=0}}function M(){this.error=null}function P(t,e){try{return t(e)}catch(n){return ct.error=n,ct}}function x(t,n,r,o){var i,s,u,c,a=e(r);if(a){if(i=P(r,o),i===ct?(c=!0,s=i.error,i=null):u=!0,n===i)return void j(n,d())}else i=o,u=!0;n._state!==ot||(a&&u?g(n,i):c?j(n,s):t===it?S(n,i):t===st&&j(n,i))}function C(t,e){try{e(function(e){g(t,e)},function(e){j(t,e)})}catch(n){j(t,n)}}function O(){return at++}function k(t){t[rt]=at++,t._state=void 0,t._result=void 0,t._subscribers=[]}function Y(t){return new _t(this,t).promise}function q(t){var e=this;return new e(I(t)?function(n,r){for(var o=t.length,i=0;o>i;i++)e.resolve(t[i]).then(n,r)}:function(t,e){e(new TypeError("You must pass an array to race."))})}function F(t){var e=this,n=new e(p);return j(n,t),n}function D(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function K(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function L(t){this[rt]=O(),this._result=this._state=void 0,this._subscribers=[],p!==t&&("function"!=typeof t&&D(),this instanceof L?C(this,t):K())}function N(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[rt]||k(this.promise),I(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?S(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&S(this.promise,this._result))):j(this.promise,U())}function U(){return new Error("Array Methods must be provided an Array")}function W(){var t;if("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;(!n||"[object Promise]"!==Object.prototype.toString.call(n.resolve())||n.cast)&&(t.Promise=pt)}var z;z=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var B,G,H,I=z,J=0,Q=function(t,e){tt[J]=t,tt[J+1]=e,J+=2,2===J&&(G?G(a):H())},R="undefined"!=typeof window?window:void 0,V=R||{},X=V.MutationObserver||V.WebKitMutationObserver,Z="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),$="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,tt=new Array(1e3);H=Z?o():X?s():$?u():void 0===R&&"function"==typeof require?f():c();var et=l,nt=h,rt=Math.random().toString(36).substring(16),ot=void 0,it=1,st=2,ut=new M,ct=new M,at=0,ft=Y,lt=q,ht=F,pt=L;L.all=ft,L.race=lt,L.resolve=nt,L.reject=ht,L._setScheduler=n,L._setAsap=r,L._asap=Q,L.prototype={constructor:L,then:et,"catch":function(t){return this.then(null,t)}};var _t=N;N.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===ot&&t>n;n++)this._eachEntry(e[n],n)},N.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===nt){var o=v(t);if(o===et&&t._state!==ot)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===pt){var i=new n(p);w(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){e(t)}),e)}else this._willSettleAt(r(t),e)},N.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===ot&&(this._remaining--,t===st?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},N.prototype._willSettleAt=function(t,e){var n=this;E(t,void 0,function(t){n._settledAt(it,e,t)},function(t){n._settledAt(st,e,t)})};var dt=W,vt={Promise:pt,polyfill:dt};"function"==typeof define&&define.amd?define(function(){return vt}):"undefined"!=typeof module&&module.exports?module.exports=vt:"undefined"!=typeof this&&(this.ES6Promise=vt),dt()}).call(this);
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js new file mode 100644 index 00000000..5984f705 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js @@ -0,0 +1,18 @@ +import Promise from './es6-promise/promise'; +import polyfill from './es6-promise/polyfill'; + +var ES6Promise = { + 'Promise': Promise, + 'polyfill': polyfill +}; + +/* global define:true module:true window: true */ +if (typeof define === 'function' && define['amd']) { + define(function() { return ES6Promise; }); +} else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = ES6Promise; +} else if (typeof this !== 'undefined') { + this['ES6Promise'] = ES6Promise; +} + +polyfill(); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js new file mode 100644 index 00000000..aeebf576 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js @@ -0,0 +1,273 @@ +import { + objectOrFunction, + isFunction +} from './utils'; + +import { + asap +} from './asap'; + +import originalThen from './then'; +import originalResolve from './promise/resolve'; + +export var PROMISE_ID = Math.random().toString(36).substring(16); + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch(error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function(promise) { + var sealed = false; + var error = tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function(value) { + resolve(promise, value); + }, function(reason) { + reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then) { + if (maybeThenable.constructor === promise.constructor && + then === originalThen && + constructor.resolve === originalResolve) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then === GET_THEN_ERROR) { + reject(promise, GET_THEN_ERROR.error); + } else if (then === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then)) { + handleForeignThenable(promise, maybeThenable, then); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { return; } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function reject(promise, reason) { + if (promise._state !== PENDING) { return; } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + FULFILLED] = onFulfillment; + subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch(e) { + reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +export { + nextId, + makePromise, + getThen, + noop, + resolve, + reject, + fulfill, + subscribe, + publish, + publishRejection, + initializePromise, + invokeCallback, + FULFILLED, + REJECTED, + PENDING, + handleMaybeThenable +}; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js new file mode 100644 index 00000000..40f1d252 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js @@ -0,0 +1,119 @@ +var len = 0; +var vertxNext; +var customSchedulerFn; + +export var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +} + +export function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +export function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = (typeof window !== 'undefined') ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + return function() { + vertxNext(flush); + }; +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + return function() { + setTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i+=2) { + var callback = queue[i]; + var arg = queue[i+1]; + + callback(arg); + + queue[i] = undefined; + queue[i+1] = undefined; + } + + len = 0; +} + +function attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch(e) { + return useSetTimeout(); + } +} + +var scheduleFlush; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js new file mode 100644 index 00000000..2a7a28f2 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js @@ -0,0 +1,118 @@ +import { + isArray, + isMaybeThenable +} from './utils'; + +import { + noop, + reject, + fulfill, + subscribe, + FULFILLED, + REJECTED, + PENDING, + getThen, + handleMaybeThenable +} from './-internal'; + +import then from './then'; +import Promise from './promise'; +import originalResolve from './promise/resolve'; +import originalThen from './then'; +import { makePromise, PROMISE_ID } from './-internal'; + +export default Enumerator; +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + reject(this.promise, validationError()); + } +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._enumerate = function() { + var length = this.length; + var input = this._input; + + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function(entry, i) { + var c = this._instanceConstructor; + var resolve = c.resolve; + + if (resolve === originalResolve) { + var then = getThen(entry); + + if (then === originalThen && + entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); + } + } else { + this._willSettleAt(resolve(entry), i); + } +}; + +Enumerator.prototype._settledAt = function(state, i, value) { + var promise = this.promise; + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; + +Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function(value) { + enumerator._settledAt(FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(REJECTED, i, reason); + }); +}; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js new file mode 100644 index 00000000..6696dfc6 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js @@ -0,0 +1,26 @@ +/*global self*/ +import Promise from './promise'; + +export default function polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = Promise; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js new file mode 100644 index 00000000..d95951e2 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js @@ -0,0 +1,384 @@ +import { + isFunction +} from './utils'; + +import { + noop, + nextId, + PROMISE_ID, + initializePromise +} from './-internal'; + +import { + asap, + setAsap, + setScheduler +} from './asap'; + +import all from './promise/all'; +import race from './promise/race'; +import Resolve from './promise/resolve'; +import Reject from './promise/reject'; +import then from './then'; + + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +export default Promise; +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = Resolve; +Promise.reject = Reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; + +Promise.prototype = { + constructor: Promise, + +/** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} +*/ + then: then, + +/** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} +*/ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } +}; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js new file mode 100644 index 00000000..03033f0d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js @@ -0,0 +1,52 @@ +import Enumerator from '../enumerator'; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = resolve(2); + var promise3 = resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = reject(new Error("2")); + var promise3 = reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +export default function all(entries) { + return new Enumerator(this, entries).promise; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js new file mode 100644 index 00000000..8c922e31 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js @@ -0,0 +1,86 @@ +import { + isArray +} from "../utils"; + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +export default function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function(resolve, reject) { + reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function(resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js new file mode 100644 index 00000000..63b86cba --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js @@ -0,0 +1,46 @@ +import { + noop, + reject as _reject +} from '../-internal'; + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +export default function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js new file mode 100644 index 00000000..201a545d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js @@ -0,0 +1,48 @@ +import { + noop, + resolve as _resolve +} from '../-internal'; + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +export default function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/then.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/then.js new file mode 100644 index 00000000..f97e946a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/then.js @@ -0,0 +1,34 @@ +import { + invokeCallback, + subscribe, + FULFILLED, + REJECTED, + noop, + makePromise, + PROMISE_ID +} from './-internal'; + +import { asap } from './asap'; + +export default function then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var state = parent._state; + + if (state) { + var callback = arguments[state - 1]; + asap(function(){ + invokeCallback(state, child, callback, parent._result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js new file mode 100644 index 00000000..31ec6f9c --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js @@ -0,0 +1,22 @@ +export function objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); +} + +export function isFunction(x) { + return typeof x === 'function'; +} + +export function isMaybeThenable(x) { + return typeof x === 'object' && x !== null; +} + +var _isArray; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +export var isArray = _isArray; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/package.json new file mode 100644 index 00000000..22bef850 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/es6-promise/package.json @@ -0,0 +1,96 @@ +{ + "name": "es6-promise", + "namespace": "es6-promise", + "version": "3.2.1", + "description": "A lightweight library that provides tools for organizing asynchronous code", + "main": "dist/es6-promise.js", + "directories": { + "lib": "lib" + }, + "files": [ + "dist", + "lib", + "!dist/test" + ], + "devDependencies": { + "babel-eslint": "^6.0.0", + "broccoli-es6-module-transpiler": "^0.5.0", + "broccoli-jshint": "^2.1.0", + "broccoli-merge-trees": "^1.1.1", + "broccoli-replace": "^0.12.0", + "broccoli-stew": "^1.2.0", + "broccoli-uglify-js": "^0.1.3", + "broccoli-watchify": "^0.2.0", + "ember-cli": "2.5.0", + "ember-publisher": "0.0.7", + "git-repo-version": "0.0.3", + "json3": "^3.3.2", + "mocha": "^1.20.1", + "promises-aplus-tests-phantom": "^2.1.0-revise", + "release-it": "0.0.10" + }, + "scripts": { + "build": "ember build", + "build:production": "ember build --environment production", + "start": "ember s", + "test": "ember test", + "test:server": "ember test --server", + "test:node": "ember build && mocha ./dist/test/browserify", + "lint": "jshint lib", + "prepublish": "ember build --environment production", + "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive" + }, + "repository": { + "type": "git", + "url": "git://github.com/jakearchibald/ES6-Promises.git" + }, + "bugs": { + "url": "https://github.com/jakearchibald/ES6-Promises/issues" + }, + "browser": { + "vertx": false + }, + "keywords": [ + "promises", + "futures" + ], + "author": { + "name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors", + "url": "Conversion to ES6 API by Jake Archibald" + }, + "license": "MIT", + "spm": { + "main": "dist/es6-promise.js" + }, + "gitHead": "5df472ec56d5b9fbc76589383852008d46055c61", + "homepage": "https://github.com/jakearchibald/ES6-Promises#readme", + "_id": "es6-promise@3.2.1", + "_shasum": "ec56233868032909207170c39448e24449dd1fc4", + "_from": "es6-promise@3.2.1", + "_npmVersion": "3.8.8", + "_nodeVersion": "5.10.1", + "_npmUser": { + "name": "stefanpenner", + "email": "stefan.penner@gmail.com" + }, + "dist": { + "shasum": "ec56233868032909207170c39448e24449dd1fc4", + "tarball": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.2.1.tgz" + }, + "maintainers": [ + { + "name": "jaffathecake", + "email": "jaffathecake@gmail.com" + }, + { + "name": "stefanpenner", + "email": "stefan.penner@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/es6-promise-3.2.1.tgz_1463027774105_0.6333294357173145" + }, + "_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.2.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml new file mode 100644 index 00000000..a0b4fb6c --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml @@ -0,0 +1 @@ +repo_token: 47iIZ0B3llo2Wc4dxWRltvgdImqcrVDTi diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/.eslintrc b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/.eslintrc new file mode 100644 index 00000000..753e2a52 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/.eslintrc @@ -0,0 +1,15 @@ +{ + "extends": ["eslint:recommended"], + "env": { + "node": true, + "mocha": true + }, + "ecmaFeatures": { + "es6": true, + }, + "plugins": [ + ], + "rules": { + "no-console":0 + } +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md new file mode 100644 index 00000000..e362724d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md @@ -0,0 +1,595 @@ +2.1.2 2016-12-10 +---------------- +* Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. +* Emit reconnect event in primary joining when in connected status for a replicaset. + +2.1.1 2016-12-08 +---------------- +* Updated bson library to 1.0.1. +* Added optional support for bson-ext 1.0.1. + +2.1.0 2016-12-05 +---------------- +* Updated bson library to 1.0.0. +* Added optional support for bson-ext 1.0.0. +* Expose property parserType allowing for identification of currently configured parser. + +2.0.14 2016-11-29 +----------------- +* Updated bson library to 0.5.7. +* Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). +* Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). +* Only check isConnected against availableConnections (Issue #142). +* NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. +* Set default servername to host is not passed through for sni. +* Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). +* NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. +* NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. +* NODE-850 Update Max Staleness implementation. +* NODE-849 username no longer required for MONGODB-X509 auth. +* NODE-848 BSON Regex flags must be alphabetically ordered. +* NODE-846 Create notice for all third party libraries. +* NODE-843 Executing bulk operations overwrites write concern parameter. +* NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. +* NODE-840 Resync CRUD spec tests. +* Unescapable while(true) loop (Issue #152). + +2.0.13 2016-10-21 +----------------- +* Updated bson library to 0.5.6. + - Included cyclic dependency detection +* Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). +* Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). +* Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). +* NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). + +2.0.12 2016-09-15 +----------------- +* fix debug logging message not printing server name. +* fixed application metadata being sent by wrong ismaster. +* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. +* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". +* Updated bson library to 0.5.5. +* Added DBPointer up conversion to DBRef. + +2.0.11 2016-08-29 +----------------- +* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. +* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). +* Ensure promoteBuffers is propagated in same fashion as promoteValues and promoteLongs + +2.0.10 2016-08-23 +----------------- +* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. +* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). + +2.0.9 2016-08-19 +---------------- +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* NODE-798 Driver hangs on count command in replica set with one member. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* Allow passing in servername for TLS connections for SNI support. + +2.0.8 2016-08-16 +---------------- +* Allow execution of store operations indepent of having both a primary and secondary available (Issue #123). +* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. +* Added hashed connection names and fullResult. +* Updated bson library to 0.5.3. +* Wrap callback in nextTick to ensure exceptions are thrown correctly. + +2.0.7 2016-07-28 +---------------- +* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). +* Added better warnings when passing in illegal seed list members to a Mongos topology. +* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. +* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) +* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. +* Initial max staleness implementation for ReplSet and Mongos for 3.4 support. +* Added handling of collation for 3.4 support. + +2.0.6 2016-07-19 +---------------- +* Destroy connection on socket timeout due to newer node versions not closing the socket. + +2.0.5 2016-07-15 +---------------- +* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. +* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. +* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. +* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. + +2.0.4 2016-07-11 +----------------- +* Updated bson to version 0.5.1. +* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. +* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. +* NODE-746 Improves replicaset errors for wrong setName. + +2.0.3 2016-07-08 +----------------- +* Implemented Server Selection Specification test suite. +* Added warning level to logger. +* Added warning message when sockeTimeout < haInterval for Replset/Mongos. + +2.0.2 2016-07-06 +----------------- +* Mongos emits close event on no proxies available or when reconnect attempt fails. +* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. +* Don't throw in auth methods but return error in callback. + +2.0.1 2016-07-05 +----------------- +* Added missing logout method on mongos proxy topology. +* Fixed logger error serialization issue. +* Documentation fixes. + +2.0.0 2016-07-05 +----------------- +* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. +* All authentication methods now handle both auth/reauthenticate and logout events. +* Introduced logout method to get rid of onAll option for logout command. +* Updated bson to 0.5.0 that includes Decimal128 support. + +1.3.21 2016-05-30 +----------------- +* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). +* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. +* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. +* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). +* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. +* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. + +1.3.20 2016-05-25 +----------------- +* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. +* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. +* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. +* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. + +1.3.19 2016-05-17 +----------------- +- Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. +- Set keepAlive to false by default to work around bug in node.js for Windows XP and Windows 2003. +- Ensure replicaset topology destroy is never called by SDAM. +- Ensure all paths are correctly returned on inspectServer in replset. + +1.3.18 2016-04-27 +----------------- +- Hardened cursor connection handling for getMore and killCursor to ensure mid operation connection kill does not throw null exception. +- Fixes for Node 6.0 support. + +1.3.17 2016-04-26 +----------------- +- Added improved handling of reconnect when topology is a single server. +- Added better handling of $query queries passed down for 3.2 or higher. +- Introduced getServerFrom method to topologies to let cursor grab a new pool for getMore and killCursors commands and not use connection pipelining. +- NODE-693 Move authentication to be after ismaster call to avoid authenticating against arbiters. + +1.3.16 2016-04-07 +----------------- +- Only call unref on destroy if it exists to ensure proper working destroy method on early node v0.10.x versions. + +1.3.15 2016-04-06 +----------------- +- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. +- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. + +1.3.14 2016-04-01 +----------------- +- Ensure server inquireServerState exits immediately on server.destroy call. +- Refactored readPreference handling in 2.4, 2.6 and 3.2 wire protocol handling. + +1.3.13 2016-03-30 +----------------- +- Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. + +1.3.12 2016-03-29 +----------------- +- Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. + +1.3.11 2016-03-29 +----------------- +- isConnected method for mongos uses same selection code as getServer. +- Exceptions in cursor getServer trapped and correctly delegated to high level handler. + +1.3.10 2016-03-22 +----------------- +- SDAM Monitoring emits diff for Replicasets to simplify detecting the state changes. +- SDAM Monitoring correctly emits Mongos as serverDescriptionEvent. + +1.3.9 2016-03-20 +---------------- +- Removed monitoring exclusive connection, should resolve timeouts and reconnects on idle replicasets where haInteval > socketTimeout. + +1.3.8 2016-03-18 +---------------- +- Implements the SDAM monitoring specification. +- Fix issue where cursor would error out and not be buffered when primary is not connected. + +1.3.7 2016-03-16 +---------------- +- Fixed issue with replicasetInquirer where it could stop performing monitoring if there was no servers available. + +1.3.6 2016-03-15 +---------------- +- Fixed raise condition where multiple replicasetInquirer operations could be started in parallel creating redundant connections. + +1.3.5 2016-03-14 +---------------- +- Handle rogue SSL exceptions (Issue #85, https://github.com/durran). + +1.3.4 2016-03-14 +---------------- +- Added unref options on server, replicaset and mongos (Issue #81, https://github.com/allevo) +- cursorNotFound flag always false (Issue #83, https://github.com/xgfd) +- refactor of events emission of fullsetup and all events (Issue #84, https://github.com/xizhibei) + +1.3.3 2016-03-08 +---------------- +- Added support for promoteLongs option for command function. +- Return connection if no callback available +- Emit connect event when server reconnects after initial connection failed (Issue #76, https://github.com/vkarpov15) +- Introduced optional monitoringSocketTimeout option to allow better control of SDAM monitoring timeouts. +- Made monitoringSocketTimeout default to 30000 if no connectionTimeout value specified or if set to 0. +- Fixed issue where tailable cursor would not retry even though cursor was still alive. +- Disabled exhaust flag support to avoid issues where users could easily write code that would cause memory to run out. +- Handle the case where the first command result document returns an empty list of documents but a live cursor. +- Allow passing down off CANONICALIZE_HOST_NAME and SERVICE_REALM options for kerberos. + +1.3.2 2016-02-09 +---------------- +- Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. +- Ensure RequestId can never be larger than Max Number integer size. + +1.3.1 2016-02-05 +---------------- +- Removed annoying missing Kerberos error (NODE-654). + +1.3.0 2016-02-03 +---------------- +- Added raw support for the command function on topologies. +- Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +- Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +- Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +- NODE-638, Cannot authenticate database user with utf-8 password. +- Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +- Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +- Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +- Switched to using Array.push instead of concat for use cases of a lot of documents. +- Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +- Added peer optional dependencies support using require_optional module. + +1.2.32 2016-01-12 +----------------- +- Bumped bson to V0.4.21 to allow using minor optimizations. + +1.2.31 2016-01-04 +----------------- +- Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +1.2.30 2015-12-23 +----------------- +- Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +- Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +1.2.29 2015-12-17 +----------------- +- Correctly emit close event when calling destroy on server topology. + +1.2.28 2015-12-13 +----------------- +- Backed out Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous) as it breaks node 0.10.x support. + +1.2.27 2015-12-13 +----------------- +- Added [options.checkServerIdentity=true] {boolean|function}. Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function, (Issue #29). +- Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous). +- State is not defined in mongos, (Issue #63, https://github.com/flyingfisher). +- Fixed corner case issue on exhaust cursors on pre 3.0.x MongoDB. + +1.2.26 2015-11-23 +----------------- +- Converted test suite to use mongodb-topology-manager. +- Upgraded bson library to V0.4.20. +- Minor fixes for 3.2 readPreferences. + +1.2.25 2015-11-23 +----------------- +- Correctly error out when passed a seedlist of non-valid server members. + +1.2.24 2015-11-20 +----------------- +- Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). +- $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + +1.2.23 2015-11-16 +----------------- +- ismaster runs against admin.$cmd instead of system.$cmd. + +1.2.22 2015-11-16 +----------------- +- Fixes to handle getMore command errors for MongoDB 3.2 +- Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +1.2.21 2015-11-07 +----------------- +- Hardened the checking for replicaset equality checks. +- OpReplay flag correctly set on Wire protocol query. +- Mongos load balancing added, introduced localThresholdMS to control the feature. +- Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +1.2.20 2015-10-28 +----------------- +- Fixed bug in arbiter connection capping code. +- NODE-599 correctly handle arrays of server tags in order of priority. +- Fix for 2.6 wire protocol handler related to readPreference handling. +- Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +- Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +1.2.19 2015-10-15 +----------------- +- Make batchSize always be > 0 for 3.2 wire protocol to make it work consistently with pre 3.2 servers. +- Locked to bson 0.4.19. + +1.2.18 2015-10-15 +----------------- +- Minor 3.2 fix for handling readPreferences on sharded commands. +- Minor fixes to correctly pass APM specification test suite. + +1.2.17 2015-10-08 +----------------- +- Connections to arbiters only maintain a single connection. + +1.2.15 2015-10-06 +----------------- +- Set slaveOk to true for getMore and killCursors commands. +- Don't swallow callback errors for 2.4 single server (Issue #49, https://github.com/vkarpov15). +- Apply toString('hex') to each buffer in an array when logging (Issue #48, https://github.com/nbrachet). + +1.2.14 2015-09-28 +----------------- +- NODE-547 only emit error if there are any listeners. +- Fixed APM issue with issuing readConcern. + +1.2.13 2015-09-18 +----------------- +- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. + +1.2.12 2015-09-08 +----------------- +- NODE-541 Added initial support for readConcern. + +1.2.11 2015-08-31 +----------------- +- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. +- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. +- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). + +1.2.10 2015-08-14 +----------------- +- Added missing Mongos.prototype.parserType function. + +1.2.9 2015-08-05 +---------------- +- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +- NODE-518 connectTimeoutMS is doubled in 2.0.39. + +1.2.8 2015-07-24 +----------------- +- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. + +1.2.7 2015-07-16 +----------------- +- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. + +1.2.6 2015-07-14 +----------------- +- NODE-505 Query fails to find records that have a 'result' property with an array value. + +1.2.5 2015-07-14 +----------------- +- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. + +1.2.4 2015-07-07 +----------------- +- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. + +1.2.3 2015-06-26 +----------------- +- Minor bug fixes. + +1.2.2 2015-06-22 +----------------- +- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). + +1.2.1 2015-06-17 +----------------- +- Ensure serializeFunctions passed down correctly to wire protocol. + +1.2.0 2015-06-17 +----------------- +- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. +- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. +- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +1.1.33 2015-05-31 +----------------- +- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. + +1.1.32 2015-05-20 +----------------- +- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) + +1.1.31 2015-05-19 +----------------- +- Minor fixes for issues with re-authentication of mongos. + +1.1.30 2015-05-18 +----------------- +- Correctly emit 'all' event when primary + all secondaries have connected. + +1.1.29 2015-05-17 +----------------- +- NODE-464 Only use a single socket against arbiters and hidden servers. +- Ensure we filter out hidden servers from any server queries. + +1.1.28 2015-05-12 +----------------- +- Fixed buffer compare for electionId for < node 12.0.2 + +1.1.27 2015-05-12 +----------------- +- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. + +1.1.26 2015-05-06 +----------------- +- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. +- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. + +1.1.25 2015-04-24 +----------------- +- Handle lack of callback in crud operations when returning error on application closed. + +1.1.24 2015-04-22 +----------------- +- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. + +1.1.23 2015-04-15 +----------------- +- Standardizing mongoErrors and its API (Issue #14) +- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) +- remove mkdirp and rimraf dependencies (Issue #12) +- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) +- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) +- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) + +1.1.22 2015-04-10 +----------------- +- Minor refactorings in cursor code to make extending the cursor simpler. +- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. + +1.1.21 2015-03-26 +----------------- +- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. + +1.1.20 2015-03-24 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. + +1.1.19 2015-03-21 +----------------- +- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. + +1.1.18 2015-03-17 +----------------- +- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. + +1.1.17 2015-03-16 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. + +1.1.16 2015-03-06 +----------------- +- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. + +1.1.15 2015-03-04 +----------------- +- Removed check for type in replset pickserver function. + +1.1.14 2015-02-26 +----------------- +- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads + +1.1.13 2015-02-24 +----------------- +- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) + +1.1.12 2015-02-16 +----------------- +- Fixed cursor transforms for buffered document reads from cursor. + +1.1.11 2015-02-02 +----------------- +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +1.1.10 2015-31-01 +----------------- +- Added tranforms.doc option to cursor to allow for pr. document transformations. + +1.1.9 2015-21-01 +---------------- +- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. +- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. +- Don't treat findOne() as a command cursor. +- Refactored out state changes into methods to simplify read the next method. + +1.1.8 2015-09-12 +---------------- +- Stripped out Object.defineProperty for performance reasons +- Applied more performance optimizations. +- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit + +1.1.7 2014-18-12 +---------------- +- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. + +1.1.6 2014-18-12 +---------------- +- Server manager fixed to support 2.2.X servers for travis test matrix. + +1.1.5 2014-17-12 +---------------- +- Fall back to errmsg when creating MongoError for command errors + +1.1.4 2014-17-12 +---------------- +- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. +- Fixed variable leak in scram. +- Fixed server manager to deal better with killing processes. +- Bumped bson to 0.2.16. + +1.1.3 2014-01-12 +---------------- +- Fixed error handling issue with nonce generation in mongocr. +- Fixed issues with restarting servers when using ssl. +- Using strict for all classes. +- Cleaned up any escaping global variables. + +1.1.2 2014-20-11 +---------------- +- Correctly encoding UTF8 collection names on wire protocol messages. +- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. + +1.1.1 2014-14-11 +---------------- +- Refactored code to use prototype instead of privileged methods. +- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. +- Several deopt optimizations for v8 to improve performance and reduce GC pauses. + +1.0.5 2014-29-10 +---------------- +- Fixed issue with wrong namespace being created for command cursors. + +1.0.4 2014-24-10 +---------------- +- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. + +1.0.3 2014-21-10 +---------------- +- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. + +1.0.2 2014-07-10 +---------------- +- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. +- fixed issue with replset_state logging. + +1.0.1 2014-07-10 +---------------- +- Dependency issue solved + +1.0.0 2014-07-10 +---------------- +- Initial release of mongodb-core diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/LICENSE new file mode 100644 index 00000000..ad410e11 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/LICENSE @@ -0,0 +1,201 @@ +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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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.
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/Makefile b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/Makefile new file mode 100644 index 00000000..36e12024 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/README.md new file mode 100644 index 00000000..433dd886 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/README.md @@ -0,0 +1,228 @@ +[![Build Status](https://secure.travis-ci.org/christkv/mongodb-core.png)](http://travis-ci.org/christkv/mongodb-core) +[![Coverage Status](https://coveralls.io/repos/github/christkv/mongodb-core/badge.svg?branch=1.3)](https://coveralls.io/github/christkv/mongodb-core?branch=1.3) + +# Description + +The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. + +## MongoDB Node.JS Core Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/christkv/mongodb-core | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) <http://christiankvalheim.com> + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login <https://jira.mongodb.org>. +- Navigate to the NODE project <https://jira.mongodb.org/browse/NODE>. +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +# QuickStart + +The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. + +## Create the package.json file + +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Create a **package.json** using your favorite text editor and fill it in. + +```json +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb-core": "~1.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +## Connecting to MongoDB + +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + test.done(); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + + // Execute the ismaster command + _server.command('system.$cmd', {ismaster: true}, function(err, result) { + + // Perform a document insert + _server.insert('myproject.inserts1', [{a:1}, {a:2}], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(2, results.result.n); + + // Perform a document update + _server.update('myproject.inserts1', [{ + q: {a: 1}, u: {'$set': {b:1}} + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Remove a document + _server.remove('myproject.inserts1', [{ + q: {a: 1}, limit: 1 + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Get a document + var cursor = _server.cursor('integration_tests.inserts_example4', { + find: 'integration_tests.example4' + , query: {a:1} + }); + + // Get the first document + cursor.next(function(err, doc) { + assert.equal(null, err); + assert.equal(2, doc.a); + + // Execute the ismaster command + _server.command("system.$cmd" + , {ismaster: true}, function(err, result) { + assert.equal(null, err) + _server.destroy(); + }); + }); + }); + }); + + test.done(); + }); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. + +* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. +* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. +* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. +* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. +* `command`, Executes a command against MongoDB and returns the result. +* `auth`, Authenticates the current topology using a supported authentication scheme. + +The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. + +## Next steps + +The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/TESTING.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/TESTING.md new file mode 100644 index 00000000..fe03ea0f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/TESTING.md @@ -0,0 +1,18 @@ +Testing setup +============= + +Single Server +------------- +mongod --dbpath=./db + +Replicaset +---------- +mongo --nodb +var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) +x.startSet(); +var config = x.getReplSetConfig() +x.initiate(config); + +Mongos +------ +var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true});
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/THIRD-PARTY-NOTICES b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/THIRD-PARTY-NOTICES new file mode 100644 index 00000000..c13e5d9a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/THIRD-PARTY-NOTICES @@ -0,0 +1,41 @@ +Mongodb-core uses third-party libraries or other resources that may +be distributed under licenses different than the Mongodb-core software. + +In the event that we accidentally failed to list a required notice, +please bring it to our attention through any of the ways detailed here: + + mongodb-dev@googlegroups.com + +The attached notices are provided for information only. + +For any licenses that require disclosure of source, sources are available at +https://github.com/mongodb/node-mongodb-native. + +1) License Notice for nan.h +--------------------------- + +The MIT License (MIT) +===================== + +Copyright (c) 2016 NAN contributors +----------------------------------- + +NAN contributors listed at <https://github.com/nodejs/nan#contributors> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to +do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/blocking_test.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/blocking_test.js new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/blocking_test.js diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/conf.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/conf.json new file mode 100644 index 00000000..12ce4c7a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/conf.json @@ -0,0 +1,59 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/tests/functional/operation_example_tests.js", + "lib/connection/command_result.js", + "lib/topologies/mongos.js", + "lib/topologies/read_preference.js", + "lib/topologies/replset.js", + "lib/topologies/server.js", + "lib/topologies/replset_state.js", + "lib/connection/logger.js", + "lib/connection/connection.js", + "lib/cursor.js", + "lib/error.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/connect_test.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/connect_test.js new file mode 100644 index 00000000..47ee71e6 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/connect_test.js @@ -0,0 +1,72 @@ +var Server = require('./lib/topologies/server'); + +// Attempt to connect +var server = new Server({ + host: 'localhost', port: 27017, socketTimeout: 500 +}); + +// function executeCursors(_server, cb) { +// var count = 100; +// +// for(var i = 0; i < 100; i++) { +// // Execute the write +// var cursor = _server.cursor('test.test', { +// find: 'test.test' +// , query: {a:1} +// }, {readPreference: new ReadPreference('secondary')}); +// +// // Get the first document +// cursor.next(function(err, doc) { +// count = count - 1; +// if(err) console.dir(err) +// if(count == 0) return cb(); +// }); +// } +// } + +server.on('connect', function(_server) { + // console.log("===== connect") + setInterval(function() { + _server.insert('test.test', [{a:1}], function(err, r) { + console.log("insert") + }); + }, 1000) + // console.log("---------------------------------- 0") + // // Attempt authentication + // _server.auth('scram-sha-1', 'admin', 'root', 'root', function(err, r) { + // console.log("---------------------------------- 1") + // // console.dir(err) + // // console.dir(r) + // + // _server.insert('test.test', [{a:1}], function(err, r) { + // console.log("---------------------------------- 2") + // console.dir(err) + // if(r)console.dir(r.result) + // var name = null; + // + // _server.on('joined', function(_t, _server) { + // if(name == _server.name) { + // console.log("=========== joined :: " + _t + " :: " + _server.name) + // executeCursors(_server, function() { + // }); + // } + // }) + // + // // var s = _server.s.replicaSetState.secondaries[0]; + // // s.destroy({emitClose:true}); + // executeCursors(_server, function() { + // console.log("============== 0") + // // Attempt to force a server reconnect + // var s = _server.s.replicaSetState.secondaries[0]; + // name = s.name; + // s.destroy({emitClose:true}); + // // console.log("============== 1") + // + // // _server.destroy(); + // // test.done(); + // }); + // }); + // }); +}); + +server.connect(); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/index.js new file mode 100644 index 00000000..6747a4a3 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/index.js @@ -0,0 +1,27 @@ +var BSON = require('bson'); + +try { + try { BSON = require('bson-ext'); } catch(err) { + BSON = require_optional('bson-ext'); + } +} catch(err) {} + +module.exports = { + MongoError: require('./lib/error') + , Connection: require('./lib/connection/connection') + , Server: require('./lib/topologies/server') + , ReplSet: require('./lib/topologies/replset') + , Mongos: require('./lib/topologies/mongos') + , Logger: require('./lib/connection/logger') + , Cursor: require('./lib/cursor') + , ReadPreference: require('./lib/topologies/read_preference') + , BSON: BSON + // Raw operations + , Query: require('./lib/connection/commands').Query + // Auth mechanisms + , MongoCR: require('./lib/auth/mongocr') + , X509: require('./lib/auth/x509') + , Plain: require('./lib/auth/plain') + , GSSAPI: require('./lib/auth/gssapi') + , ScramSHA1: require('./lib/auth/scram') +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js new file mode 100644 index 00000000..7fe30265 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js @@ -0,0 +1,262 @@ +"use strict"; + +var f = require('util').format + , require_optional = require('require_optional') + , Query = require('../connection/commands').Query + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require_optional('kerberos').Kerberos; + // Authentication process for Mongo + MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess; +} catch(err) { +} + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @return {GSSAPI} A cursor instance + */ +var GSSAPI = function(bson) { + this.bson = bson; + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + GSSAPIInitialize(self, db, username, password, db, gssapiServiceName, server, connection, options, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + } + + _execute(connections.shift()); + } +} + +// +// Initialize step +var GSSAPIInitialize = function(self, db, username, password, authdb, gssapiServiceName, server, connection, options, callback) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName, options); + + // Perform initialization + mongo_auth_process.init(username, password, function(err) { + if(err) return callback(err, false); + + // Perform the first step + mongo_auth_process.transition('', function(err, payload) { + if(err) return callback(err, false); + + // Call the next db step + MongoDBGSSAPIFirstStep(self, mongo_auth_process, payload, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function(self, mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { + // Build the sasl start command + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: payload + , autoAuthorize: 1 + }; + + // Write the commmand on the connection + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Execute mongodb transition + mongo_auth_process.transition(r.result.payload, function(err, payload) { + if(err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep(self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function(self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + // Write the commmand on the connection + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Call next transition for kerberos + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err, false); + + // Call the last and third step + MongoDBGSSAPIThirdStep(self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +var MongoDBGSSAPIThirdStep = function(self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build final command + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + if(err) return callback(err, false); + mongo_auth_process.transition(null, function(err) { + if(err) return callback(err, null); + callback(null, r); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +GSSAPI.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db != dbName; + }); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js new file mode 100644 index 00000000..14e3c4d0 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js @@ -0,0 +1,181 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Query = require('../connection/commands').Query + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new MongoCR authentication mechanism + * @class + * @return {MongoCR} A cursor instance + */ +var MongoCR = function(bson) { + this.bson = bson; + this.authStore = []; +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var executeMongoCR = function(connection) { + // Write the commmand on the connection + server(connection, new Query(self.bson, f("%s.$cmd", db), { + getnonce:1 + }, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + var nonce = null; + var key = null; + + // Adjust the number of connections left + // Get nonce + if(err == null) { + nonce = r.result.nonce; + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password, 'utf8'); + var hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + // Execute command + // Write the commmand on the connection + server(connection, new Query(self.bson, f("%s.$cmd", db), { + authenticate: 1, user: username, nonce: nonce, key:key + }, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + }); + } + + var _execute = function(_connection) { + process.nextTick(function() { + executeMongoCR(_connection); + }); + } + + _execute(connections.shift()); + } +} + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +MongoCR.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db != dbName; + }); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = MongoCR; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js new file mode 100644 index 00000000..e3fb1a8f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js @@ -0,0 +1,170 @@ +"use strict"; + +var BSON = require('bson'); + +var f = require('util').format + , Binary = BSON.Binary + , retrieveBSON = require('../connection/utils').retrieveBSON + , Query = require('../connection/commands').Query + , MongoError = require('../error'); + +var BSON = retrieveBSON(); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new Plain authentication mechanism + * @class + * @return {Plain} A cursor instance + */ +var Plain = function(bson) { + this.bson = bson; + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Create payload + var payload = new Binary(f("\x00%s\x00%s", username, password)); + + // Let's start the sasl process + var command = { + saslStart: 1 + , mechanism: 'PLAIN' + , payload: payload + , autoAuthorize: 1 + }; + + // Let's start the process + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + } + + _execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +Plain.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db != dbName; + }); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = Plain; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js new file mode 100644 index 00000000..cdc6ebb1 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js @@ -0,0 +1,343 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , retrieveBSON = require('../connection/utils').retrieveBSON + , Query = require('../connection/commands').Query + , MongoError = require('../error'); + +var BSON = retrieveBSON(), + Binary = BSON.Binary; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +var id = 0; + +/** + * Creates a new ScramSHA1 authentication mechanism + * @class + * @return {ScramSHA1} A cursor instance + */ +var ScramSHA1 = function(bson) { + this.bson = bson; + this.authStore = []; + this.id = id++; +} + +var parsePayload = function(payload) { + var dict = {}; + var parts = payload.split(','); + + for(var i = 0; i < parts.length; i++) { + var valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +} + +var passwordDigest = function(username, password) { + if(typeof username != 'string') throw new MongoError("username must be a string"); + if(typeof password != 'string') throw new MongoError("password must be a string"); + if(password.length == 0) throw new MongoError("password cannot be empty"); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password, 'utf8'); + return md5.digest('hex'); +} + +// XOR two buffers +var xor = function(a, b) { + if (!Buffer.isBuffer(a)) a = new Buffer(a) + if (!Buffer.isBuffer(b)) b = new Buffer(b) + var res = [] + if (a.length > b.length) { + for (var i = 0; i < b.length; i++) { + res.push(a[i] ^ b[i]) + } + } else { + for (i = 0; i < a.length; i++) { + res.push(a[i] ^ b[i]) + } + } + return new Buffer(res); +} + +// Create a final digest +var hi = function(data, salt, iterations) { + // Create digest + var digest = function(msg) { + var hmac = crypto.createHmac('sha1', data); + hmac.update(msg); + return new Buffer(hmac.digest('base64'), 'base64'); + } + + // Create variables + salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')]) + var ui = digest(salt); + var u1 = ui; + + for(var i = 0; i < iterations - 1; i++) { + u1 = digest(u1); + ui = xor(ui, u1); + } + + return ui; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // Execute MongoCR + var executeScram = function(connection) { + // Clean up the user + username = username.replace('=', "=3D").replace(',', '=2C'); + + // Create a random nonce + var nonce = crypto.randomBytes(24).toString('base64'); + // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' + var firstBare = f("n=%s,r=%s", username, nonce); + + // Build command structure + var cmd = { + saslStart: 1 + , mechanism: 'SCRAM-SHA-1' + , payload: new Binary(f("n,,%s", firstBare)) + , autoAuthorize: 1 + } + + // Handle the error + var handleError = function(err, r) { + if(err) { + numberOfValidConnections = numberOfValidConnections - 1; + errorObject = err; return false; + } else if(r.result['$err']) { + errorObject = r.result; return false; + } else if(r.result['errmsg']) { + errorObject = r.result; return false; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + return true + } + + // Finish up + var finish = function(_count, _numberOfValidConnections) { + if(_count == 0 && _numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(_count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + } + + var handleEnd = function(_err, _r) { + // Handle any error + handleError(_err, _r) + // Adjust the number of connections + count = count - 1; + // Execute the finish + finish(count, numberOfValidConnections); + } + + // Write the commmand on the connection + server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + // Do we have an error, handle it + if(handleError(err, r) == false) { + count = count - 1; + + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + + return; + } + + // Get the dictionary + var dict = parsePayload(r.result.payload.value()) + + // Unpack dictionary + var iterations = parseInt(dict.i, 10); + var salt = dict.s; + var rnonce = dict.r; + + // Set up start of proof + var withoutProof = f("c=biws,r=%s", rnonce); + var passwordDig = passwordDigest(username, password); + var saltedPassword = hi(passwordDig + , new Buffer(salt, 'base64') + , iterations); + + // Create the client key + var hmac = crypto.createHmac('sha1', saltedPassword); + hmac.update(new Buffer("Client Key")); + var clientKey = new Buffer(hmac.digest('base64'), 'base64'); + + // Create the stored key + var hash = crypto.createHash('sha1'); + hash.update(clientKey); + var storedKey = new Buffer(hash.digest('base64'), 'base64'); + + // Create the authentication message + var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); + + // Create client signature + hmac = crypto.createHmac('sha1', storedKey); + hmac.update(new Buffer(authMsg)); + var clientSig = new Buffer(hmac.digest('base64'), 'base64'); + + // Create client proof + var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); + + // Create client final + var clientFinal = [withoutProof, clientProof].join(','); + + // Generate server key + hmac = crypto.createHmac('sha1', saltedPassword); + hmac.update(new Buffer('Server Key')) + var serverKey = new Buffer(hmac.digest('base64'), 'base64'); + + // Generate server signature + hmac = crypto.createHmac('sha1', serverKey); + hmac.update(new Buffer(authMsg)) + + // + // Create continue message + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Binary(new Buffer(clientFinal)) + } + + // + // Execute sasl continue + // Write the commmand on the connection + server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + if(r && r.result.done == false) { + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Buffer(0) + } + + // Write the commmand on the connection + server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + handleEnd(err, r); + }); + } else { + handleEnd(err, r); + } + }); + }); + } + + var _execute = function(_connection) { + process.nextTick(function() { + executeScram(_connection); + }); + } + + // For each connection we need to authenticate + while(connections.length > 0) { + _execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +ScramSHA1.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db != dbName; + }); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + // No connections + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + + +module.exports = ScramSHA1; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js new file mode 100644 index 00000000..ef4874c3 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js @@ -0,0 +1,250 @@ +"use strict"; + +var f = require('util').format + , require_optional = require('require_optional') + , Query = require('../connection/commands').Query + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require_optional('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new SSPI authentication mechanism + * @class + * @return {SSPI} A cursor instance + */ +var SSPI = function(bson) { + this.bson = bson; + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + SSIPAuthenticate(self, username, password, gssapiServiceName, server, connection, options, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r && typeof r == 'object' && r.result['$err']) { + errorObject = r.result; + } else if(r && typeof r == 'object' && r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + } + + _execute(connections.shift()); + } +} + +var SSIPAuthenticate = function(self, username, password, gssapiServiceName, server, connection, options, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: '' + , autoAuthorize: 1 + }; + + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName, options); + + // Execute first sasl step + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.init(username, password, function(err) { + if(err) return callback(err); + + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err); + + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err); + + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.transition(doc.payload, function(err, payload) { + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + if(doc.done) return callback(null, true); + callback(new Error("Authentication failed"), false); + }); + }); + }); + }); + }); + }); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +SSPI.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db != dbName; + }); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = SSPI; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js new file mode 100644 index 00000000..0b75d797 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js @@ -0,0 +1,164 @@ +"use strict"; + +var f = require('util').format + , Query = require('../connection/commands').Query + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new X509 authentication mechanism + * @class + * @return {X509} A cursor instance + */ +var X509 = function(bson) { + this.bson = bson; + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Let's start the sasl process + var command = { + authenticate: 1 + , mechanism: 'MONGODB-X509' + }; + + // Add username if specified + if(username) { + command.user = username; + } + + // Let's start the process + server(connection, new Query(self.bson, "$external.$cmd", command, { + numberToSkip: 0, numberToReturn: 1 + }), function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + } + + _execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +X509.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db != dbName; + }); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = X509; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/command_result.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/command_result.js new file mode 100644 index 00000000..2b15dd76 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/command_result.js @@ -0,0 +1,34 @@ +"use strict"; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection, message) { + this.result = result; + this.connection = connection; + this.message = message; +} + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + return this.result; +} + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +} + +module.exports = CommandResult; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js new file mode 100644 index 00000000..85fc193f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js @@ -0,0 +1,546 @@ +"use strict"; + +var retrieveBSON = require('../connection/utils').retrieveBSON; +var BSON = retrieveBSON(); +var Long = BSON.Long; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var OP_QUERY = 2004; +var OP_GETMORE = 2005; +var OP_KILL_CURSORS = 2007; + +// Query flags +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 0; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if(ns == null) throw new Error("ns must be specified for query"); + if(query == null) throw new Error("query must be specified for query"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new Error("namespace cannot contain a null character"); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = Query.getRequestId(); + + // Serialization option + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = typeof options.slaveOk == 'boolean'? options.slaveOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +} + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +} + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if(this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if(this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if(this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if(this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if(this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if(this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if(this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to self.numberToReturn + if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(self.ns) + 1 // namespace + + 4 // numberToSkip + + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined, + }); + + // Add query document + buffers.push(query); + + if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined, + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = (totalLength) & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (OP_QUERY >> 24) & 0xff; + header[index + 2] = (OP_QUERY >> 16) & 0xff; + header[index + 1] = (OP_QUERY >> 8) & 0xff; + header[index] = (OP_QUERY) & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = (flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = (this.numberToSkip) & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +Query.getRequestId = function() { + return ++_requestId; +} + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; + _buffer[index] = (OP_GETMORE) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getHighBits()) & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +} + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, cursorIds) { + this.requestId = _requestId++; + this.cursorIds = cursorIds; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); + + // Create command buffer + var index = 0; + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = (OP_KILL_CURSORS) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = (this.cursorIds.length) & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for(var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +} + +var Response = function(bson, data, opts) { + opts = opts || {promoteLongs: true, promoteValues: true, promoteBuffers: false}; + this.parsed = false; + + // + // Parse Header + // + this.index = 0; + this.raw = data; + this.data = data; + this.bson = bson; + this.opts = opts; + + // Read the message length + this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the request id for this reply + this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the id of the request that triggered the response + this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Skip op-code field + this.index = this.index + 4; + + // Unpack flags + this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the cursor + var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + // Create long object + this.cursorId = new Long(lowBits, highBits); + + // Unpack the starting from + this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the number of objects returned + this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; + this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues == 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers == 'boolean' ? opts.promoteBuffers : false; +} + +Response.prototype.isParsed = function() { + return this.parsed; +} + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if(this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + var promoteLongs = typeof options.promoteLongs == 'boolean' + ? options.promoteLongs + : this.opts.promoteLongs; + var promoteValues = typeof options.promoteValues == 'boolean' + ? options.promoteValues + : this.opts.promoteValues; + var promoteBuffers = typeof options.promoteBuffers == 'boolean' + ? options.promoteBuffers + : this.opts.promoteBuffers + var bsonSize, _options; + + // Set up the options + _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + // + // Single document and documentsReturnedIn set + // + if(this.numberReturned == 1 && documentsReturnedIn != null && raw) { + // Calculate the bson size + bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Slice out the buffer containing the command result document + var document = this.data.slice(this.index, this.index + bsonSize); + // Set up field we wish to keep as raw + var fieldsAsRaw = {} + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + // Deserialize but keep the array of documents in non-parsed form + var doc = this.bson.deserialize(document, _options); + + // Get the documents + this.documents = doc.cursor[documentsReturnedIn]; + this.numberReturned = this.documents.length; + // Ensure we have a Long valie cursor id + this.cursorId = typeof doc.cursor.id == 'number' + ? Long.fromNumber(doc.cursor.id) + : doc.cursor.id; + + // Adjust the index + this.index = this.index + bsonSize; + + // Set as parsed + this.parsed = true + return; + } + + // + // Parse Body + // + for(var i = 0; i < this.numberReturned; i++) { + bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + + // If we have raw results specified slice the return document + if(raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + // Set parsed + this.parsed = true; +} + +module.exports = { + Query: Query + , GetMore: GetMore + , Response: Response + , KillCursor: KillCursor +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js new file mode 100644 index 00000000..ab425522 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js @@ -0,0 +1,582 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , net = require('net') + , tls = require('tls') + , crypto = require('crypto') + , f = require('util').format + , debugOptions = require('./utils').debugOptions + , Response = require('./commands').Response + , MongoError = require('../error') + , Logger = require('./logger'); + +var _id = 0; +var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' + , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert' + , 'rejectUnauthorized', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'checkServerIdentity']; +var connectionAccounting = false; +var connections = {}; + +/** + * Creates a new Connection instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @return {Connection} A cursor instance + */ +var Connection = function(messageHandler, options) { + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + // Identification information + this.id = _id++; + // Logger instance + this.logger = Logger('Connection', options); + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Get bson parser + this.bson = options.bson; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Message handler + this.messageHandler = messageHandler; + + // Max BSON message size + this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); + // Debug information + if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); + + // Default options + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; + this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; + this.connectionTimeout = options.connectionTimeout || 0; + this.socketTimeout = options.socketTimeout || 0; + + // If connection was destroyed + this.destroyed = false; + + // Check if we have a domain socket + this.domainSocket = this.host.indexOf('\/') != -1; + + // Serialize commands using function + this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; + this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; + + // SSL options + this.ca = options.ca || null; + this.cert = options.cert || null; + this.key = options.key || null; + this.passphrase = options.passphrase || null; + this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; + this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true; + this.checkServerIdentity = typeof options.checkServerIdentity == 'boolean' + || typeof options.checkServerIdentity == 'function' ? options.checkServerIdentity : true; + + // If ssl not enabled + if(!this.ssl) this.rejectUnauthorized = false; + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues == 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers == 'boolean' ? options.promoteBuffers: false + } + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.connection = null; + this.writeStream = null; + + // Create hash method + var hash = crypto.createHash('sha1'); + hash.update(f('%s:%s', this.host, this.port)); + + // Create a hash name + this.hashedName = hash.digest('hex'); + + // All operations in flight on the connection + this.workItems = []; +} + +inherits(Connection, EventEmitter); + +Connection.prototype.setSocketTimeout = function(value) { + if(this.connection) { + this.connection.setTimeout(value); + } +} + +Connection.prototype.resetSocketTimeout = function() { + if(this.connection) { + this.connection.setTimeout(this.socketTimeout); + } +} + +Connection.enableConnectionAccounting = function() { + connectionAccounting = true; + connections = {}; +} + +Connection.disableConnectionAccounting = function() { + connectionAccounting = false; +} + +Connection.connections = function() { + return connections; +} + +function deleteConnection(id) { + delete connections[id]; +} + +function addConnection(id, connection) { + connections[id] = connection; +} + +// +// Connection handlers +var errorHandler = function(self) { + return function(err) { + if(connectionAccounting) deleteConnection(self.id); + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); + // Emit the error + if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); + } +} + +var timeoutHandler = function(self) { + return function() { + if(connectionAccounting) deleteConnection(self.id); + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); + // Emit timeout error + self.emit("timeout" + , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) + , self); + } +} + +var closeHandler = function(self) { + return function(hadError) { + if(connectionAccounting) deleteConnection(self.id); + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); + + // Emit close event + if(!hadError) { + self.emit("close" + , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) + , self); + } + } +} + +var dataHandler = function(self) { + return function(data) { + // Parse until we are done with the data + while(data.length > 0) { + // If we still have bytes to read on the current message + if(self.bytesRead > 0 && self.sizeOfMessage > 0) { + // Calculate the amount of remaining bytes + var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; + // Check if the current chunk contains the rest of the message + if(remainingBytesToRead > data.length) { + // Copy the new data into the exiting buffer (should have been allocated when we know the message size) + data.copy(self.buffer, self.bytesRead); + // Adjust the number of bytes read so it point to the correct index in the buffer + self.bytesRead = self.bytesRead + data.length; + + // Reset state of buffer + data = new Buffer(0); + } else { + // Copy the missing part of the data into our current buffer + data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); + // Slice the overflow into a new buffer that we will then re-parse + data = data.slice(remainingBytesToRead); + + // Emit current complete message + try { + var emitBuffer = self.buffer; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Emit the buffer + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } catch(err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } + } else { + // Stub buffer is kept in case we don't get enough bytes to determine the + // size of the message (< 4 bytes) + if(self.stubBuffer != null && self.stubBuffer.length > 0) { + // If we have enough bytes to determine the message size let's do it + if(self.stubBuffer.length + data.length > 4) { + // Prepad the data + var newData = new Buffer(self.stubBuffer.length + data.length); + self.stubBuffer.copy(newData, 0); + data.copy(newData, self.stubBuffer.length); + // Reassign for parsing + data = newData; + + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + + } else { + + // Add the the bytes to the stub buffer + var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); + // Copy existing stub buffer + self.stubBuffer.copy(newStubBuffer, 0); + // Copy missing part of the data + data.copy(newStubBuffer, self.stubBuffer.length); + // Exit parsing loop + data = new Buffer(0); + } + } else { + if(data.length > 4) { + // Retrieve the message size + // var sizeOfMessage = data.readUInt32LE(0); + var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; + // If we have a negative sizeOfMessage emit error and return + if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { + errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ + sizeOfMessage: sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + return; + } + + // Ensure that the size of message is larger than 0 and less than the max allowed + if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length) { + self.buffer = new Buffer(sizeOfMessage); + // Copy all the data into the buffer + data.copy(self.buffer, 0); + // Update bytes read + self.bytesRead = data.length; + // Update sizeOfMessage + self.sizeOfMessage = sizeOfMessage; + // Ensure stub buffer is null + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + + } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage == data.length) { + try { + emitBuffer = data; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + // Emit the message + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } catch (err) { + self.emit("parseError", err, self); + } + } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { + errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ + sizeOfMessage:sizeOfMessage, + bytesRead:0, + buffer:null, + stubBuffer:null}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + + // Clear out the state of the parser + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + } else { + emitBuffer = data.slice(0, sizeOfMessage); + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Copy rest of message + data = data.slice(sizeOfMessage); + // Emit the message + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } + } else { + // Create a buffer that contains the space for the non-complete message + self.stubBuffer = new Buffer(data.length) + // Copy the data to the stub buffer + data.copy(self.stubBuffer, 0); + // Exit parsing loop + data = new Buffer(0); + } + } + } + } + } +} + +// List of socket level valid ssl options +var legalSslSocketOptions = ['pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers' + , 'NPNProtocols', 'ALPNProtocols', 'servername' + , 'secureProtocol', 'secureContext', 'session' + , 'minDHSize']; + +function merge(options1, options2) { + // Merge in any allowed ssl options + for(var name in options2) { + if(options2[name] != null && legalSslSocketOptions.indexOf(name) != -1) { + options1[name] = options2[name]; + } + } +} + +/** + * Connect + * @method + */ +Connection.prototype.connect = function(_options) { + var self = this; + _options = _options || {}; + // Set the connections + if(connectionAccounting) addConnection(this.id, this); + // Check if we are overriding the promoteLongs + if(typeof _options.promoteLongs == 'boolean') { + self.responseOptions.promoteLongs = _options.promoteLongs; + self.responseOptions.promoteValues = _options.promoteValues; + self.responseOptions.promoteBuffers = _options.promoteBuffers; + } + + // Create new connection instance + self.connection = self.domainSocket + ? net.createConnection(self.host) + : net.createConnection(self.port, self.host); + + // Set the options for the connection + self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + self.connection.setTimeout(self.connectionTimeout); + self.connection.setNoDelay(self.noDelay); + + // If we have ssl enabled + if(self.ssl) { + var sslOptions = { + socket: self.connection + , rejectUnauthorized: self.rejectUnauthorized + } + + // Merge in options + merge(sslOptions, this.options); + merge(sslOptions, _options); + + // Set options for ssl + if(self.ca) sslOptions.ca = self.ca; + if(self.cert) sslOptions.cert = self.cert; + if(self.key) sslOptions.key = self.key; + if(self.passphrase) sslOptions.passphrase = self.passphrase; + + // Override checkServerIdentity behavior + if(self.checkServerIdentity == false) { + // Skip the identiy check by retuning undefined as per node documents + // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback + sslOptions.checkServerIdentity = function() { + return undefined; + } + } else if(typeof self.checkServerIdentity == 'function') { + sslOptions.checkServerIdentity = self.checkServerIdentity; + } + + // Set default sni servername to be the same as host + if(sslOptions.servername == null) { + sslOptions.servername = self.host; + } + + // Attempt SSL connection + self.connection = tls.connect(self.port, self.host, sslOptions, function() { + // Error on auth or skip + if(self.connection.authorizationError && self.rejectUnauthorized) { + return self.emit("error", self.connection.authorizationError, self, {ssl:true}); + } + + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // We are done emit connect + self.emit('connect', self); + }); + self.connection.setTimeout(self.connectionTimeout); + } else { + self.connection.on('connect', function() { + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // Emit connect event + self.emit('connect', self); + }); + } + + // Add handlers for events + self.connection.once('error', errorHandler(self)); + self.connection.once('timeout', timeoutHandler(self)); + self.connection.once('close', closeHandler(self)); + self.connection.on('data', dataHandler(self)); +} + +/** + * Unref this connection + * @method + * @return {boolean} + */ +Connection.prototype.unref = function() { + if (this.connection) this.connection.unref(); + else { + var self = this; + this.once('connect', function() { + self.connection.unref(); + }); + } +} + +/** + * Destroy connection + * @method + */ +Connection.prototype.destroy = function() { + // Set the connections + if(connectionAccounting) deleteConnection(this.id); + if(this.connection) { + this.connection.end(); + this.connection.destroy(); + } + + this.destroyed = true; +} + +/** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ +Connection.prototype.write = function(buffer) { + var i; + // Debug Log + if(this.logger.isDebug()) { + if(!Array.isArray(buffer)) { + this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); + } else { + for(i = 0; i < buffer.length; i++) + this.logger.debug(f('writing buffer [%s] to %s:%s', buffer[i].toString('hex'), this.host, this.port)); + } + } + + // Write out the command + if(!Array.isArray(buffer)) return this.connection.write(buffer, 'binary'); + // Iterate over all buffers and write them in order to the socket + for(i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); +} + +/** + * Return id of connection as a string + * @method + * @return {string} + */ +Connection.prototype.toString = function() { + return "" + this.id; +} + +/** + * Return json object of connection + * @method + * @return {object} + */ +Connection.prototype.toJSON = function() { + return {id: this.id, host: this.host, port: this.port}; +} + +/** + * Is the connection connected + * @method + * @return {boolean} + */ +Connection.prototype.isConnected = function() { + if(this.destroyed) return false; + return !this.connection.destroyed && this.connection.writable; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +module.exports = Connection; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js new file mode 100644 index 00000000..b8b18187 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js @@ -0,0 +1,228 @@ +"use strict"; + +var f = require('util').format + , MongoError = require('../error'); + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if(!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + this.className = className; + + // Current logger + if(options.logger) { + currentLogger = options.logger; + } else if(currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if(options.loggerLevel) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if(filteredClasses[this.className] == null) classFilters[this.className] = true; +} + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if(this.isDebug() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +} + +/** + * Log a message at the warn level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.warn = function(message, object) { + if(this.isWarn() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'WARN', this.className, pid, dateTime, message); + var state = { + type: 'warn', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.info = function(message, object) { + if(this.isInfo() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.error = function(message, object) { + if(this.isError() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Is the logger set at info level + * @method + * @return {boolean} + */ +Logger.prototype.isInfo = function() { + return level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at error level + * @method + * @return {boolean} + */ +Logger.prototype.isError = function() { + return level == 'error' || level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at error level + * @method + * @return {boolean} + */ +Logger.prototype.isWarn = function() { + return level == 'error' || level == 'warn' || level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at debug level + * @method + * @return {boolean} + */ +Logger.prototype.isDebug = function() { + return level == 'debug'; +} + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +} + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +} + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if(typeof logger != 'function') throw new MongoError("current logger must be a function"); + currentLogger = logger; +} + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if(type == 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +} + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if(_level != 'info' && _level != 'error' && _level != 'debug' && _level != 'warn') { + throw new Error(f("%s is an illegal logging level", _level)); + } + + level = _level; +} + +module.exports = Logger; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js new file mode 100644 index 00000000..b3c874df --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js @@ -0,0 +1,1237 @@ +"use strict"; + +var inherits = require('util').inherits, + EventEmitter = require('events').EventEmitter, + Connection = require('./connection'), + MongoError = require('../error'), + Logger = require('./logger'), + f = require('util').format, + Query = require('./commands').Query, + CommandResult = require('./command_result'), + assign = require('../topologies/shared').assign; + +var MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram'); + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYING = 'destroying'; +var DESTROYED = 'destroyed'; + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=1] Max server connection pool size + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passPhrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(options) { + // Add event listener + EventEmitter.call(this); + // Add the options + this.options = assign({ + // Host and port settings + host: 'localhost', + port: 27017, + // Pool default max size + size: 5, + // socket settings + connectionTimeout: 30000, + socketTimeout: 30000, + keepAlive: true, + keepAliveInitialDelay: 0, + noDelay: true, + // SSL Settings + ssl: false, checkServerIdentity: true, + ca: null, cert: null, key: null, passPhrase: null, + rejectUnauthorized: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + // Reconnection options + reconnect: true, + reconnectInterval: 1000, + reconnectTries: 30, + // Enable domains + domainsEnabled: false + }, options); + + // Identification information + this.id = _id++; + // Current reconnect retries + this.retriesLeft = this.options.reconnectTries; + this.reconnectId = null; + // No bson parser passed in + if(!options.bson || (options.bson + && (typeof options.bson.serialize != 'function' + || typeof options.bson.deserialize != 'function'))) { + throw new Error("must pass in valid bson parser"); + } + + // Logger instance + this.logger = Logger('Pool', options); + // Pool state + this.state = DISCONNECTED; + // Connections + this.availableConnections = []; + this.inUseConnections = []; + this.connectingConnections = []; + // Currently executing + this.executing = false; + // Operation work queue + this.queue = []; + + // All the authProviders + this.authProviders = options.authProviders || { + 'mongocr': new MongoCR(options.bson), 'x509': new X509(options.bson) + , 'plain': new Plain(options.bson), 'gssapi': new GSSAPI(options.bson) + , 'sspi': new SSPI(options.bson), 'scram-sha-1': new ScramSHA1(options.bson) + } + + // Are we currently authenticating + this.authenticating = false; + this.loggingout = false; + this.nonAuthenticatedConnections = []; + this.authenticatingTimestamp = null; + // Number of consecutive timeouts caught + this.numberOfConsecutiveTimeouts = 0; + // Current pool Index + this.connectionIndex = 0; +} + +inherits(Pool, EventEmitter); + +Object.defineProperty(Pool.prototype, 'size', { + enumerable:true, + get: function() { return this.options.size; } +}); + +Object.defineProperty(Pool.prototype, 'connectionTimeout', { + enumerable:true, + get: function() { return this.options.connectionTimeout; } +}); + +Object.defineProperty(Pool.prototype, 'socketTimeout', { + enumerable:true, + get: function() { return this.options.socketTimeout; } +}); + +function stateTransition(self, newState) { + var legalTransitions = { + 'disconnected': [CONNECTING, DESTROYING, DISCONNECTED], + 'connecting': [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], + 'connected': [CONNECTED, DISCONNECTED, DESTROYING], + 'destroying': [DESTROYING, DESTROYED], + 'destroyed': [DESTROYED] + } + + // Get current state + var legalStates = legalTransitions[self.state]; + if(legalStates && legalStates.indexOf(newState) != -1) { + self.state = newState; + } else { + self.logger.error(f('Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]' + , self.id, self.state, newState, legalStates)); + } +} + +function authenticate(pool, auth, connection, cb) { + if(auth[0] === undefined) return cb(null); + // We need to authenticate the server + var mechanism = auth[0]; + var db = auth[1]; + // Validate if the mechanism exists + if(!pool.authProviders[mechanism]) { + throw new MongoError(f('authMechanism %s not supported', mechanism)); + } + + // Get the provider + var provider = pool.authProviders[mechanism]; + + // Authenticate using the provided mechanism + provider.auth.apply(provider, [write(pool), [connection], db].concat(auth.slice(2)).concat([cb])); +} + +// The write function used by the authentication mechanism (bypasses external) +function write(self) { + return function(connection, command, callback) { + // Get the raw buffer + // Ensure we stop auth if pool was destroyed + if(self.state == DESTROYED || self.state == DESTROYING) { + return callback(new MongoError('pool destroyed')); + } + + // Set the connection workItem callback + connection.workItems.push({ + cb: callback, command: true, requestId: command.requestId + }); + + // Write the buffer out to the connection + connection.write(command.toBin()); + }; +} + + +function reauthenticate(pool, connection, cb) { + // Authenticate + function authenticateAgainstProvider(pool, connection, providers, cb) { + // Finished re-authenticating against providers + if(providers.length == 0) return cb(); + // Get the provider name + var provider = pool.authProviders[providers.pop()]; + + // Auth provider + provider.reauthenticate(write(pool), [connection], function(err) { + // We got an error return immediately + if(err) return cb(err); + // Continue authenticating the connection + authenticateAgainstProvider(pool, connection, providers, cb); + }); + } + + // Start re-authenticating process + authenticateAgainstProvider(pool, connection, Object.keys(pool.authProviders), cb); +} + +function connectionFailureHandler(self, event) { + return function(err) { + if (this._connectionFailHandled) return; + this._connectionFailHandled = true; + // Destroy the connection + this.destroy(); + + // Remove the connection + removeConnection(self, this); + + // Flush all work Items on this connection + while(this.workItems.length > 0) { + var workItem = this.workItems.shift(); + // if(workItem.cb) workItem.cb(err); + if(workItem.cb) workItem.cb(err); + } + + // Did we catch a timeout, increment the numberOfConsecutiveTimeouts + if(event == 'timeout') { + self.numberOfConsecutiveTimeouts = self.numberOfConsecutiveTimeouts + 1; + + // Have we timed out more than reconnectTries in a row ? + // Force close the pool as we are trying to connect to tcp sink hole + if(self.numberOfConsecutiveTimeouts > self.options.reconnectTries) { + self.numberOfConsecutiveTimeouts = 0; + // Destroy all connections and pool + self.destroy(true); + // Emit close event + return self.emit('close', self); + } + } + + // No more socket available propegate the event + if(self.socketCount() == 0) { + if(self.state != DESTROYED && self.state != DESTROYING) { + stateTransition(self, DISCONNECTED); + } + + // Do not emit error events, they are always close events + // do not trigger the low level error handler in node + event = event == 'error' ? 'close' : event; + self.emit(event, err); + } + + // Start reconnection attempts + if(!self.reconnectId && self.options.reconnect) { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + }; +} + +function attemptReconnect(self) { + return function() { + self.emit('attemptReconnect', self); + if(self.state == DESTROYED || self.state == DESTROYING) return; + + // We are connected do not try again + if(self.isConnected()) { + self.reconnectId = null; + return; + } + + // If we have failure schedule a retry + function _connectionFailureHandler(self) { + return function() { + if (this._connectionFailHandled) return; + this._connectionFailHandled = true; + // Destroy the connection + this.destroy(); + // Count down the number of reconnects + self.retriesLeft = self.retriesLeft - 1; + // How many retries are left + if(self.retriesLeft == 0) { + // Destroy the instance + self.destroy(); + // Emit close event + self.emit('reconnectFailed' + , new MongoError(f('failed to reconnect after %s attempts with interval %s ms', self.options.reconnectTries, self.options.reconnectInterval))); + } else { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + } + } + + // Got a connect handler + function _connectHandler(self) { + return function() { + // Assign + var connection = this; + + // Pool destroyed stop the connection + if(self.state == DESTROYED || self.state == DESTROYING) { + return connection.destroy(); + } + + // Clear out all handlers + handlers.forEach(function(event) { + connection.removeAllListeners(event); + }); + + // Reset reconnect id + self.reconnectId = null; + + // Apply pool connection handlers + connection.on('error', connectionFailureHandler(self, 'error')); + connection.on('close', connectionFailureHandler(self, 'close')); + connection.on('timeout', connectionFailureHandler(self, 'timeout')); + connection.on('parseError', connectionFailureHandler(self, 'parseError')); + + // Apply any auth to the connection + reauthenticate(self, this, function() { + // Reset retries + self.retriesLeft = self.options.reconnectTries; + // Push to available connections + self.availableConnections.push(connection); + // Emit reconnect event + self.emit('reconnect', self); + // Trigger execute to start everything up again + _execute(self)(); + }); + } + } + + // Create a connection + var connection = new Connection(messageHandler(self), self.options); + // Add handlers + connection.on('close', _connectionFailureHandler(self, 'close')); + connection.on('error', _connectionFailureHandler(self, 'error')); + connection.on('timeout', _connectionFailureHandler(self, 'timeout')); + connection.on('parseError', _connectionFailureHandler(self, 'parseError')); + // On connection + connection.on('connect', _connectHandler(self)); + // Attempt connection + connection.connect(); + } +} + +function moveConnectionBetween(connection, from, to) { + var index = from.indexOf(connection); + // Move the connection from connecting to available + if(index != -1) { + from.splice(index, 1); + to.push(connection); + } +} + +function messageHandler(self) { + return function(message, connection) { + // workItem to execute + var workItem = null; + + // Locate the workItem + for(var i = 0; i < connection.workItems.length; i++) { + if(connection.workItems[i].requestId == message.responseTo) { + // Get the callback + workItem = connection.workItems[i]; + // Remove from list of workItems + connection.workItems.splice(i, 1); + } + } + + + // Reset timeout counter + self.numberOfConsecutiveTimeouts = 0; + + // Reset the connection timeout if we modified it for + // this operation + if(workItem.socketTimeout) { + connection.resetSocketTimeout(); + } + + // Log if debug enabled + if(self.logger.isDebug()) { + self.logger.debug(f('message [%s] received from %s:%s' + , message.raw.toString('hex'), self.options.host, self.options.port)); + } + + // Authenticate any straggler connections + function authenticateStragglers(self, connection, callback) { + // Get any non authenticated connections + var connections = self.nonAuthenticatedConnections.slice(0); + var nonAuthenticatedConnections = self.nonAuthenticatedConnections; + self.nonAuthenticatedConnections = []; + + // Establish if the connection need to be authenticated + // Add to authentication list if + // 1. we were in an authentication process when the operation was executed + // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened + if(connection.workItems.length == 1 && (connection.workItems[0].authenticating == true + || (typeof connection.workItems[0].authenticatingTimestamp == 'number' + && connection.workItems[0].authenticatingTimestamp != self.authenticatingTimestamp))) { + // Add connection to the list + connections.push(connection); + } + + // No connections need to be re-authenticated + if(connections.length == 0) { + // Release the connection back to the pool + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + // Finish + return callback(); + } + + // Apply re-authentication to all connections before releasing back to pool + var connectionCount = connections.length; + // Authenticate all connections + for(var i = 0; i < connectionCount; i++) { + reauthenticate(self, connections[i], function() { + connectionCount = connectionCount - 1; + + if(connectionCount == 0) { + // Put non authenticated connections in available connections + self.availableConnections = self.availableConnections.concat(nonAuthenticatedConnections); + // Release the connection back to the pool + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + // Return + callback(); + } + }); + } + } + + function handleOperationCallback(self, cb, err, result) { + // No domain enabled + if(!self.options.domainsEnabled) { + return process.nextTick(function() { + return cb(err, result); + }); + } + + // Domain enabled just call the callback + cb(err, result); + } + + authenticateStragglers(self, connection, function() { + // Keep executing, ensure current message handler does not stop execution + if(!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + + // Time to dispatch the message if we have a callback + if(!workItem.immediateRelease) { + try { + // Parse the message according to the provided options + message.parse(workItem); + } catch(err) { + return handleOperationCallback(self, workItem.cb, MongoError.create(err)); + } + + // Establish if we have an error + if(workItem.command && message.documents[0] && (message.documents[0].ok == 0 || message.documents[0]['$err'] + || message.documents[0]['errmsg'] || message.documents[0]['code'])) { + return handleOperationCallback(self, workItem.cb, MongoError.create(message.documents[0])); + } + + // Add the connection details + message.hashedName = connection.hashedName; + + // Return the documents + handleOperationCallback(self, workItem.cb, null, new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message)); + } + }); + } +} + +/** + * Return the total socket count in the pool. + * @method + * @return {Number} The number of socket available. + */ +Pool.prototype.socketCount = function() { + return this.availableConnections.length + + this.inUseConnections.length; + // + this.connectingConnections.length; +} + +/** + * Return all pool connections + * @method + * @return {Connectio[]} The pool connections + */ +Pool.prototype.allConnections = function() { + return this.availableConnections + .concat(this.inUseConnections) + .concat(this.connectingConnections); +} + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + return this.allConnections()[0]; +} + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + // We are in a destroyed state + if(this.state == DESTROYED || this.state == DESTROYING) { + return false; + } + + // Get connections + var connections = this.availableConnections + .concat(this.inUseConnections); + + // Check if we have any connected connections + for(var i = 0; i < connections.length; i++) { + if(connections[i].isConnected()) return true; + } + + // Might be authenticating, but we are still connected + if(connections.length == 0 && this.authenticating) { + return true + } + + // Not connected + return false; +} + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state == DESTROYED || this.state == DESTROYING; +} + +/** + * Is the pool in a disconnected state + * @method + * @return {boolean} + */ +Pool.prototype.isDisconnected = function() { + return this.state == DISCONNECTED; +} + +/** + * Connect pool + * @method + */ +Pool.prototype.connect = function() { + if(this.state != DISCONNECTED) { + throw new MongoError('connection in unlawful state ' + this.state); + } + + var self = this; + // Transition to connecting state + stateTransition(this, CONNECTING); + // Create an array of the arguments + var args = Array.prototype.slice.call(arguments, 0); + // Create a connection + var connection = new Connection(messageHandler(self), this.options); + // Add to list of connections + this.connectingConnections.push(connection); + // Add listeners to the connection + connection.once('connect', function(connection) { + if(self.state == DESTROYED || self.state == DESTROYING) return self.destroy(); + + // Apply any store credentials + reauthenticate(self, connection, function(err) { + if(self.state == DESTROYED || self.state == DESTROYING) return self.destroy(); + + // We have an error emit it + if(err) { + // Destroy the pool + self.destroy(); + // Emit the error + return self.emit('error', err); + } + + // Authenticate + authenticate(self, args, connection, function(err) { + if(self.state == DESTROYED || self.state == DESTROYING) return self.destroy(); + + // We have an error emit it + if(err) { + // Destroy the pool + self.destroy(); + // Emit the error + return self.emit('error', err); + } + // Set connected mode + stateTransition(self, CONNECTED); + + // Move the active connection + moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); + + // Emit the connect event + self.emit('connect', self); + }); + }); + }); + + // Add error handlers + connection.once('error', connectionFailureHandler(this, 'error')); + connection.once('close', connectionFailureHandler(this, 'close')); + connection.once('timeout', connectionFailureHandler(this, 'timeout')); + connection.once('parseError', connectionFailureHandler(this, 'parseError')); + + try { + connection.connect(); + } catch(err) { + // SSL or something threw on connect + self.emit('error', err); + } +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.auth = function(mechanism) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(self.authProviders[mechanism] == null && mechanism != 'default') { + throw new MongoError(f("auth provider %s does not exist", mechanism)); + } + + // Signal that we are authenticating a new set of credentials + this.authenticating = true; + this.authenticatingTimestamp = new Date().getTime(); + + // Authenticate all live connections + function authenticateLiveConnections(self, args, cb) { + // Get the current viable connections + var connections = self.availableConnections; + // Allow nothing else to use the connections while we authenticate them + self.availableConnections = []; + + var connectionsCount = connections.length; + var error = null; + // No connections available, return + if(connectionsCount == 0) return callback(null); + // Authenticate the connections + for(var i = 0; i < connections.length; i++) { + authenticate(self, args, connections[i], function(err) { + connectionsCount = connectionsCount - 1; + + // Store the error + if(err) error = err; + + // Processed all connections + if(connectionsCount == 0) { + // Auth finished + self.authenticating = false; + // Add the connections back to available connections + self.availableConnections = self.availableConnections.concat(connections); + // We had an error, return it + if(error) { + // Log the error + if(self.logger.isError()) { + self.logger.error(f('[%s] failed to authenticate against server %s:%s' + , self.id, self.options.host, self.options.port)); + } + + return cb(error); + } + cb(null); + } + }); + } + } + + // Wait for a logout in process to happen + function waitForLogout(self, cb) { + if(!self.loggingout) return cb(); + setTimeout(function() { + waitForLogout(self, cb); + }, 1) + } + + // Wait for loggout to finish + waitForLogout(self, function() { + // Authenticate all live connections + authenticateLiveConnections(self, args, function(err) { + // Credentials correctly stored in auth provider if successful + // Any new connections will now reauthenticate correctly + self.authenticating = false; + // Return after authentication connections + callback(err); + }); + }); +} + +/** + * Logout all users against a database + * @method + * @param {string} dbName The database name + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.logout = function(dbName, callback) { + var self = this; + if(typeof dbName != 'string') { + throw new MongoError('logout method requires a db name as first argument'); + } + + if(typeof callback != 'function') { + throw new MongoError('logout method requires a callback'); + } + + // Indicate logout in process + this.loggingout = true; + + // Get all relevant connections + var connections = self.availableConnections.concat(self.inUseConnections); + var count = connections.length; + // Store any error + var error = null; + + // Send logout command over all the connections + for(var i = 0; i < connections.length; i++) { + write(self)(connections[i], new Query(this.options.bson + , f('%s.$cmd', dbName) + , {logout:1}, {numberToSkip: 0, numberToReturn: 1}), function(err) { + count = count - 1; + if(err) error = err; + + if(count == 0) { + self.loggingout = false; + callback(error); + } + }); + } +} + +/** + * Unref the pool + * @method + */ +Pool.prototype.unref = function() { + // Get all the known connections + var connections = this.availableConnections + .concat(this.inUseConnections) + .concat(this.connectingConnections); + connections.forEach(function(c) { + c.unref(); + }); +} + +// Events +var events = ['error', 'close', 'timeout', 'parseError', 'connect']; + +// Destroy the connections +function destroy(self, connections) { + // Destroy all connections + connections.forEach(function(c) { + // Remove all listeners + for(var i = 0; i < events.length; i++) { + c.removeAllListeners(events[i]); + } + // Destroy connection + c.destroy(); + }); + + // Zero out all connections + self.inUseConnections = []; + self.availableConnections = []; + self.nonAuthenticatedConnections = []; + self.connectingConnections = []; + + // Set state to destroyed + stateTransition(self, DESTROYED); +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function(force) { + var self = this; + // Do not try again if the pool is already dead + if(this.state == DESTROYED || self.state == DESTROYING) return; + // Set state to destroyed + stateTransition(this, DESTROYING); + + // Are we force closing + if(force) { + // Get all the known connections + var connections = self.availableConnections + .concat(self.inUseConnections) + .concat(self.nonAuthenticatedConnections) + .concat(self.connectingConnections); + return destroy(self, connections); + } + + // Wait for the operations to drain before we close the pool + function checkStatus() { + if(self.queue.length == 0) { + // Get all the known connections + var connections = self.availableConnections + .concat(self.inUseConnections) + .concat(self.nonAuthenticatedConnections) + .concat(self.connectingConnections); + + // Check if we have any in flight operations + for(var i = 0; i < connections.length; i++) { + // There is an operation still in flight, reschedule a + // check waiting for it to drain + if(connections[i].workItems.length > 0) { + return setTimeout(checkStatus, 1); + } + } + + destroy(self, connections); + } else { + setTimeout(checkStatus, 1); + } + } + + // Initiate drain of operations + checkStatus(); +} + +/** + * Write a message to MongoDB + * @method + * @return {Connection} + */ +Pool.prototype.write = function(commands, options, cb) { + var self = this; + // Ensure we have a callback + if(typeof options == 'function') { + cb = options; + } + + // Always have options + options = options || {}; + + // Pool was destroyed error out + if(this.state == DESTROYED || this.state == DESTROYING) { + // Callback with an error + if(cb) { + try { + cb(new MongoError('pool destroyed')); + } catch(err) { + process.nextTick(function() { + throw err; + }); + } + } + + return; + } + + if(this.options.domainsEnabled + && process.domain && typeof cb === "function") { + // if we have a domain bind to it + var oldCb = cb; + cb = process.domain.bind(function() { + // v8 - argumentsToArray one-liner + var args = new Array(arguments.length); for(var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } + // bounce off event loop so domain switch takes place + process.nextTick(function() { + oldCb.apply(null, args); + }); + }); + } + + // Do we have an operation + var operation = { + cb: cb, raw: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, fullResult: false + }; + + var buffer = null + + if(Array.isArray(commands)) { + buffer = []; + + for(var i = 0; i < commands.length; i++) { + buffer.push(commands[i].toBin()); + } + + // Get the requestId + operation.requestId = commands[commands.length - 1].requestId; + } else { + operation.requestId = commands.requestId; + buffer = commands.toBin(); + } + + // Set the buffers + operation.buffer = buffer; + + // Set the options for the parsing + operation.promoteLongs = typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true; + operation.promoteValues = typeof options.promoteValues == 'boolean' ? options.promoteValues : true; + operation.promoteBuffers = typeof options.promoteBuffers == 'boolean' ? options.promoteBuffers : false; + operation.raw = typeof options.raw == 'boolean' ? options.raw : false; + operation.immediateRelease = typeof options.immediateRelease == 'boolean' ? options.immediateRelease : false; + operation.documentsReturnedIn = options.documentsReturnedIn; + operation.command = typeof options.command == 'boolean' ? options.command : false; + operation.fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false; + operation.noResponse = typeof options.noResponse == 'boolean' ? options.noResponse : false; + // operation.requestId = options.requestId; + + // Optional per operation socketTimeout + operation.socketTimeout = options.socketTimeout; + operation.monitoring = options.monitoring; + // Custom socket Timeout + if(options.socketTimeout) { + operation.socketTimeout = options.socketTimeout; + } + + // We need to have a callback function unless the message returns no response + if(!(typeof cb == 'function') && !options.noResponse) { + throw new MongoError('write method must provide a callback'); + } + + // If we have a monitoring operation schedule as the very first operation + // Otherwise add to back of queue + if(options.monitoring) { + this.queue.unshift(operation); + } else { + this.queue.push(operation); + } + + // Attempt to execute the operation + if(!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } +} + +// Remove connection method +function remove(connection, connections) { + for(var i = 0; i < connections.length; i++) { + if(connections[i] === connection) { + connections.splice(i, 1); + return true; + } + } +} + +function removeConnection(self, connection) { + if(remove(connection, self.availableConnections)) return; + if(remove(connection, self.inUseConnections)) return; + if(remove(connection, self.connectingConnections)) return; + if(remove(connection, self.nonAuthenticatedConnections)) return; +} + +// All event handlers +var handlers = ["close", "message", "error", "timeout", "parseError", "connect"]; + +function _createConnection(self) { + var connection = new Connection(messageHandler(self), self.options); + + // Push the connection + self.connectingConnections.push(connection); + + // Handle any errors + var tempErrorHandler = function(_connection) { + return function() { + // Destroy the connection + _connection.destroy(); + // Remove the connection from the connectingConnections list + removeConnection(self, _connection); + // Start reconnection attempts + if(!self.reconnectId && self.options.reconnect) { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + } + } + + // Handle successful connection + var tempConnectHandler = function(_connection) { + return function() { + // Destroyed state return + if(self.state == DESTROYED || self.state == DESTROYING) { + // Remove the connection from the list + removeConnection(self, _connection); + return _connection.destroy(); + } + + // Destroy all event emitters + handlers.forEach(function(e) { + _connection.removeAllListeners(e); + }); + + // Add the final handlers + _connection.once('close', connectionFailureHandler(self, 'close')); + _connection.once('error', connectionFailureHandler(self, 'error')); + _connection.once('timeout', connectionFailureHandler(self, 'timeout')); + _connection.once('parseError', connectionFailureHandler(self, 'parseError')); + + // Signal + reauthenticate(self, _connection, function(err) { + if(self.state == DESTROYED || self.state == DESTROYING) { + return _connection.destroy(); + } + // Remove the connection from the connectingConnections list + removeConnection(self, _connection); + + // Handle error + if(err) { + return _connection.destroy(); + } + + // If we are authenticating at the moment + // Do not automatially put in available connections + // As we need to apply the credentials first + if(self.authenticating) { + self.nonAuthenticatedConnections.push(_connection); + } else { + // Push to available + self.availableConnections.push(_connection); + // Execute any work waiting + _execute(self)(); + } + }); + } + } + + // Add all handlers + connection.once('close', tempErrorHandler(connection)); + connection.once('error', tempErrorHandler(connection)); + connection.once('timeout', tempErrorHandler(connection)); + connection.once('parseError', tempErrorHandler(connection)); + connection.once('connect', tempConnectHandler(connection)); + + // Start connection + connection.connect(); +} + +function flushMonitoringOperations(queue) { + for(var i = 0; i < queue.length; i++) { + if(queue[i].monitoring) { + var workItem = queue[i]; + queue.splice(i, 1); + workItem.cb(new MongoError({ message: 'no connection available for monitoring', driver:true })); + } + } +} + +function _execute(self) { + return function() { + if(self.state == DESTROYED) return; + // Already executing, skip + if(self.executing) return; + // Set pool as executing + self.executing = true; + + // Wait for auth to clear before continuing + function waitForAuth(cb) { + if(!self.authenticating) return cb(); + // Wait for a milisecond and try again + setTimeout(function() { + waitForAuth(cb); + }, 1); + } + + // Block on any auth in process + waitForAuth(function() { + // As long as we have available connections + while(true) { + // Total availble connections + var totalConnections = self.availableConnections.length + + self.connectingConnections.length + + self.inUseConnections.length; + + // No available connections available, flush any monitoring ops + if(self.availableConnections.length == 0) { + // Flush any monitoring operations + flushMonitoringOperations(self.queue); + break; + } + + // No queue break + if(self.queue.length == 0) { + break; + } + + // Get a connection + var connection = self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; + // Is the connection connected + if(connection.isConnected()) { + // Get the next work item + var workItem = self.queue.shift(); + + // Get actual binary commands + var buffer = workItem.buffer; + + // Set current status of authentication process + workItem.authenticating = self.authenticating; + workItem.authenticatingTimestamp = self.authenticatingTimestamp; + + // If we are monitoring take the connection of the availableConnections + if (workItem.monitoring) { + moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); + } + + // Track the executing commands on the mongo server + // as long as there is an expected response + if (! workItem.noResponse) { + connection.workItems.push(workItem); + } + + // We have a custom socketTimeout + if(!workItem.immediateRelease && typeof workItem.socketTimeout == 'number') { + connection.setSocketTimeout(workItem.socketTimeout); + } + + // Put operation on the wire + if(Array.isArray(buffer)) { + for(var i = 0; i < buffer.length; i++) { + connection.write(buffer[i]) + } + } else { + connection.write(buffer); + } + + if(workItem.immediateRelease && self.authenticating) { + self.nonAuthenticatedConnections.push(connection); + } + + // Have we not reached the max connection size yet + if(totalConnections < self.options.size + && self.queue.length > 0) { + // Create a new connection + _createConnection(self); + } + } else { + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + } + } + }); + + self.executing = false; + } +} + +// Make execution loop available for testing +Pool._execute = _execute; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * A server reconnect event, used to verify that pool reconnected. + * + * @event Pool#reconnect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +/** + * The driver attempted to reconnect + * + * @event Pool#attemptReconnect + * @type {Pool} + */ + +/** + * The driver exhausted all reconnect attempts + * + * @event Pool#reconnectFailed + * @type {Pool} + */ + +module.exports = Pool; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js new file mode 100644 index 00000000..0a827edb --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js @@ -0,0 +1,91 @@ +"use strict"; + +var f = require('util').format, + require_optional = require('require_optional'); + +// Set property function +var setProperty = function(obj, prop, flag, values) { + Object.defineProperty(obj, prop.name, { + enumerable:true, + set: function(value) { + if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); + // Flip the bit to 1 + if(value == true) values.flags |= flag; + // Flip the bit to 0 if it's set, otherwise ignore + if(value == false && (values.flags & flag) == flag) values.flags ^= flag; + prop.value = value; + } + , get: function() { return prop.value; } + }); +} + +// Set property function +var getProperty = function(obj, propName, fieldName, values, func) { + Object.defineProperty(obj, propName, { + enumerable:true, + get: function() { + // Not parsed yet, parse it + if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { + obj.parse(); + } + + // Do we have a post processing function + if(typeof func == 'function') return func(values[fieldName]); + // Return raw value + return values[fieldName]; + } + }); +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +// Shallow copy +var copy = function(fObj, tObj) { + tObj = tObj || {}; + for(var name in fObj) tObj[name] = fObj[name]; + return tObj; +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +var retrieveBSON = function() { + var BSON = require('bson'); + BSON.native = false; + + try { + try { + BSON = require('bson-ext'); + BSON.native = true; + } catch(err) { + var optionalBSON = require_optional('bson-ext'); + if(optionalBSON) { + optionalBSON.native = true; + return optionalBSON; + } + } + } catch(err) {} + + return BSON; +} + +exports.setProperty = setProperty; +exports.getProperty = getProperty; +exports.getSingleProperty = getSingleProperty; +exports.copy = copy; +exports.debugOptions = debugOptions; +exports.retrieveBSON = retrieveBSON; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js new file mode 100644 index 00000000..9d170d90 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js @@ -0,0 +1,696 @@ +"use strict"; + +var Logger = require('./connection/logger') + , retrieveBSON = require('./connection/utils').retrieveBSON + , MongoError = require('./error') + , f = require('util').format; + +var BSON = retrieveBSON(), + Long = BSON.Long; + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * assert.equal(null, err); + * + * // Execute the write + * var cursor = _server.cursor('integration_tests.inserts_example4', { + * find: 'integration_tests.example4' + * , query: {a:1} + * }, { + * readPreference: new ReadPreference('secondary'); + * }); + * + * // Get the first document + * cursor.next(function(err, doc) { + * assert.equal(null, err); + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Cursor, not to be used directly + * @class + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + * @return {Cursor} A cursor instance + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null + , cmd: cmd + , documents: options.documents || [] + , cursorIndex: 0 + , dead: false + , killed: false + , init: false + , notified: false + , limit: options.limit || cmd.limit || 0 + , skip: options.skip || cmd.skip || 0 + , batchSize: options.batchSize || cmd.batchSize || 1000 + , currentLimit: 0 + // Result field name if not a cursor (contains the array of results) + , transforms: options.transforms + } + + // Add promoteLong to cursor state + if(typeof topologyOptions.promoteLongs == 'boolean') { + this.cursorState.promoteLongs = topologyOptions.promoteLongs; + } else if(typeof options.promoteLongs == 'boolean') { + this.cursorState.promoteLongs = options.promoteLongs; + } + + // Add promoteValues to cursor state + if(typeof topologyOptions.promoteValues == 'boolean') { + this.cursorState.promoteValues = topologyOptions.promoteValues; + } else if(typeof options.promoteValues == 'boolean') { + this.cursorState.promoteValues = options.promoteValues; + } + + // Add promoteBuffers to cursor state + if(typeof topologyOptions.promoteBuffers == 'boolean') { + this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; + } else if(typeof options.promoteBuffers == 'boolean') { + this.cursorState.promoteBuffers = options.promoteBuffers; + } + + // Logger + this.logger = Logger('Cursor', topologyOptions); + + // + // Did we pass in a cursor id + if(typeof cmd == 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + this.cursorState.lastCursorId = this.cursorState.cursorId; + } else if(cmd instanceof Long) { + this.cursorState.cursorId = cmd; + this.cursorState.lastCursorId = cmd; + } +} + +Cursor.prototype.setCursorBatchSize = function(value) { + this.cursorState.batchSize = value; +} + +Cursor.prototype.cursorBatchSize = function() { + return this.cursorState.batchSize; +} + +Cursor.prototype.setCursorLimit = function(value) { + this.cursorState.limit = value; +} + +Cursor.prototype.cursorLimit = function() { + return this.cursorState.limit; +} + +Cursor.prototype.setCursorSkip = function(value) { + this.cursorState.skip = value; +} + +Cursor.prototype.cursorSkip = function() { + return this.cursorState.skip; +} + +// +// Handle callback (including any exceptions thrown) +var handleCallback = function(callback, err, result) { + try { + callback(err, result); + } catch(err) { + process.nextTick(function() { + throw err; + }); + } +} + +// Internal methods +Cursor.prototype._find = function(callback) { + var self = this; + + if(self.logger.isDebug()) { + self.logger.debug(f('issue initial query [%s] with flags [%s]' + , JSON.stringify(self.cmd) + , JSON.stringify(self.query))); + } + + var queryCallback = function(err, r) { + if(err) return callback(err); + + // Get the raw message + var result = r.message; + + // Query failure bit set + if(result.queryFailure) { + return callback(MongoError.create(result.documents[0]), null); + } + + // Check if we have a command cursor + if(Array.isArray(result.documents) && result.documents.length == 1 + && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false)) + && (result.documents[0].cursor != 'string' + || result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || Array.isArray(result.documents[0].result)) + ) { + + // We have a an error document return the error + if(result.documents[0]['$err'] + || result.documents[0]['errmsg']) { + return callback(MongoError.create(result.documents[0]), null); + } + + // We have a cursor document + if(result.documents[0].cursor != null + && typeof result.documents[0].cursor != 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if(result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; + self.cursorState.lastCursorId = self.cursorState.cursorId; + // If we have a firstBatch set it + if(Array.isArray(result.documents[0].cursor.firstBatch)) { + self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); + } + + // Return after processing command cursor + return callback(null, null); + } + + if(Array.isArray(result.documents[0].result)) { + self.cursorState.documents = result.documents[0].result; + self.cursorState.cursorId = Long.ZERO; + return callback(null, null); + } + } + + // Otherwise fall back to regular find path + self.cursorState.cursorId = result.cursorId; + self.cursorState.documents = result.documents; + self.cursorState.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') { + self.cursorState.documents = self.cursorState.transforms.query(result); + } + + // Return callback + callback(null, null); + } + + // Options passed to the pool + var queryOptions = {}; + + // If we have a raw query decorate the function + if(self.options.raw || self.cmd.raw) { + // queryCallback.raw = self.options.raw || self.cmd.raw; + queryOptions.raw = self.options.raw || self.cmd.raw; + } + + // Do we have documentsReturnedIn set on the query + if(typeof self.query.documentsReturnedIn == 'string') { + // queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; + queryOptions.documentsReturnedIn = self.query.documentsReturnedIn; + } + + // Add promote Long value if defined + if(typeof self.cursorState.promoteLongs == 'boolean') { + queryOptions.promoteLongs = self.cursorState.promoteLongs; + } + + // Add promote values if defined + if(typeof self.cursorState.promoteValues == 'boolean') { + queryOptions.promoteValues = self.cursorState.promoteValues; + } + + // Add promote values if defined + if(typeof self.cursorState.promoteBuffers == 'boolean') { + queryOptions.promoteBuffers = self.cursorState.promoteBuffers; + } + + // Write the initial command out + self.server.s.pool.write(self.query, queryOptions, queryCallback); +} + +Cursor.prototype._getmore = function(callback) { + if(this.logger.isDebug()) this.logger.debug(f('schedule getMore call for query [%s]', JSON.stringify(this.query))) + // Determine if it's a raw query + var raw = this.options.raw || this.cmd.raw; + + // Set the current batchSize + var batchSize = this.cursorState.batchSize; + if(this.cursorState.limit > 0 + && ((this.cursorState.currentLimit + batchSize) > this.cursorState.limit)) { + batchSize = this.cursorState.limit - this.cursorState.currentLimit; + } + + // Default pool + var pool = this.server.s.pool; + + // We have a wire protocol handler + this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, batchSize, raw, pool, this.options, callback); +} + +Cursor.prototype._killcursor = function(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { + if(callback) callback(null, null); + return; + } + + // Default pool + var pool = this.server.s.pool; + // Execute command + this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, pool, callback); +} + +/** + * Clone the cursor + * @method + * @return {Cursor} + */ +Cursor.prototype.clone = function() { + return this.topology.cursor(this.ns, this.cmd, this.options); +} + +/** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ +Cursor.prototype.isDead = function() { + return this.cursorState.dead == true; +} + +/** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ +Cursor.prototype.isKilled = function() { + return this.cursorState.killed == true; +} + +/** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ +Cursor.prototype.isNotified = function() { + return this.cursorState.notified == true; +} + +/** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ +Cursor.prototype.bufferedCount = function() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; +} + +/** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ +Cursor.prototype.readBufferedDocuments = function(number) { + var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); + + // Transform the doc with passed in transformation method if provided + if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { + // Transform all the elements + for(var i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) { + elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit)); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; +} + +/** + * Kill the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.kill = function(callback) { + this._killcursor(callback); +} + +/** + * Resets the cursor + * @method + * @return {null} + */ +Cursor.prototype.rewind = function() { + if(this.cursorState.init) { + if(!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } +} + +/** + * Validate if the pool is dead and return error + */ +var isConnectionDead = function(self, callback) { + if(self.pool + && self.pool.isDestroyed()) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + callback(MongoError.create(f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port))) + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +var isCursorDeadButNotkilled = function(self, callback) { + // Cursor is dead but not marked killed, return null + if(self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +var isCursorDeadAndKilled = function(self, callback) { + if(self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, MongoError.create('cursor is dead')); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +var isCursorKilled = function(self, callback) { + if(self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +var setCursorDeadAndNotified = function(self, callback) { + self.cursorState.dead = true; + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +/** + * Mark cursor as being notified + */ +var setCursorNotified = function(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +var nextFunction = function(self, callback) { + // We have notified about it + if(self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if(isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if(isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if(isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if(!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) { + if (self.topology.isDestroyed()) { + // Topology was destroyed, so don't try to wait for it to reconnect + return callback(new MongoError('Topology was destroyed')); + } + return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + } + + try { + self.server = self.topology.getServer(self.options); + } catch(err) { + // Handle the error and add object to next method call + if(self.disconnectHandler != null) { + return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + } + + // Otherwise return the error + return callback(err); + } + + // Set as init + self.cursorState.init = true; + + // Server does not support server + if(self.cmd + && self.cmd.collation + && self.server.ismaster.maxWireVersion < 5) { + return callback(new MongoError(f('server %s does not support collation', self.server.name))); + } + + try { + self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); + } catch(err) { + return callback(err); + } + } + + // If we don't have a cursorId execute the first query + if(self.cursorState.cursorId == null) { + // Check if pool is dead and return if not possible to + // execute the query against the db + if(isConnectionDead(self, callback)) return; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError('connection destroyed, not possible to instantiate cursor')); + + // query, cmd, options, cursorState, callback + self._find(function(err) { + if(err) return handleCallback(callback, err, null); + + if(self.cursorState.documents.length == 0 + && self.cursorState.cursorId && self.cursorState.cursorId.isZero() + && !self.cmd.tailable && !self.cmd.awaitData) { + return setCursorNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if(self.cursorState.cursorIndex == self.cursorState.documents.length + && !Long.ZERO.equals(self.cursorState.cursorId)) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError('connection destroyed, not possible to instantiate cursor')); + + // Check if connection is dead and return if not possible to + // execute a getmore on this connection + if(isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getmore(function(err, doc, connection) { + if(err) return handleCallback(callback, err); + + // Save the returned connection to ensure all getMore's fire over the same connection + self.connection = connection; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if(self.cursorState.documents.length == 0 + && self.cmd.tailable && Long.ZERO.equals(self.cursorState.cursorId)) { + // No more documents in the tailed cursor + return handleCallback(callback, MongoError.create({ + message: 'No more documents in tailed cursor' + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } else if(self.cursorState.documents.length == 0 + && self.cmd.tailable && !Long.ZERO.equals(self.cursorState.cursorId)) { + return nextFunction(self, callback); + } + + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && self.cmd.tailable && Long.ZERO.equals(self.cursorState.cursorId)) { + return handleCallback(callback, MongoError.create({ + message: 'No more documents in tailed cursor' + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && Long.ZERO.equals(self.cursorState.cursorId)) { + setCursorDeadAndNotified(self, callback); + } else { + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Doc overflow + if(doc.$err) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, function() { + handleCallback(callback, new MongoError(doc.$err)); + }); + } + + // Transform the doc with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +/** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.next = function(callback) { + nextFunction(this, callback); +} + +module.exports = Cursor; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/error.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/error.js new file mode 100644 index 00000000..31ede94d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/error.js @@ -0,0 +1,44 @@ +"use strict"; + +/** + * Creates a new MongoError + * @class + * @augments Error + * @param {string} message The error message + * @return {MongoError} A MongoError instance + */ +function MongoError(message) { + this.name = 'MongoError'; + this.message = message; + Error.captureStackTrace(this, MongoError); +} + +/** + * Creates a new MongoError object + * @method + * @param {object} options The error options + * @return {MongoError} A MongoError instance + */ +MongoError.create = function(options) { + var err = null; + + if(options instanceof Error) { + err = new MongoError(options.message); + err.stack = options.stack; + } else if(typeof options == 'string') { + err = new MongoError(options); + } else { + err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); + // Other options + for(var name in options) { + err[name] = options[name]; + } + } + + return err; +} + +// Extend JavaScript error +MongoError.prototype = new Error; + +module.exports = MongoError; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js new file mode 100644 index 00000000..dcceda4b --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js @@ -0,0 +1,59 @@ +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results : [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: "" + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: "fail", + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: "" + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js new file mode 100644 index 00000000..d0ffcff0 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js @@ -0,0 +1,1133 @@ +"use strict" + +var inherits = require('util').inherits, + f = require('util').format, + EventEmitter = require('events').EventEmitter, + BasicCursor = require('../cursor'), + Logger = require('../connection/logger'), + retrieveBSON = require('../connection/utils').retrieveBSON, + MongoError = require('../error'), + Server = require('./server'), + assign = require('./shared').assign, + clone = require('./shared').clone, + createClientInfo = require('./shared').createClientInfo; + +var BSON = retrieveBSON(); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * @example + * var Mongos = require('mongodb-core').Mongos + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Mongos([{host: 'localhost', port: 30000}]); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram'); + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + 'disconnected': [CONNECTING, DESTROYED, DISCONNECTED], + 'connecting': [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + 'connected': [CONNECTED, DISCONNECTED, DESTROYED], + 'destroyed': [DESTROYED] + } + + // Get current state + var legalStates = legalTransitions[self.state]; + if(legalStates && legalStates.indexOf(newState) != -1) { + self.state = newState; + } else { + self.logger.error(f('Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]' + , self.id, self.state, newState, legalStates)); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#reconnect + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#failed + * @fires Mongos#fullsetup + * @fires Mongos#all + * @fires Mongos#serverHeartbeatStarted + * @fires Mongos#serverHeartbeatSucceeded + * @fires Mongos#serverHeartbeatFailed + * @fires Mongos#topologyOpening + * @fires Mongos#topologyClosed + * @fires Mongos#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Mongos = function(seedlist, options) { + options = options || {}; + + // Get replSet Id + this.id = id++; + + // Internal state + this.s = { + options: assign({}, options), + // BSON instance + bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, + BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, + BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // Logger instance + logger: Logger('Mongos', options), + // Seedlist + seedlist: seedlist, + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug == 'boolean' ? options.debug : false, + // localThresholdMS + localThresholdMS: options.localThresholdMS || 15, + // Client info + clientInfo: createClientInfo(options) + } + + // Set the client info + this.s.options.clientInfo = createClientInfo(options); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if(this.s.logger.isWarn() + && this.s.options.socketTimeout != 0 + && this.s.options.socketTimeout < this.s.haInterval) { + this.s.logger.warn(f('warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts' + , this.s.options.socketTimeout, this.s.haInterval)); + } + + // All the authProviders + this.authProviders = options.authProviders || { + 'mongocr': new MongoCR(this.s.bson), 'x509': new X509(this.s.bson) + , 'plain': new Plain(this.s.bson), 'gssapi': new GSSAPI(this.s.bson) + , 'sspi': new SSPI(this.s.bson), 'scram-sha-1': new ScramSHA1(this.s.bson) + } + + // Disconnected state + this.state = DISCONNECTED; + + // Current proxies we are connecting to + this.connectingProxies = []; + // Currently connected proxies + this.connectedProxies = []; + // Disconnected proxies + this.disconnectedProxies = []; + // Are we authenticating + this.authenticating = false; + // Index of proxy to run operations against + this.index = 0; + // High availability timeout id + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + + // Add event listener + EventEmitter.call(this); +} + +inherits(Mongos, EventEmitter); + +Object.defineProperty(Mongos.prototype, 'type', { + enumerable:true, get: function() { return 'mongos'; } +}); + +Object.defineProperty(Mongos.prototype, 'parserType', { + enumerable:true, get: function() { + return BSON.native ? "c++" : "js"; + } +}); + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if(self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +Mongos.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + // Set connecting state + stateTransition(this, CONNECTING); + // Create server instances + var servers = this.s.seedlist.map(function(x) { + return new Server(assign({}, self.s.options, x, { + authProviders: self.authProviders, reconnect:false, monitoring:false, inTopology: true + }, { + clientInfo: clone(self.s.clientInfo) + })); + }); + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + + // Start all server connections + connectProxies(self, servers); +} + +function handleEvent(self) { + return function() { + if(self.state == DESTROYED) return; + // Move to list of disconnectedProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); + // Emit the left signal + self.emit('left', 'mongos', this); + } +} + +function handleInitialConnectEvent(self, event) { + return function() { + // Destroy the instance + if(self.state == DESTROYED) { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + return this.destroy(); + } + + // Check the type of server + if(event == 'connect') { + // Get last known ismaster + self.ismaster = this.lastIsMaster(); + + // Is this not a proxy, remove t + if(self.ismaster.msg == 'isdbgrid') { + // Add to the connectd list + for(var i = 0; i < self.connectedProxies.length; i++) { + if(self.connectedProxies[i].name == this.name) { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + this.destroy(); + return self.emit('failed', this); + } + } + + // Remove the handlers + for(i = 0; i < handlers.length; i++) { + this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + this.on('error', handleEvent(self, 'error')); + this.on('close', handleEvent(self, 'close')); + this.on('timeout', handleEvent(self, 'timeout')); + this.on('parseError', handleEvent(self, 'parseError')); + + // Move from connecting proxies connected + moveServerFrom(self.connectingProxies, self.connectedProxies, this); + // Emit the joined event + self.emit('joined', 'mongos', this); + } else { + + // Print warning if we did not find a mongos proxy + if(self.s.logger.isWarn()) { + var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; + // We have a standalone server + if(!self.ismaster.hosts) { + message = 'expected mongos proxy, but found standalone mongod for server %s'; + } + + self.s.logger.warn(f(message, this.name)); + } + + // This is not a mongos proxy, remove it completely + removeProxyFrom(self.connectingProxies, this); + // Emit the left event + self.emit('left', 'server', this); + // Emit failed event + self.emit('failed', this); + } + } else { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + // Emit the left event + self.emit('left', 'mongos', this); + // Emit failed event + self.emit('failed', this); + } + + // Trigger topologyMonitor + if(self.connectingProxies.length == 0) { + // Emit connected if we are connected + if(self.connectedProxies.length > 0) { + // Set the state to connected + stateTransition(self, CONNECTED); + // Emit the connect event + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if(self.disconnectedProxies.length == 0) { + // Print warning if we did not find a mongos proxy + if(self.s.logger.isWarn()) { + self.s.logger.warn(f('no mongos proxies found in seed list, did you mean to connect to a replicaset')); + } + + // Emit the error that no proxies were found + return self.emit('error', new MongoError('no mongos proxies found in seed list')); + } + + // Topology monitor + topologyMonitor(self, {firstConnect:true}); + } + }; +} + +function connectProxies(self, servers) { + // Update connectingProxies + self.connectingProxies = self.connectingProxies.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + // SDAM Monitoring events + server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); + server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); + server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + // Start all the servers + while(servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +function pickProxy(self) { + // Get the currently connected Proxies + var connectedProxies = self.connectedProxies.slice(0); + + // Set lower bound + var lowerBoundLatency = Number.MAX_VALUE; + + // Determine the lower bound for the Proxies + for(var i = 0; i < connectedProxies.length; i++) { + if(connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { + lowerBoundLatency = connectedProxies[i].lastIsMasterMS; + } + } + + // Filter out the possible servers + connectedProxies = connectedProxies.filter(function(server) { + if((server.lastIsMasterMS <= (lowerBoundLatency + self.s.localThresholdMS)) + && server.isConnected()) { + return true; + } + }); + + // We have no connectedProxies pick first of the connected ones + if(connectedProxies.length == 0) { + return self.connectedProxies[0]; + } + + // Get proxy + var proxy = connectedProxies[self.index % connectedProxies.length]; + // Update the index + self.index = (self.index + 1) % connectedProxies.length; + // Return the proxy + return proxy; +} + +function moveServerFrom(from, to, proxy) { + for(var i = 0; i < from.length; i++) { + if(from[i].name == proxy.name) { + from.splice(i, 1); + } + } + + for(i = 0; i < to.length; i++) { + if(to[i].name == proxy.name) { + to.splice(i, 1); + } + } + + to.push(proxy); +} + +function removeProxyFrom(from, proxy) { + for(var i = 0; i < from.length; i++) { + if(from[i].name == proxy.name) { + from.splice(i, 1); + } + } +} + +function reconnectProxies(self, proxies, callback) { + // Count lefts + var count = proxies.length; + + // Handle events + var _handleEvent = function(self, event) { + return function() { + var _self = this; + count = count - 1; + + // Destroyed + if(self.state == DESTROYED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return this.destroy(); + } + + if(event == 'connect' && !self.authenticating) { + // Destroyed + if(self.state == DESTROYED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return _self.destroy(); + } + + // Remove the handlers + for(var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Move to the connected servers + moveServerFrom(self.disconnectedProxies, self.connectedProxies, _self); + // Emit joined event + self.emit('joined', 'mongos', _self); + } else if(event == 'connect' && self.authenticating) { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + this.destroy(); + } + + // Are we done finish up callback + if(count == 0) { + callback(); + } + } + } + + // No new servers + if(count == 0) { + return callback(); + } + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if(self.state == DESTROYED) { + return; + } + + // Create a new server instance + var server = new Server(assign({}, self.s.options, { + host: _server.name.split(':')[0], + port: parseInt(_server.name.split(':')[1], 10) + }, { + authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true + }, { + clientInfo: clone(self.s.clientInfo) + })); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // SDAM Monitoring events + server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); + server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); + server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for(var i = 0; i < proxies.length; i++) { + execute(proxies[i], i); + } +} + +function topologyMonitor(self, options) { + options = options || {}; + + // Set momitoring timeout + self.haTimeoutId = setTimeout(function() { + if(self.state == DESTROYED) return; + // If we have a primary and a disconnect handler, execute + // buffered operations + if(self.isConnected() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } + + // Get the connectingServers + var proxies = self.connectedProxies.slice(0); + // Get the count + var count = proxies.length; + + // If the count is zero schedule a new fast + function pingServer(_self, _server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); + + // Execute ismaster + _server.command('admin.$cmd', { + ismaster:true + }, { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000, + }, function(err, r) { + if(self.state == DESTROYED) { + // Move from connectingProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + _server.destroy(); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // We had an error, remove it from the state + if(err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name }); + // Move from connected proxies to disconnected proxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + } else { + // Update the server ismaster + _server.ismaster = r.result; + _server.lastIsMasterMS = latencyMS; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name }); + } + + cb(err, r); + }); + } + + // No proxies initiate monitor again + if(proxies.length == 0) { + // Emit close event if any listeners registered + if(self.listeners("close").length > 0 && self.state == CONNECTING) { + self.emit('error', new MongoError('no mongos proxy available')); + } else { + self.emit('close', self); + } + + // Attempt to connect to any unknown servers + return reconnectProxies(self, self.disconnectedProxies, function() { + if(self.state == DESTROYED) return; + + // Are we connected ? emit connect event + if(self.state == CONNECTING && options.firstConnect) { + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if(self.isConnected()) { + self.emit('reconnect', self); + } else if(!self.isConnected() && self.listeners("close").length > 0) { + self.emit('close', self); + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + + // Ping all servers + for(var i = 0; i < proxies.length; i++) { + pingServer(self, proxies[i], function() { + count = count - 1; + + if(count == 0) { + if(self.state == DESTROYED) return; + + // Attempt to connect to any unknown servers + reconnectProxies(self, self.disconnectedProxies, function() { + if(self.state == DESTROYED) return; + // Perform topology monitor + topologyMonitor(self); + }); + } + }); + } + }, self.s.haInterval); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + return this.ismaster; +} + +/** + * Unref all connections belong to this server + * @method + */ +Mongos.prototype.unref = function() { + // Transition state + stateTransition(this, DISCONNECTED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + proxies.forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +} + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +Mongos.prototype.destroy = function(options) { + // Transition state + stateTransition(this, DESTROYED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + // Clear out any monitoring process + if(this.haTimeoutId) clearTimeout(this.haTimeoutId); + + // Destroy all connecting servers + proxies.forEach(function(x) { + x.destroy(options); + }); + + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.connectedProxies.length > 0; +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.state == DESTROYED; +} + +// +// Operations +// + +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + // Ensure we have no options + options = options || {}; + // Pick a server + var server = pickProxy(self); + // No server found error out + if(!server) return callback(new MongoError('no mongos proxy available')); + // Execute the command + server[op](ns, ops, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if(!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // No mongos proxy available + if(!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if(!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // No mongos proxy available + if(!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'update', ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if(!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // No mongos proxy available + if(!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'remove', ns, ops, options, callback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Pick a proxy + var server = pickProxy(self); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // No server returned we had an error + if(server == null) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute the command + server.command(ns, cmd, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.authProviders[mechanism] == null && mechanism != 'default') { + return callback(new MongoError(f("auth provider %s does not exist", mechanism))); + } + + // Are we already authenticating, throw + if(this.authenticating) { + return callback(new MongoError('authentication or logout allready in process')); + } + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); + } + + // Set to authenticating + this.authenticating = true; + // All errors + var errors = []; + + // Get all the servers + var servers = this.connectedProxies.slice(0); + // No servers return + if(servers.length == 0) { + this.authenticating = false; + callback(null, true); + } + + // Authenticate + function auth(server) { + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err) { + count = count - 1; + // Save all the errors + if(err) errors.push({name: server.name, err: err}); + // We are done + if(count == 0) { + // Auth is done + self.authenticating = false; + + // Return the auth error + if(errors.length) return callback(MongoError.create({ + message: 'authentication fail', errors: errors + }), false); + + // Successfully authenticated session + callback(null, self); + } + }]); + + // Execute the auth only against non arbiter servers + if(!server.lastIsMaster().arbiterOnly) { + server.auth.apply(server, finalArguments); + } + } + + // Get total count + var count = servers.length; + // Authenticate against all servers + while(servers.length > 0) { + auth(servers.shift()); + } +} + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.logout = function(dbName, callback) { + var self = this; + // Are we authenticating or logging out, throw + if(this.authenticating) { + throw new MongoError('authentication or logout allready in process'); + } + + // Ensure no new members are processed while logging out + this.authenticating = true; + + // Remove from all auth providers (avoid any reaplication of the auth details) + var providers = Object.keys(this.authProviders); + for(var i = 0; i < providers.length; i++) { + this.authProviders[providers[i]].logout(dbName); + } + + // Now logout all the servers + var servers = this.connectedProxies.slice(0); + var count = servers.length; + if(count == 0) return callback(); + var errors = []; + + function logoutServer(_server, cb) { + _server.logout(dbName, function(err) { + if(err) errors.push({name: _server.name, err: err}); + cb(); + }); + } + + // Execute logout on all server instances + for(i = 0; i < servers.length; i++) { + logoutServer(servers[i], function() { + count = count - 1; + + if(count == 0) { + // Do not block new operations + self.authenticating = false; + // If we have one or more errors + if(errors.length) return callback(MongoError.create({ + message: f('logout failed against db %s', dbName), errors: errors + }), false); + + // No errors + callback(); + } + }) + } +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Mongos.prototype.getServer = function() { + var server = pickProxy(this); + if(this.s.debug) this.emit('pickedServer', null, server); + return server; +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + var connections = []; + + for(var i = 0; i < this.connectedProxies.length; i++) { + connections = connections.concat(this.connectedProxies[i].connections()); + } + + return connections; +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A mongos reconnect event, used to verify that the mongos topology has reconnected + * + * @event Mongos#reconnect + * @type {Mongos} + */ + +/** + * A mongos fullsetup event, used to signal that all topology members have been contacted. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * A mongos all event, used to signal that all topology members have been contacted. + * + * @event Mongos#all + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event Mongos#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Mongos#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Mongos#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Mongos#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Mongos#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Mongos#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Mongos#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Mongos#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Mongos#serverHeartbeatSucceeded + * @type {object} + */ + +module.exports = Mongos; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js new file mode 100644 index 00000000..1f10dd97 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js @@ -0,0 +1,118 @@ +"use strict"; + +var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * var cursor = server.cursor('db.test' + * , {find: 'db.test', query: {}} + * , {readPreference: new ReadPreference('secondary')}); + * cursor.next(function(err, doc) { + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Pool instance + * @class + * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {array} tags The tags object + * @param {object} [options] Additional read preference options + * @param {number} [options.maxStalenessSeconds] Max Secondary Read Stalleness in Seconds, Minimum value is 90 seconds. + * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @property {array} tags The tags object + * @property {object} options Additional read preference options + * @property {number} maxStalenessSeconds MaxStalenessSeconds value for the read preference + * @return {ReadPreference} + */ +var ReadPreference = function(preference, tags, options) { + this.preference = preference; + this.tags = tags; + this.options = options; + + // Add the maxStalenessSeconds value to the read Preference + if(this.options && this.options.maxStalenessSeconds != null) { + this.options = options; + this.maxStalenessSeconds = this.options.maxStalenessSeconds >= 0 + ? this.options.maxStalenessSeconds : null; + } else if(tags && typeof tags == 'object') { + this.options = tags, tags = null; + } +} + +/** + * This needs slaveOk bit set + * @method + * @return {boolean} + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.preference) != -1; +} + +/** + * Are the two read preference equal + * @method + * @return {boolean} + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.preference == this.preference; +} + +/** + * Return JSON representation + * @method + * @return {Object} + */ +ReadPreference.prototype.toJSON = function() { + var readPreference = {mode: this.preference}; + if(Array.isArray(this.tags)) readPreference.tags = this.tags; + if(this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + return readPreference; +} + +/** + * Primary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js new file mode 100644 index 00000000..0082da8a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js @@ -0,0 +1,1403 @@ +"use strict" + +var inherits = require('util').inherits, + f = require('util').format, + EventEmitter = require('events').EventEmitter, + ReadPreference = require('./read_preference'), + BasicCursor = require('../cursor'), + retrieveBSON = require('../connection/utils').retrieveBSON, + Logger = require('../connection/logger'), + MongoError = require('../error'), + Server = require('./server'), + ReplSetState = require('./replset_state'), + assign = require('./shared').assign, + clone = require('./shared').clone, + createClientInfo = require('./shared').createClientInfo; + +var MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram'); + +var BSON = retrieveBSON(); + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + 'disconnected': [CONNECTING, DESTROYED, DISCONNECTED], + 'connecting': [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + 'connected': [CONNECTED, DISCONNECTED, DESTROYED], + 'destroyed': [DESTROYED] + } + + // Get current state + var legalStates = legalTransitions[self.state]; + if(legalStates && legalStates.indexOf(newState) != -1) { + self.state = newState; + } else { + self.logger.error(f('Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]' + , self.id, self.state, newState, legalStates)); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#failed + * @fires ReplSet#fullsetup + * @fires ReplSet#all + * @fires ReplSet#error + * @fires ReplSet#serverHeartbeatStarted + * @fires ReplSet#serverHeartbeatSucceeded + * @fires ReplSet#serverHeartbeatFailed + * @fires ReplSet#topologyOpening + * @fires ReplSet#topologyClosed + * @fires ReplSet#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // Add event listener + EventEmitter.call(this); + + // Get replSet Id + this.id = id++; + + // Get the localThresholdMS + var localThresholdMS = options.localThresholdMS || 15; + // Backward compatibility + if(options.acceptableLatency) localThresholdMS = options.acceptableLatency; + + // Create a logger + var logger = Logger('ReplSet', options); + + // Internal state + this.s = { + options: assign({}, options), + // BSON instance + bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, + BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, + BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // Logger instance + logger: logger, + // Seedlist + seedlist: seedlist, + // Replicaset state + replicaSetState: new ReplSetState({ + id: this.id, setName: options.setName, + acceptableLatency: localThresholdMS, + heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, + logger: logger + }), + // Current servers we are connecting to + connectingServers: [], + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Minimum heartbeat frequency used if we detect a server close + minHeartbeatFrequencyMS: 500, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug == 'boolean' ? options.debug : false, + // Client info + clientInfo: createClientInfo(options) + } + + // Add handler for topology change + this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { self.emit('topologyDescriptionChanged', r); }); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if(this.s.logger.isWarn() + && this.s.options.socketTimeout != 0 + && this.s.options.socketTimeout < this.s.haInterval) { + this.s.logger.warn(f('warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts' + , this.s.options.socketTimeout, this.s.haInterval)); + } + + // All the authProviders + this.authProviders = options.authProviders || { + 'mongocr': new MongoCR(this.s.bson), 'x509': new X509(this.s.bson) + , 'plain': new Plain(this.s.bson), 'gssapi': new GSSAPI(this.s.bson) + , 'sspi': new SSPI(this.s.bson), 'scram-sha-1': new ScramSHA1(this.s.bson) + } + + // Add forwarding of events from state handler + var types = ['joined', 'left']; + types.forEach(function(x) { + self.s.replicaSetState.on(x, function(t, s) { + if(self.state === CONNECTED && x === 'joined' && t == 'primary') { + self.emit('reconnect', self); + } + + self.emit(x, t, s); + }); + }); + + // Connect stat + this.initialConnectState = { + connect: false, fullsetup: false, all: false + } + + // Disconnected state + this.state = DISCONNECTED; + this.haTimeoutId = null; + // Are we authenticating + this.authenticating = false; + // Last ismaster + this.ismaster = null; +} + +inherits(ReplSet, EventEmitter); + +Object.defineProperty(ReplSet.prototype, 'type', { + enumerable:true, get: function() { return 'replset'; } +}); + +Object.defineProperty(ReplSet.prototype, 'parserType', { + enumerable:true, get: function() { + return BSON.native ? "c++" : "js"; + } +}); + +function attemptReconnect(self) { + if(self.runningAttempReconnect) return; + // Set as running + self.runningAttempReconnect = true; + // Wait before execute + self.haTimeoutId = setTimeout(function() { + if(self.state == DESTROYED) return; + + // Debug log + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('attemptReconnect for replset with id %s', self.id)); + } + + // Get all known hosts + var keys = Object.keys(self.s.replicaSetState.set); + var servers = keys.map(function(x) { + return new Server(assign({}, self.s.options, { + host: x.split(':')[0], port: parseInt(x.split(':')[1], 10) + }, { + authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true + }, { + clientInfo: clone(self.s.clientInfo) + })); + }); + + // Create the list of servers + self.s.connectingServers = servers.slice(0); + + // Handle all events coming from servers + function _handleEvent(self, event) { + return function() { + // Destroy the instance + if(self.state == DESTROYED) { + return this.destroy(); + } + + // Debug log + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('attemptReconnect for replset with id %s using server %s ended with event %s', self.id, this.name, event)); + } + + // Check if we are done + function done() { + // Done with the reconnection attempt + if(self.s.connectingServers.length == 0) { + if(self.state == DESTROYED) return; + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } else if(self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executePrimary:true }); + } else if(self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executeSecondary:true }); + } + + // Do we have a primary + if(self.s.replicaSetState.hasPrimary()) { + // Emit reconnect as new primary was discovered + self.emit('reconnect', self); + + // Connect any missing servers + connectNewServers(self, self.s.replicaSetState.unknownServers, function() { + // Debug log + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('attemptReconnect for replset with id successful resuming topologyMonitor', self.id)); + } + + // Reset the running + self.runningAttempReconnect = false; + + // Go back to normal topology monitoring + // Schedule a topology monitoring sweep + setTimeout(function() { + topologyMonitor(self); + }, self.s.haInterval); + }); + } else { + if(self.listeners("close").length > 0) { + self.emit('close', self); + } + + // Reset the running + self.runningAttempReconnect = false; + // Attempt a new reconnect + attemptReconnect(self); + } + } + } + + // Remove the server from our list + for(var i = 0; i < self.s.connectingServers.length; i++) { + if(self.s.connectingServers[i].equals(this)) { + self.s.connectingServers.splice(i, 1); + } + } + + // Keep reference to server + var _self = this; + + // Debug log + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('attemptReconnect in replset with id %s for', self.id)); + } + + // Connect and not authenticating + if(event == 'connect' && !self.authenticating) { + if(self.state == DESTROYED) { + return _self.destroy(); + } + + // Update the replicaset state + if(self.s.replicaSetState.update(_self)) { + // Primary lastIsMaster store it + if(_self.lastIsMaster() && _self.lastIsMaster().ismaster) { + self.ismaster = _self.lastIsMaster(); + } + + // Remove the handlers + for(i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + } else { + _self.destroy(); + } + } else if(event == 'connect' && self.authenticating) { + this.destroy(); + } + + done(); + } + } + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // SDAM Monitoring events + server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); + server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); + server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); + + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Connect all servers + while(servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } + }, self.s.minHeartbeatFrequencyMS); +} + +function connectNewServers(self, servers, callback) { + // Count lefts + var count = servers.length; + + // Handle events + var _handleEvent = function(self, event) { + return function() { + var _self = this; + count = count - 1; + + // Destroyed + if(self.state == DESTROYED) { + return this.destroy(); + } + + if(event == 'connect' && !self.authenticating) { + // Destroyed + if(self.state == DESTROYED) { + return _self.destroy(); + } + + var result = self.s.replicaSetState.update(_self); + // Update the state with the new server + if(result) { + // Primary lastIsMaster store it + if(_self.lastIsMaster() && _self.lastIsMaster().ismaster) { + self.ismaster = _self.lastIsMaster(); + } + + // Remove the handlers + for(var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + } else { + _self.destroy(); + } + } else if(event == 'connect' && self.authenticating) { + this.destroy(); + } + + // Are we done finish up callback + if(count == 0) { callback(); } + } + } + + // No new servers + if(count == 0) return callback(); + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if(self.state == DESTROYED) { + return; + } + + // Create a new server instance + var server = new Server(assign({}, self.s.options, { + host: _server.split(':')[0], + port: parseInt(_server.split(':')[1], 10) + }, { + authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true + }, { + clientInfo: clone(self.s.clientInfo) + })); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // SDAM Monitoring events + server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); + server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); + server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for(var i = 0; i < servers.length; i++) { + execute(servers[i], i); + } +} + +function topologyMonitor(self, options) { + options = options || {}; + + // Set momitoring timeout + self.haTimeoutId = setTimeout(function() { + if(self.state == DESTROYED) return; + + // Is this a on connect topology discovery + // Schedule a proper topology monitoring to happen + // To ensure any discovered servers do not timeout + // while waiting for the initial discovery to happen. + if(options.haInterval) { + topologyMonitor(self); + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } else if(self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executePrimary:true }); + } else if(self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executeSecondary:true }); + } + + // Get the connectingServers + var connectingServers = self.s.replicaSetState.allServers(); + // Debug log + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('topologyMonitor in replset with id %s connected servers [%s]' + , self.id + , connectingServers.map(function(x) { + return x.name; + }))); + } + // Get the count + var count = connectingServers.length; + + // If we have no servers connected + if(count == 0 && !options.haInterval) { + if(self.listeners("close").length > 0) { + self.emit('close', self); + } + + return attemptReconnect(self); + } + + // If the count is zero schedule a new fast + function pingServer(_self, _server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); + // Execute ismaster + // Set the socketTimeout for a monitoring message to a low number + // Ensuring ismaster calls are timed out quickly + _server.command('admin.$cmd', { + ismaster:true + }, { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000, + }, function(err, r) { + if(self.state == DESTROYED) { + _server.destroy(); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // Set the last updatedTime + var hrTime = process.hrtime(); + // Calculate the last update time + _server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1]/1000); + + // We had an error, remove it from the state + if(err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name }); + // Remove server from the state + _self.s.replicaSetState.remove(_server); + } else { + // Update the server ismaster + _server.ismaster = r.result; + + // Check if we have a lastWriteDate convert it to MS + // and store on the server instance for later use + if(_server.ismaster.lastWrite && _server.ismaster.lastWrite.lastWriteDate) { + _server.lastWriteDate = _server.ismaster.lastWrite.lastWriteDate.getTime(); + } + + // Do we have a brand new server + if(_server.lastIsMasterMS == -1) { + _server.lastIsMasterMS = latencyMS; + } else if(_server.lastIsMasterMS) { + // After the first measurement, average RTT MUST be computed using an + // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. + // If the prior average is denoted old_rtt, then the new average (new_rtt) is + // computed from a new RTT measurement (x) using the following formula: + // alpha = 0.2 + // new_rtt = alpha * x + (1 - alpha) * old_rtt + _server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * _server.lastIsMasterMS; + } + + if(_self.s.replicaSetState.update(_server)) { + // Primary lastIsMaster store it + if(_server.lastIsMaster() && _server.lastIsMaster().ismaster) { + self.ismaster = _server.lastIsMaster(); + } + } + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name }); + } + + // Calculate the stalness for this server + self.s.replicaSetState.updateServerMaxStaleness(_server, self.s.haInterval); + + // Callback + cb(err, r); + }); + } + + // Connect any missing servers + function connectMissingServers() { + if(self.state == DESTROYED) return; + + // Attempt to connect to any unknown servers + connectNewServers(self, self.s.replicaSetState.unknownServers, function() { + if(self.state == DESTROYED) return; + + // Check if we have an options.haInterval (meaning it was triggered from connect) + if(options.haInterval) { + // Do we have a primary and secondary + if(self.state == CONNECTING + && self.s.replicaSetState.hasPrimaryAndSecondary()) { + // Transition to connected + stateTransition(self, CONNECTED); + // Update initial state + self.initialConnectState.connect = true; + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + // Emit fullsetup and all events + process.nextTick(function() { + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + }); + } else if(self.state == CONNECTING + && self.s.replicaSetState.hasPrimary()) { + // Transition to connected + stateTransition(self, CONNECTED); + // Update initial state + self.initialConnectState.connect = true; + // Emit connected sign + process.nextTick(function() { + self.emit('connect', self); + }); + } else if(self.state == CONNECTING + && self.s.replicaSetState.hasSecondary() + && self.s.options.secondaryOnlyConnectionAllowed) { + // Transition to connected + stateTransition(self, CONNECTED); + // Update initial state + self.initialConnectState.connect = true; + // Emit connected sign + process.nextTick(function() { + self.emit('connect', self); + }); + } else if(self.state == CONNECTING) { + self.emit('error', new MongoError('no primary found in replicaset')); + // Destroy the topology + return self.destroy(); + } else if(self.state == CONNECTED + && self.s.replicaSetState.hasPrimaryAndSecondary() + && !self.initialConnectState.fullsetup) { + self.initialConnectState.fullsetup = true; + // Emit fullsetup and all events + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + } + + if(!options.haInterval) topologyMonitor(self); + }); + } + + // No connectingServers but unknown servers + if(connectingServers.length == 0 + && self.s.replicaSetState.unknownServers.length > 0 && options.haInterval) { + return connectMissingServers(); + } else if(connectingServers.length == 0 && options.haInterval) { + self.destroy(); + return self.emit('error', new MongoError('no valid replicaset members found')); + } + + // Ping all servers + for(var i = 0; i < connectingServers.length; i++) { + pingServer(self, connectingServers[i], function() { + count = count - 1; + + if(count == 0) { + connectMissingServers(); + } + }); + } + }, options.haInterval || self.s.haInterval) +} + +function handleEvent(self, event) { + return function() { + if(self.state == DESTROYED) return; + // Debug log + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id)); + } + + self.s.replicaSetState.remove(this); + } +} + +function handleInitialConnectEvent(self, event) { + return function() { + // Debug log + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('handleInitialConnectEvent %s from server %s in replset with id %s', event, this.name, self.id)); + } + + // Destroy the instance + if(self.state == DESTROYED) { + return this.destroy(); + } + + // Check the type of server + if(event == 'connect') { + // Update the state + var result = self.s.replicaSetState.update(this); + if(result == true) { + // Primary lastIsMaster store it + if(this.lastIsMaster() && this.lastIsMaster().ismaster) { + self.ismaster = this.lastIsMaster(); + } + + // Debug log + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', event, this.name, self.id, JSON.stringify(self.s.replicaSetState.set))); + } + + // Remove the handlers + for(var i = 0; i < handlers.length; i++) { + this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + this.on('error', handleEvent(self, 'error')); + this.on('close', handleEvent(self, 'close')); + this.on('timeout', handleEvent(self, 'timeout')); + this.on('parseError', handleEvent(self, 'parseError')); + } else if(result instanceof MongoError) { + this.destroy(); + self.destroy(); + return self.emit('error', result); + } else { + this.destroy(); + } + } else { + // Emit failure to connect + self.emit('failed', this); + // Remove from the state + self.s.replicaSetState.remove(this); + } + + // Remove from the list from connectingServers + for(i = 0; i < self.s.connectingServers.length; i++) { + if(self.s.connectingServers[i].equals(this)) { + self.s.connectingServers.splice(i, 1); + } + } + + // Trigger topologyMonitor + if(self.s.connectingServers.length == 0) { + topologyMonitor(self, {haInterval: 1}); + } + }; +} + +function connectServers(self, servers) { + // Update connectingServers + self.s.connectingServers = self.s.connectingServers.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Add the server to the state + if(self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if(server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + // SDAM Monitoring events + server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); + server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); + server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + while(servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if(self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +ReplSet.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + // Set connecting state + stateTransition(this, CONNECTING); + // Create server instances + var servers = this.s.seedlist.map(function(x) { + return new Server(assign({}, self.s.options, x, { + authProviders: self.authProviders, reconnect:false, monitoring:false, inTopology: true + }, { + clientInfo: clone(self.s.clientInfo) + })); + }); + + // Error out as high availbility interval must be < than socketTimeout + if(this.s.options.socketTimeout > 0 && this.s.options.socketTimeout <= this.s.options.haInterval) { + return self.emit('error', new MongoError(f("haInterval [%s] MS must be set to less than socketTimeout [%s] MS" + , this.s.options.haInterval, this.s.options.socketTimeout))); + } + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + // Start all server connections + connectServers(self, servers); +} + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +ReplSet.prototype.destroy = function(options) { + options = options || {}; + // Transition state + stateTransition(this, DESTROYED); + // Clear out any monitoring process + if(this.haTimeoutId) clearTimeout(this.haTimeoutId); + // Destroy the replicaset + this.s.replicaSetState.destroy(options); + + // Destroy all connecting servers + this.s.connectingServers.forEach(function(x) { + x.destroy(options); + }); + + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); +} + +/** + * Unref all connections belong to this server + * @method + */ +ReplSet.prototype.unref = function() { + // Transition state + stateTransition(this, DISCONNECTED); + + this.s.replicaSetState.allServers().forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + return this.s.replicaSetState.primary + ? this.s.replicaSetState.primary.lastIsMaster() : this.ismaster; +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + var servers = this.s.replicaSetState.allServers(); + var connections = []; + for(var i = 0; i < servers.length; i++) { + connections = connections.concat(servers[i].connections()); + } + + return connections; +} + +/** + * Figure out if the server is connected + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + + // If we are authenticating signal not connected + // To avoid interleaving of operations + if(this.authenticating) return false; + + // If we specified a read preference check if we are connected to something + // than can satisfy this + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondary)) { + return this.s.replicaSetState.hasSecondary(); + } + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primary)) { + return this.s.replicaSetState.hasPrimary(); + } + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if(this.s.secondaryOnlyConnectionAllowed + && this.s.replicaSetState.hasSecondary()) { + return true; + } + + return this.s.replicaSetState.hasPrimary(); +} + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.state == DESTROYED; +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +ReplSet.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + + // Pick the right server baspickServerd on readPreference + var server = this.s.replicaSetState.pickServer(options.readPreference); + if(this.s.debug) this.emit('pickedServer', options.readPreference, server); + return server; +} + +/** + * Get all connected servers + * @method + * @return {Server[]} + */ +ReplSet.prototype.getServers = function() { + return this.s.replicaSetState.allServers(); +} + +// +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + // Ensure we have no options + options = options || {}; + + // No server returned we had an error + if(self.s.replicaSetState.primary == null) { + return callback(new MongoError("no primary server found")); + } + + // Execute the command + self.s.replicaSetState.primary[op](ns, ops, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // Execute write operation + executeWriteOperation(this, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // Execute write operation + executeWriteOperation(this, 'update', ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // Execute write operation + executeWriteOperation(this, 'remove', ns, ops, options, callback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Establish readPreference + var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; + + // If the readPreference is primary and we have no primary, store it + if(readPreference.preference == 'primary' && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if(readPreference.preference == 'secondary' && !this.s.replicaSetState.hasSecondary() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if(readPreference.preference != 'primary' && !this.s.replicaSetState.hasSecondary() && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // Pick a server + var server = this.s.replicaSetState.pickServer(readPreference); + // We received an error, return it + if(!(server instanceof Server)) return callback(server); + // Emit debug event + if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + + // No server returned we had an error + if(server == null) { + return callback(new MongoError(f("no server found that matches the provided readPreference %s", readPreference))); + } + + // Execute the command + server.command(ns, cmd, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.authProviders[mechanism] == null && mechanism != 'default') { + return callback(new MongoError(f("auth provider %s does not exist", mechanism))); + } + + // Are we already authenticating, throw + if(this.authenticating) { + return callback(new MongoError('authentication or logout allready in process')); + } + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler != null) { + return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); + } + + // Set to authenticating + this.authenticating = true; + // All errors + var errors = []; + + // Get all the servers + var servers = this.s.replicaSetState.allServers(); + // No servers return + if(servers.length == 0) { + this.authenticating = false; + callback(null, true); + } + + // Authenticate + function auth(server) { + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err) { + count = count - 1; + // Save all the errors + if(err) errors.push({name: server.name, err: err}); + // We are done + if(count == 0) { + // Auth is done + self.authenticating = false; + + // Return the auth error + if(errors.length) return callback(MongoError.create({ + message: 'authentication fail', errors: errors + }), false); + + // Successfully authenticated session + callback(null, self); + } + }]); + + if(!server.lastIsMaster().arbiterOnly) { + // Execute the auth only against non arbiter servers + server.auth.apply(server, finalArguments); + } else { + // If we are authenticating against an arbiter just ignore it + finalArguments.pop()(null); + } + } + + // Get total count + var count = servers.length; + // Authenticate against all servers + while(servers.length > 0) { + auth(servers.shift()); + } +} + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.logout = function(dbName, callback) { + var self = this; + // Are we authenticating or logging out, throw + if(this.authenticating) { + throw new MongoError('authentication or logout allready in process'); + } + + // Ensure no new members are processed while logging out + this.authenticating = true; + + // Remove from all auth providers (avoid any reaplication of the auth details) + var providers = Object.keys(this.authProviders); + for(var i = 0; i < providers.length; i++) { + this.authProviders[providers[i]].logout(dbName); + } + + // Now logout all the servers + var servers = this.s.replicaSetState.allServers(); + var count = servers.length; + if(count == 0) return callback(); + var errors = []; + + function logoutServer(_server, cb) { + _server.logout(dbName, function(err) { + if(err) errors.push({name: _server.name, err: err}); + cb(); + }); + } + + // Execute logout on all server instances + for(i = 0; i < servers.length; i++) { + logoutServer(servers[i], function() { + count = count - 1; + + if(count == 0) { + // Do not block new operations + self.authenticating = false; + // If we have one or more errors + if(errors.length) return callback(MongoError.create({ + message: f('logout failed against db %s', dbName), errors: errors + }), false); + + // No errors + callback(); + } + }) + } +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * A replset reconnect event, used to verify that the topology reconnected + * + * @event ReplSet#reconnect + * @type {ReplSet} + */ + +/** + * A replset fullsetup event, used to signal that all topology members have been contacted. + * + * @event ReplSet#fullsetup + * @type {ReplSet} + */ + +/** + * A replset all event, used to signal that all topology members have been contacted. + * + * @event ReplSet#all + * @type {ReplSet} + */ + +/** + * A replset failed event, used to signal that initial replset connection failed. + * + * @event ReplSet#failed + * @type {ReplSet} + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event ReplSet#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event ReplSet#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event ReplSet#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event ReplSet#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event ReplSet#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event ReplSet#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event ReplSet#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event ReplSet#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event ReplSet#serverHeartbeatSucceeded + * @type {object} + */ + +module.exports = ReplSet; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js new file mode 100644 index 00000000..4fb1d4d7 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js @@ -0,0 +1,972 @@ +"use strict" + +var inherits = require('util').inherits, + f = require('util').format, + EventEmitter = require('events').EventEmitter, + Logger = require('../connection/logger'), + ReadPreference = require('./read_preference'), + MongoError = require('../error'); + +var TopologyType = { + 'Single': 'Single', 'ReplicaSetNoPrimary': 'ReplicaSetNoPrimary', + 'ReplicaSetWithPrimary': 'ReplicaSetWithPrimary', 'Sharded': 'Sharded', + 'Unknown': 'Unknown' +}; + +var ServerType = { + 'Standalone': 'Standalone', 'Mongos': 'Mongos', 'PossiblePrimary': 'PossiblePrimary', + 'RSPrimary': 'RSPrimary', 'RSSecondary': 'RSSecondary', 'RSArbiter': 'RSArbiter', + 'RSOther': 'RSOther', 'RSGhost': 'RSGhost', 'Unknown': 'Unknown' +}; + +var ReplSetState = function(options) { + options = options || {}; + // Add event listener + EventEmitter.call(this); + // Topology state + this.topologyType = TopologyType.ReplicaSetNoPrimary; + this.setName = options.setName; + + // Server set + this.set = {}; + + // Unpacked options + this.id = options.id; + this.setName = options.setName; + + // Replicaset logger + this.logger = options.logger || Logger('ReplSet', options); + + // Server selection index + this.index = 0; + // Acceptable latency + this.acceptableLatency = options.acceptableLatency || 15; + + // heartbeatFrequencyMS + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + + // Server side + this.primary = null; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + // Current unknown hosts + this.unknownServers = []; + // In set status + this.set = {}; + // Status + this.maxElectionId = null; + this.maxSetVersion = 0; + // Description of the Replicaset + this.replicasetDescription = { + "topologyType": "Unknown", "servers": [] + }; +} + +inherits(ReplSetState, EventEmitter); + +ReplSetState.prototype.hasPrimaryAndSecondary = function() { + return this.primary != null && this.secondaries.length > 0; +} + +ReplSetState.prototype.hasPrimary = function() { + return this.primary != null; +} + +ReplSetState.prototype.hasSecondary = function() { + return this.secondaries.length > 0; +} + +ReplSetState.prototype.allServers = function(options) { + options = options || {}; + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + if(!options.ignoreArbiters) servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + return servers; +} + +ReplSetState.prototype.destroy = function(options) { + // Destroy all sockets + if(this.primary) this.primary.destroy(options); + this.secondaries.forEach(function(x) { x.destroy(options); }); + this.arbiters.forEach(function(x) { x.destroy(options); }); + this.passives.forEach(function(x) { x.destroy(options); }); + this.ghosts.forEach(function(x) { x.destroy(options); }); + // Clear out the complete state + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + this.unknownServers = []; + this.set = {}; +} + +ReplSetState.prototype.remove = function(server, options) { + options = options || {}; + + // Only remove if the current server is not connected + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + + // Check if it's active and this is just a failed connection attempt + for(var i = 0; i < servers.length; i++) { + if(!options.force && servers[i].equals(server) && servers[i].isConnected && servers[i].isConnected()) { + return; + } + } + + // If we have it in the set remove it + if(this.set[server.name.toLowerCase()]) { + this.set[server.name.toLowerCase()].type = ServerType.Unknown; + this.set[server.name.toLowerCase()].electionId = null; + this.set[server.name.toLowerCase()].setName = null; + this.set[server.name.toLowerCase()].setVersion = null; + } + + // Remove type + var removeType = null; + + // Remove from any lists + if(this.primary && this.primary.equals(server)) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + removeType = 'primary'; + } + + // Remove from any other server lists + removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; + removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; + removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; + removeFrom(server, this.ghosts); + removeFrom(server, this.unknownServers); + + // Do we have a removeType + if(removeType) { + this.emit('left', removeType, server); + } +} + +ReplSetState.prototype.update = function(server) { + var self = this; + // Get the current ismaster + var ismaster = server.lastIsMaster(); + + // + // Add any hosts + // + if(ismaster) { + // Join all the possible new hosts + var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; + hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); + hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); + + // Add all hosts as unknownServers + for(var i = 0; i < hosts.length; i++) { + // Add to the list of unknown server + if(this.unknownServers.indexOf(hosts[i]) == -1 + && (!this.set[hosts[i].toLowerCase()] || this.set[hosts[i].toLowerCase()].type == ServerType.Unknown)) { + this.unknownServers.push(hosts[i]); + } + + if(!this.set[hosts[i].toLowerCase()]) { + this.set[hosts[i].toLowerCase()] = { + type: ServerType.Unknown, + electionId: null, + setName: null, + setVersion: null + } + } + } + } + + // + // Unknown server + // + if(!ismaster && !inList(ismaster, server, this.unknownServers)) { + self.set[server.name.toLowerCase()] = { + type: ServerType.Unknown, setVersion: null, electionId: null, setName: null + } + // Update set information about the server instance + self.set[server.name.toLowerCase()].type = ServerType.Unknown; + self.set[server.name.toLowerCase()].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[server.name.toLowerCase()].setName = ismaster ? ismaster.setName : ismaster; + self.set[server.name.toLowerCase()].setVersion = ismaster ? ismaster.setVersion : ismaster; + + if(self.unknownServers.indexOf(server.name) == -1) { + self.unknownServers.push(server.name); + } + + // Set the topology + return false; + } + + // + // Is this a mongos + // + if(ismaster && ismaster.msg == 'isdbgrid') { + return false; + } + + // A RSOther instance + if((ismaster.setName && ismaster.hidden) + || (ismaster.setName && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly && !ismaster.passive)) { + self.set[server.name.toLowerCase()] = { + type: ServerType.RSOther, setVersion: null, + electionId: null, setName: ismaster.setName + } + // Set the topology + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; + if(ismaster.setName) this.setName = ismaster.setName; + return false; + } + + // A RSGhost instance + if(ismaster.isreplicaset) { + self.set[server.name.toLowerCase()] = { + type: ServerType.RSGhost, setVersion: null, + electionId: null, setName: null + } + + // Set the topology + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; + if(ismaster.setName) this.setName = ismaster.setName; + + // Set the topology + return false; + } + + // + // Standalone server, destroy and return + // + if(ismaster && ismaster.ismaster && !ismaster.setName) { + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; + this.remove(server, {force:true}); + return false; + } + + // + // Server in maintanance mode + // + if(ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + this.remove(server, {force:true}); + return false; + } + + // + // If the .me field does not match the passed in server + // + if(ismaster.me && ismaster.me != server.name) { + if(this.logger.isWarn()) { + this.logger.warn(f('the seedlist server was removed due to its address %s not matching its ismaster.me address %s', server.name, ismaster.me)); + } + + // Delete from the set + delete this.set[server.name.toLowerCase()]; + + // Set the type of topology we have + if(this.primary && !this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + // + // We have a potential primary + // + if(!this.primary && ismaster.primary) { + this.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setName: null, + electionId: null, + setVersion: null, + } + } + + return false; + } + + // + // Primary handling + // + if(!this.primary && ismaster.ismaster && ismaster.setName) { + var ismasterElectionId = server.lastIsMaster().electionId; + if(this.setName && this.setName != ismaster.setName) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return new MongoError(f('setName from ismaster does not match provided connection setName [%s] != [%s]', ismaster.setName, this.setName)); + } + + if(!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if(this.maxElectionId && ismasterElectionId) { + var result = compareObjectIds(this.maxElectionId, ismasterElectionId); + // Get the electionIds + var ismasterSetVersion = server.lastIsMaster().setVersion; + + // if(result == 1 || result == 0) { + if(result == 1) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } else if(result == 0 && ismasterSetVersion) { + if(ismasterSetVersion < this.maxSetVersion) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + } + + this.maxSetVersion = ismasterSetVersion; + this.maxElectionId = ismasterElectionId; + } + + // Hande normalization of server names + var normalizedHosts = ismaster.hosts.map(function(x) { return x.toLowerCase() }); + var locationIndex = normalizedHosts.indexOf(server.name.toLowerCase()); + + // Validate that the server exists in the host list + if(locationIndex != -1) { + self.primary = server; + self.set[server.name.toLowerCase()] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + } + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if(ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + emitTopologyDescriptionChanged(self); + return true; + } else if(ismaster.ismaster && ismaster.setName) { + // Get the electionIds + var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; + var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; + var currentSetName = self.set[self.primary.name.toLowerCase()].setName; + ismasterElectionId = server.lastIsMaster().electionId; + ismasterSetVersion = server.lastIsMaster().setVersion; + var ismasterSetName = server.lastIsMaster().setName; + + // Is it the same server instance + if(this.primary.equals(server) + && currentSetName == ismasterSetName) { + return false; + } + + // If we do not have the same rs name + if(currentSetName && currentSetName != ismasterSetName) { + if(!this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // Check if we need to replace the server + if(currentElectionId && ismasterElectionId) { + result = compareObjectIds(currentElectionId, ismasterElectionId); + + if(result == 1) { + return false; + } else if(result == 0 && (currentSetVersion > ismasterSetVersion)) { + return false; + } + } else if(!currentElectionId && ismasterElectionId + && ismasterSetVersion) { + if(ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + if(!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if(this.maxElectionId && ismasterElectionId) { + result = compareObjectIds(this.maxElectionId, ismasterElectionId); + + if(result == 1) { + return false; + } else if(result == 0 && currentSetVersion && ismasterSetVersion) { + if(ismasterSetVersion < this.maxSetVersion) { + return false; + } + } else { + if(ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + this.maxElectionId = ismasterElectionId; + this.maxSetVersion = ismasterSetVersion; + } else { + this.maxSetVersion = ismasterSetVersion; + } + + // Modify the entry to unknown + self.set[self.primary.name.toLowerCase()] = { + type: ServerType.Unknown, setVersion: null, + electionId: null, setName: null + } + + // Signal primary left + self.emit('left', 'primary', this.primary); + // Destroy the instance + self.primary.destroy(); + // Set the new instance + self.primary = server; + // Set the set information + self.set[server.name.toLowerCase()] = { + type: ServerType.RSPrimary, setVersion: ismaster.setVersion, + electionId: ismaster.electionId, setName: ismaster.setName + } + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if(ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // A possible instance + if(!this.primary && ismaster.primary) { + self.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, setVersion: null, + electionId: null, setName: null + } + } + + // + // Secondary handling + // + if(ismaster.secondary && ismaster.setName + && !inList(ismaster, server, this.secondaries) + && this.setName && this.setName == ismaster.setName) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); + // Set the topology + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; + if(ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if(this.primary && this.primary.name == server.name) { + server.destroy(); + this.primary = null; + self.emit('left', 'primary', server); + } + + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Arbiter handling + // + if(ismaster.arbiterOnly && ismaster.setName + && !inList(ismaster, server, this.arbiters) + && this.setName && this.setName == ismaster.setName) { + addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); + // Set the topology + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; + if(ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + self.emit('joined', 'arbiter', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Passive handling + // + if(ismaster.passive && ismaster.setName + && !inList(ismaster, server, this.passives) + && this.setName && this.setName == ismaster.setName) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); + // Set the topology + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; + if(ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if(this.primary && this.primary.name == server.name) { + server.destroy(); + this.primary = null; + self.emit('left', 'primary', server); + } + + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Remove the primary + // + if(this.set[server.name.toLowerCase()] && this.set[server.name.toLowerCase()].type == ServerType.RSPrimary) { + self.emit('left', 'primary', this.primary); + this.primary.destroy(); + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; + return false; +} + +/** + * Recalculate single server max staleness + * @method + */ +ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { + // Locate the max secondary lastwrite + var max = 0; + // Go over all secondaries + for(var i = 0; i < this.secondaries.length; i++) { + max = Math.max(max, this.secondaries[i].lastWriteDate); + } + + // Perform this servers staleness calculation + if(server.ismaster.maxWireVersion >= 5 + && server.ismaster.secondary + && this.hasPrimary()) { + server.staleness = (server.lastUpdateTime - server.lastWriteDate) + - (this.primary.lastUpdateTime - this.primary.lastWriteDate) + + haInterval; + } else if(server.ismaster.maxWireVersion >= 5 + && server.ismaster.secondary){ + server.staleness = max - server.lastWriteDate + haInterval; + } +} + +/** + * Recalculate all the stalness values for secodaries + * @method + */ +ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { + for(var i = 0; i < this.secondaries.length; i++) { + this.updateServerMaxStaleness(this.secondaries[i], haInterval); + } +} + +/** + * Pick a server by the passed in ReadPreference + * @method + * @param {ReadPreference} readPreference The ReadPreference instance to use + */ +ReplSetState.prototype.pickServer = function(readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // maxStalenessSeconds is not allowed with a primary read + if(readPreference.preference == 'primary' && readPreference.maxStalenessSeconds != null) { + return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); + } + + // Check if we have any non compatible servers for maxStalenessSeconds + var allservers = this.primary ? [this.primary] : []; + allservers = allservers.concat(this.secondaries); + + // Does any of the servers not support the right wire protocol version + // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out + if(readPreference.maxStalenessSeconds != null) { + for(var i = 0; i < allservers.length; i++) { + if(allservers[i].ismaster.maxWireVersion < 5) { + return new MongoError('maxStalenessSeconds not supported by at least one of the replicaset members'); + } + } + } + + // Do we have the nearest readPreference + if(readPreference.preference == 'nearest' && readPreference.maxStalenessSeconds == null) { + return pickNearest(this, readPreference); + } else if(readPreference.preference == 'nearest' && readPreference.maxStalenessSeconds != null) { + return pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Get all the secondaries + var secondaries = this.secondaries; + + // Check if we can satisfy and of the basic read Preferences + if(readPreference.equals(ReadPreference.secondary) + && secondaries.length == 0) { + return new MongoError("no secondary server available"); + } + + if(readPreference.equals(ReadPreference.secondaryPreferred) + && secondaries.length == 0 + && this.primary == null) { + return new MongoError("no secondary or primary server available"); + } + + if(readPreference.equals(ReadPreference.primary) + && this.primary == null) { + return new MongoError("no primary server available"); + } + + // Secondary preferred or just secondaries + if(readPreference.equals(ReadPreference.secondaryPreferred) + || readPreference.equals(ReadPreference.secondary)) { + + if(secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + // Pick nearest of any other servers available + var server = pickNearest(this, readPreference); + // No server in the window return primary + if(server) { + return server; + } + } else if(secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + // Pick nearest of any other servers available + server = pickNearestMaxStalenessSeconds(this, readPreference); + // No server in the window return primary + if(server) { + return server; + } + } + + if(readPreference.equals(ReadPreference.secondaryPreferred)){ + return this.primary; + } + + return null; + } + + // Primary preferred + if(readPreference.equals(ReadPreference.primaryPreferred)) { + server = null; + + // We prefer the primary if it's available + if(this.primary) { + return this.primary; + } + + // Pick a secondary + if(secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + server = pickNearest(this, readPreference); + } else if(secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + server = pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Did we find a server + if(server) return server; + } + + // Return the primary + return this.primary; +} + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; + + // Iterate over the tags + for(var j = 0; j < tagsArray.length; j++) { + var tags = tagsArray[j]; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) { + found = false; + } + } + + // Add to candidate list + if(found) { + filteredServers.push(servers[i]); + } + } + } + + // Returned filtered servers + return filteredServers; +} + +function pickNearestMaxStalenessSeconds(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + var heartbeatFrequencyMS = self.heartbeatFrequencyMS; + + // Get the maxStalenessMS + var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; + + // Check if the maxStalenessMS > 90 seconds + if(maxStalenessMS < 90 * 1000) { + return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); + } + + // Add primary to list if not a secondary read preference + if(self.primary && readPreference.preference != 'secondary') { + servers.push(self.primary); + } + + // Add all the secondaries + for(var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + // var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; + + // Filter by latency + servers = servers.filter(function(s) { + return s.staleness <= maxStalenessMS; + }); + + // Sort by time + servers.sort(function(a, b) { + // return a.time > b.time; + return a.lastIsMasterMS > b.lastIsMasterMS + }); + + // No servers, default to primary + if(servers.length == 0) { + return null + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function pickNearest(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Add primary to list if not a secondary read preference + if(self.primary && readPreference.preference != 'secondary') { + servers.push(self.primary); + } + + // Add all the secondaries + for(var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Sort by time + servers.sort(function(a, b) { + // return a.time > b.time; + return a.lastIsMasterMS > b.lastIsMasterMS + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; + + // Filter by latency + servers = servers.filter(function(s) { + return s.lastIsMasterMS <= lowest + self.acceptableLatency; + }); + + // No servers, default to primary + if(servers.length == 0) { + return null + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function inList(ismaster, server, list) { + for(var i = 0; i < list.length; i++) { + if(list[i].name == server.name) return true; + } + + return false; +} + +function addToList(self, type, ismaster, server, list) { + // Update set information about the server instance + self.set[server.name.toLowerCase()].type = type; + self.set[server.name.toLowerCase()].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[server.name.toLowerCase()].setName = ismaster ? ismaster.setName : ismaster; + self.set[server.name.toLowerCase()].setVersion = ismaster ? ismaster.setVersion : ismaster; + // Add to the list + list.push(server); +} + +function compareObjectIds(id1, id2) { + var a = new Buffer(id1.toHexString(), 'hex'); + var b = new Buffer(id2.toHexString(), 'hex'); + + if(a === b) { + return 0; + } + + if(typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +function removeFrom(server, list) { + for(var i = 0; i < list.length; i++) { + if(list[i].equals && list[i].equals(server)) { + list.splice(i, 1); + return true; + } else if(typeof list[i] == 'string' && list[i] == server.name) { + list.splice(i, 1); + return true; + } + } + + return false; +} + +function emitTopologyDescriptionChanged(self) { + if(self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + var setName = self.setName; + + if(self.hasPrimaryAndSecondary()) { + topology = 'ReplicaSetWithPrimary'; + } else if(!self.hasPrimary() && self.hasSecondary()) { + topology = 'ReplicaSetNoPrimary'; + } + + // Generate description + var description = { + topologyType: topology, + setName: setName, + servers: [] + } + + // Add the primary to the list + if(self.hasPrimary()) { + var desc = self.primary.getDescription(); + desc.type = 'RSPrimary'; + description.servers.push(desc); + } + + // Add all the secondaries + description.servers = description.servers.concat(self.secondaries.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + })); + + // Add all the arbiters + description.servers = description.servers.concat(self.arbiters.map(function(x) { + var description = x.getDescription(); + description.type = 'RSArbiter'; + return description; + })); + + // Add all the passives + description.servers = description.servers.concat(self.passives.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + })); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.replicasetDescription, + newDescription: description, + diff: diff(self.replicasetDescription, description) + }; + + // Emit the topologyDescription change + self.emit('topologyDescriptionChanged', result); + + // Set the new description + self.replicasetDescription = description; + } +} + +function diff(previous, current) { + // Difference document + var diff = { + servers: [] + } + + // Previous entry + if(!previous) { + previous = { servers: [] }; + } + + // Got through all the servers + for(var i = 0; i < previous.servers.length; i++) { + var prevServer = previous.servers[i]; + + // Go through all current servers + for(var j = 0; j < current.servers.length; j++) { + var currServer = current.servers[j]; + + // Matching server + if(prevServer.address === currServer.address) { + // We had a change in state + if(prevServer.type != currServer.type) { + diff.servers.push({ + address: prevServer.address, + from: prevServer.type, + to: currServer.type + }); + } + } + } + } + + // Return difference + return diff; +} + +module.exports = ReplSetState; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js new file mode 100644 index 00000000..fac82b5c --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js @@ -0,0 +1,855 @@ +"use strict" + +var inherits = require('util').inherits, + require_optional = require('require_optional'), + f = require('util').format, + EventEmitter = require('events').EventEmitter, + ReadPreference = require('./read_preference'), + Logger = require('../connection/logger'), + debugOptions = require('../connection/utils').debugOptions, + retrieveBSON = require('../connection/utils').retrieveBSON, + Pool = require('../connection/pool'), + Query = require('../connection/commands').Query, + MongoError = require('../error'), + PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support'), + TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'), + ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'), + BasicCursor = require('../cursor'), + sdam = require('./shared'), + assign = require('./shared').assign, + createClientInfo = require('./shared').createClientInfo; + +// Used for filtering out fields for loggin +var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' + , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout', 'checkServerIdentity' + , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs', 'promoteValues' + , 'promoteBuffers', 'servername']; + +// Server instance id +var id = 0; +var serverAccounting = false; +var servers = {}; +var BSON = retrieveBSON(); + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) + * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#reconnectFailed + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + * @fires Server#topologyOpening + * @fires Server#topologyClosed + * @fires Server#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Server = function(options) { + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Server instance id + this.id = id++; + + // Internal state + this.s = { + // Options + options: options, + // Logger + logger: Logger('Server', options), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // BSON instance + bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, + BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, + BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]), + // Pool + pool: null, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Monitor thread (keeps the connection alive) + monitoring: typeof options.monitoring == 'boolean' ? options.monitoring : true, + // Is the server in a topology + inTopology: typeof options.inTopology == 'boolean' ? options.inTopology : false, + // Monitoring timeout + monitoringInterval: typeof options.monitoringInterval == 'number' + ? options.monitoringInterval + : 5000, + // Topology id + topologyId: -1 + } + + // Curent ismaster + this.ismaster = null; + // Current ping time + this.lastIsMasterMS = -1; + // The monitoringProcessId + this.monitoringProcessId = null; + // Initial connection + this.initalConnect = true; + // Wire protocol handler, default to oldest known protocol handler + // this gets changed when the first ismaster is called. + this.wireProtocolHandler = new PreTwoSixWireProtocolSupport(); + // Default type + this._type = 'server'; + // Set the client info + this.clientInfo = createClientInfo(options); + + // Max Stalleness values + // last time we updated the ismaster state + this.lastUpdateTime = 0; + // Last write time + this.lastWriteDate = 0; + // Stalleness + this.staleness = 0; +} + +inherits(Server, EventEmitter); + +Object.defineProperty(Server.prototype, 'type', { + enumerable:true, get: function() { return this._type; } +}); + +Object.defineProperty(Server.prototype, 'parserType', { + enumerable:true, get: function() { + return BSON.native ? "c++" : "js"; + } +}); + +Server.enableServerAccounting = function() { + serverAccounting = true; + servers = {}; +} + +Server.disableServerAccounting = function() { + serverAccounting = false; +} + +Server.servers = function() { + return servers; +} + +Object.defineProperty(Server.prototype, 'name', { + enumerable:true, + get: function() { return this.s.options.host + ":" + this.s.options.port; } +}); + +function configureWireProtocolHandler(self, ismaster) { + // 3.2 wire protocol handler + if(ismaster.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); + } + + // 2.6 wire protocol handler + if(ismaster.maxWireVersion >= 2) { + return new TwoSixWireProtocolSupport(); + } + + // 2.4 or earlier wire protocol handler + return new PreTwoSixWireProtocolSupport(); +} + +function disconnectHandler(self, type, ns, cmd, options, callback) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.s.pool.isConnected() && self.s.disconnectHandler != null && !options.monitoring) { + self.s.disconnectHandler.add(type, ns, cmd, options, callback); + return true; + } + + // If we have no connection error + if(!self.s.pool.isConnected()) { + callback(MongoError.create(f("no connection available to server %s", self.name))); + return true; + } +} + +function monitoringProcess(self) { + return function() { + // Pool was destroyed do not continue process + if(self.s.pool.isDestroyed()) return; + // Emit monitoring Process event + self.emit('monitoring', self); + // Perform ismaster call + // Query options + var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; + // Create a query instance + var query = new Query(self.s.bson, 'admin.$cmd', {ismaster:true}, queryOptions); + // Get start time + var start = new Date().getTime(); + // Execute the ismaster query + self.s.pool.write(query, { + socketTimeout: self.s.options.connectionTimeout || 2000, + }, function(err, result) { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + if(self.s.pool.isDestroyed()) return; + // Update the ismaster view if we have a result + if(result) { + self.ismaster = result.result; + } + // Re-schedule the monitoring process + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + }); + } +} + +var eventHandler = function(self, event) { + return function(err) { + // Log information of received information if in info mode + if(self.s.logger.isInfo()) { + var object = err instanceof MongoError ? JSON.stringify(err) : {} + self.s.logger.info(f('server %s fired event %s out with message %s' + , self.name, event, object)); + } + + // Handle connect event + if(event == 'connect') { + // Issue an ismaster command at connect + // Query options + var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; + // Create a query instance + var query = new Query(self.s.bson, 'admin.$cmd', {ismaster:true, client: self.clientInfo}, queryOptions); + // Get start time + var start = new Date().getTime(); + // Execute the ismaster query + self.s.pool.write(query, { + socketTimeout: self.s.options.connectionTimeout || 2000, + }, function(err, result) { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + if(err) { + self.destroy(); + if(self.listeners('error').length > 0) self.emit('error', err); + return; + } + + // Ensure no error emitted after initial connect when reconnecting + self.initalConnect = false; + // Save the ismaster + self.ismaster = result.result; + + // It's a proxy change the type so + // the wireprotocol will send $readPreference + if(self.ismaster.msg == 'isdbgrid') { + self._type = 'mongos'; + } + // Add the correct wire protocol handler + self.wireProtocolHandler = configureWireProtocolHandler(self, self.ismaster); + // Have we defined self monitoring + if(self.s.monitoring) { + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + + // Emit server description changed if something listening + sdam.emitServerDescriptionChanged(self, { + address: self.name, arbiters: [], hosts: [], passives: [], type: !self.s.inTopology ? 'Standalone' : sdam.getTopologyType(self) + }); + + // Emit topology description changed if something listening + sdam.emitTopologyDescriptionChanged(self, { + topologyType: 'Single', servers: [{address: self.name, arbiters: [], hosts: [], passives: [], type: 'Standalone'}] + }); + + // Log the ismaster if available + if(self.s.logger.isInfo()) { + self.s.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster))); + } + + // Emit connect + self.emit('connect', self); + }); + } else if(event == 'error' || event == 'parseError' + || event == 'close' || event == 'timeout' || event == 'reconnect' + || event == 'attemptReconnect' || 'reconnectFailed') { + // Remove server instance from accounting + if(serverAccounting && ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) != -1) { + // Emit toplogy opening event if not in topology + if(!self.s.inTopology) { + self.emit('topologyOpening', { topologyId: self.id }); + } + + delete servers[self.id]; + } + + // Reconnect failed return error + if(event == 'reconnectFailed') { + self.emit('reconnectFailed', err); + // Emit error if any listeners + if(self.listeners('error').length > 0) { + self.emit('error', err); + } + // Terminate + return; + } + + // On first connect fail + if(self.s.pool.state == 'disconnected' && self.initalConnect && ['close', 'timeout', 'error', 'parseError'].indexOf(event) != -1) { + self.initalConnect = false; + return self.emit('error', new MongoError(f('failed to connect to server [%s] on first connect', self.name))); + } + + // Reconnect event, emit the server + if(event == 'reconnect') { + return self.emit(event, self); + } + + // Emit the event + self.emit(event, err); + } + } +} + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +Server.prototype.connect = function(options) { + var self = this; + options = options || {}; + + // Set the connections + if(serverAccounting) servers[this.id] = this; + + // Do not allow connect to be called on anything that's not disconnected + if(self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { + throw MongoError.create(f('server instance in invalid state %s', self.s.state)); + } + + // Create a pool + self.s.pool = new Pool(assign(self.s.options, options, {bson: this.s.bson})); + + // Set up listeners + self.s.pool.on('close', eventHandler(self, 'close')); + self.s.pool.on('error', eventHandler(self, 'error')); + self.s.pool.on('timeout', eventHandler(self, 'timeout')); + self.s.pool.on('parseError', eventHandler(self, 'parseError')); + self.s.pool.on('connect', eventHandler(self, 'connect')); + self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); + self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); + + // Emit toplogy opening event if not in topology + if(!self.s.inTopology) { + this.emit('topologyOpening', { topologyId: self.id }); + } + + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.s.topologyId != -1 ? self.s.topologyId : self.id, + address: self.name + }); + + // Connect with optional auth settings + if(options.auth) { + self.s.pool.connect.apply(self.s.pool, options.auth); + } else { + self.s.pool.connect(); + } +} + +/** + * Get the server description + * @method + * @return {object} +*/ +Server.prototype.getDescription = function() { + var ismaster = this.ismaster || {}; + var description = { + type: sdam.getTopologyType(this), + address: this.name, + }; + + // Add fields if available + if(ismaster.hosts) description.hosts = ismaster.hosts; + if(ismaster.arbiters) description.arbiters = ismaster.arbiters; + if(ismaster.passives) description.passives = ismaster.passives; + if(ismaster.setName) description.setName = ismaster.setName; + return description; +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.ismaster; +} + +/** + * Unref all connections belong to this server + * @method + */ +Server.prototype.unref = function() { + this.s.pool.unref(); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + if(!this.s.pool) return false; + return this.s.pool.isConnected(); +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + if(!this.s.pool) return false; + return this.s.pool.isDestroyed(); +} + +function basicWriteValidations(self) { + if(!self.s.pool) return MongoError.create('server instance is not connected'); + if(self.s.pool.isDestroyed()) return MongoError.create('server instance pool was destroyed'); +} + +function basicReadValidations(self, options) { + basicWriteValidations(self, options); + + if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error("readPreference must be an instance of ReadPreference"); + } +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + var result = basicReadValidations(self, options); + if(result) return callback(result); + + // Debug log + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ + ns: ns, cmd: cmd, options: debugOptions(debugFields, options) + }), self.name)); + + // If we are not connected or have a disconnectHandler specified + if(disconnectHandler(self, 'command', ns, cmd, options, callback)) return; + + // Check if we have collation support + if(this.ismaster && this.ismaster.maxWireVersion < 5 && cmd.collation) { + return callback(new MongoError(f('server %s does not support collation', this.name))); + } + + // Query options + var queryOptions = { + numberToSkip: 0, + numberToReturn: -1, + checkKeys: typeof options.checkKeys == 'boolean' ? options.checkKeys: false, + serializeFunctions: typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false, + ignoreUndefined: typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false + }; + + // Create a query instance + var query = new Query(self.s.bson, ns, cmd, queryOptions); + // Set slave OK of the query + query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false; + + // Write options + var writeOptions = { + raw: typeof options.raw == 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues == 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers == 'boolean' ? options.promoteBuffers : false, + command: true, + monitoring: typeof options.monitoring == 'boolean' ? options.monitoring : false, + fullResult: typeof options.fullResult == 'boolean' ? options.fullResult : false, + requestId: query.requestId, + socketTimeout: typeof options.socketTimeout == 'number' ? options.socketTimeout : null, + }; + + // Write the operation to the pool + self.s.pool.write(query, writeOptions, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + var result = basicWriteValidations(self, options); + if(result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if(disconnectHandler(self, 'insert', ns, ops, options, callback)) return; + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + + // Execute write + return self.wireProtocolHandler.insert(self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + var result = basicWriteValidations(self, options); + if(result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if(disconnectHandler(self, 'update', ns, ops, options, callback)) return; + + // Check if we have collation support + if(this.ismaster && this.ismaster.maxWireVersion < 5 && options.collation) { + return callback(new MongoError(f('server %s does not support collation', this.name))); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.wireProtocolHandler.update(self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}, options = options || {}; + var result = basicWriteValidations(self, options); + if(result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if(disconnectHandler(self, 'remove', ns, ops, options, callback)) return; + + // Check if we have collation support + if(this.ismaster && this.ismaster.maxWireVersion < 5 && options.collation) { + return callback(new MongoError(f('server %s does not support collation', this.name))); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.wireProtocolHandler.remove(self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback); +} + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.cursor = function(ns, cmd, cursorOptions) { + var s = this.s; + cursorOptions = cursorOptions || {}; + // Set up final cursor type + var FinalCursor = cursorOptions.cursorFactory || s.Cursor; + // Return the cursor + return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); +} + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +Server.prototype.logout = function(dbName, callback) { + this.s.pool.logout(dbName, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(mechanism, db) { + var self = this; + + // If we have the default mechanism we pick mechanism based on the wire + // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr + if(mechanism == 'default' && self.ismaster && self.ismaster.maxWireVersion >= 3) { + mechanism = 'scram-sha-1'; + } else if(mechanism == 'default') { + mechanism = 'mongocr'; + } + + // Slice all the arguments off + var args = Array.prototype.slice.call(arguments, 0); + // Set the mechanism + args[0] = mechanism; + // Get the callback + var callback = args[args.length - 1]; + + // If we are not connected or have a disconnectHandler specified + if(disconnectHandler(self, 'auth', db, args, {}, callback)) { + return; + } + + // Do not authenticate if we are an arbiter + if(this.lastIsMaster() && this.lastIsMaster().arbiterOnly) { + return callback(null, true); + } + + // Apply the arguments to the pool + self.s.pool.auth.apply(self.s.pool, args); +} + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if(typeof server == 'string') return this.name == server; + if(server.name) return this.name == server.name; + return false; +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.allConnections(); +} + +/** + * Get server + * @method + * @return {Server} + */ +Server.prototype.getServer = function() { + return this; +} + +/** + * Get connection + * @method + * @return {Connection} + */ +Server.prototype.getConnection = function() { + return this.s.pool.get(); +} + +var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; + +/** + * Destroy the server connection + * @method + * @param {boolean} [options.emitClose=false] Emit close event on destroy + * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy + * @param {boolean} [options.force=false] Force destroy the pool + */ +Server.prototype.destroy = function(options) { + options = options || {}; + var self = this; + + // Set the connections + if(serverAccounting) delete servers[this.id]; + + // Destroy the monitoring process if any + if(this.monitoringProcessId) { + clearTimeout(this.monitoringProcessId); + } + + // Emit close event + if(options.emitClose) { + self.emit('close', self); + } + + // Emit destroy event + if(options.emitDestroy) { + self.emit('destroy', self); + } + + // Remove all listeners + listeners.forEach(function(event) { + self.s.pool.removeAllListeners(event); + }); + + // Emit opening server event + if(self.listeners('serverClosed').length > 0) self.emit('serverClosed', { + topologyId: self.s.topologyId != -1 ? self.s.topologyId : self.id, address: self.name + }); + + // Emit toplogy opening event if not in topology + if(self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { + self.emit('topologyClosed', { topologyId: self.id }); + } + + if(self.s.logger.isDebug()) { + self.s.logger.debug(f('destroy called on server %s', self.name)); + } + + // Destroy the pool + this.s.pool.destroy(options.force); +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * A server reconnect event, used to verify that the server topology has reconnected + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * A server opening SDAM monitoring event + * + * @event Server#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Server#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Server#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Server#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Server#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Server#topologyDescriptionChanged + * @type {object} + */ + +/** + * Server reconnect failed + * + * @event Server#reconnectFailed + * @type {Error} + */ + +/** + * Server connection pool closed + * + * @event Server#close + * @type {object} + */ + +/** + * Server connection pool caused an error + * + * @event Server#error + * @type {Error} + */ + +/** + * Server destroyed was called + * + * @event Server#destroy + * @type {Server} + */ + +module.exports = Server; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/shared.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/shared.js new file mode 100644 index 00000000..8cc019c1 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/shared.js @@ -0,0 +1,225 @@ +"use strict" + +var os = require('os'), + f = require('util').format; + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if(self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +// Get package.json variable +var driverVersion = require(__dirname + '/../../package.json').version; +var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); +var type = os.type(); +var name = process.platform; +var architecture = process.arch; +var release = os.release(); + +function createClientInfo(options) { + // Build default client information + var clientInfo = options.clientInfo ? clone(options.clientInfo) : { + driver: { + name: "nodejs-core", + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + } + } + + // Is platform specified + if(clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') == -1) { + clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); + } else if(!clientInfo.platform){ + clientInfo.platform = nodejsversion; + } + + // Do we have an application specific string + if(options.appname) { + // Cut at 128 bytes + var buffer = new Buffer(options.appname); + // Return the truncated appname + var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; + // Add to the clientInfo + clientInfo.application = { name: appname }; + } + + return clientInfo; +} + +function clone(object) { + return JSON.parse(JSON.stringify(object)); +} + +var getPreviousDescription = function(self) { + if(!self.s.serverDescription) { + self.s.serverDescription = { + address: self.name, + arbiters: [], hosts: [], passives: [], type: 'Unknown' + } + } + + return self.s.serverDescription; +} + +var emitServerDescriptionChanged = function(self, description) { + if(self.listeners('serverDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('serverDescriptionChanged', { + topologyId: self.s.topologyId != -1 ? self.s.topologyId : self.id, address: self.name, + previousDescription: getPreviousDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +} + +var getPreviousTopologyDescription = function(self) { + if(!self.s.topologyDescription) { + self.s.topologyDescription = { + topologyType: 'Unknown', + servers: [{ + address: self.name, arbiters: [], hosts: [], passives: [], type: 'Unknown' + }] + } + } + + return self.s.topologyDescription; +} + +var emitTopologyDescriptionChanged = function(self, description) { + if(self.listeners('topologyDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('topologyDescriptionChanged', { + topologyId: self.s.topologyId != -1 ? self.s.topologyId : self.id, address: self.name, + previousDescription: getPreviousTopologyDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +} + +var changedIsMaster = function(self, currentIsmaster, ismaster) { + var currentType = getTopologyType(self, currentIsmaster); + var newType = getTopologyType(self, ismaster); + if(newType != currentType) return true; + return false; +} + +var getTopologyType = function(self, ismaster) { + if(!ismaster) { + ismaster = self.ismaster; + } + + if(!ismaster) return 'Unknown'; + if(ismaster.ismaster && !ismaster.hosts) return 'Standalone'; + if(ismaster.ismaster && ismaster.msg == 'isdbgrid') return 'Mongos'; + if(ismaster.ismaster) return 'RSPrimary'; + if(ismaster.secondary) return 'RSSecondary'; + if(ismaster.arbiterOnly) return 'RSArbiter'; + return 'Unknown'; +} + +var inquireServerState = function(self) { + return function(callback) { + if(self.s.state == 'destroyed') return; + // Record response time + var start = new Date().getTime(); + + // emitSDAMEvent + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); + + // Attempt to execute ismaster command + self.command('admin.$cmd', { ismaster:true }, { monitoring:true }, function(err, r) { + if(!err) { + // Legacy event sender + self.emit('ismaster', r, self); + + // Calculate latencyMS + var latencyMS = new Date().getTime() - start; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: self.name }); + + // Did the server change + if(changedIsMaster(self, self.s.ismaster, r.result)) { + // Emit server description changed if something listening + emitServerDescriptionChanged(self, { + address: self.name, arbiters: [], hosts: [], passives: [], type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) + }); + } + + // Updat ismaster view + self.s.ismaster = r.result; + + // Set server response time + self.s.isMasterLatencyMS = latencyMS; + } else { + emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: self.name }); + } + + // Peforming an ismaster monitoring callback operation + if(typeof callback == 'function') { + return callback(err, r); + } + + // Perform another sweep + self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); + }); + }; +} + +// Object.assign method or polyfille +var assign = Object.assign ? Object.assign : function assign(target) { + if (target === undefined || target === null) { + throw new TypeError('Cannot convert first argument to object'); + } + + var to = Object(target); + for (var i = 1; i < arguments.length; i++) { + var nextSource = arguments[i]; + if (nextSource === undefined || nextSource === null) { + continue; + } + + var keysArray = Object.keys(Object(nextSource)); + for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { + var nextKey = keysArray[nextIndex]; + var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); + if (desc !== undefined && desc.enumerable) { + to[nextKey] = nextSource[nextKey]; + } + } + } + return to; +} + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +module.exports.inquireServerState = inquireServerState +module.exports.getTopologyType = getTopologyType; +module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; +module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; +module.exports.cloneOptions = cloneOptions; +module.exports.assign = assign; +module.exports.createClientInfo = createClientInfo; +module.exports.clone = clone; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js new file mode 100644 index 00000000..f59f3507 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js @@ -0,0 +1,567 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , copy = require('../connection/utils').copy + , retrieveBSON = require('../connection/utils').retrieveBSON + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , f = require('util').format + , CommandResult = require('../connection/command_result') + , MongoError = require('../error') + , getReadPreference = require('./shared').getReadPreference; + +var BSON = retrieveBSON(), + Long = BSON.Long; + +// Write concern fields +var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; + +var WireProtocol = function() {} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // If we have more than a 1000 ops fails + if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('insert', Insert, ismaster, ns, bson, pool, ops, options, callback); + } + + return executeOrdered('insert', Insert, ismaster, ns, bson, pool, ops, options, callback); +} + +WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('update', Update, ismaster, ns, bson, pool, ops, options, callback); + } + + return executeOrdered('update', Update, ismaster, ns, bson, pool, ops, options, callback); +} + +WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('remove', Remove, ismaster, ns, bson, pool, ops, options, callback); + } + + return executeOrdered('remove', Remove, ismaster, ns, bson, pool, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(pool && pool.isConnected()) { + pool.write(killCursor, { + immediateRelease:true, noResponse: true + }); + } + + // Callback + if(typeof callback == 'function') callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, result) { + if(err) return callback(err); + // Get the raw message + var r = result.message; + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor does not exist, was killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null, null, r.connection); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Check if we need to promote longs + if(typeof cursorState.promoteLongs == 'boolean') { + queryCallback.promoteLongs = cursorState.promoteLongs; + } + + if(typeof cursorState.promoteValues == 'boolean') { + queryCallback.promoteValues = cursorState.promoteValues; + } + + if(typeof cursorState.promoteBuffers == 'boolean') { + queryCallback.promoteBuffers = cursorState.promoteBuffers; + } + + // Write out the getMore command + connection.write(getMore, queryCallback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + return; + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + // Ensure we have at least some options + options = options || {}; + // Get the readPreference + var readPreference = getReadPreference(cmd, options); + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + if(cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + // Set empty options object + options = options || {} + // Get the readPreference + var readPreference = getReadPreference(cmd, options); + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +var hasWriteConcern = function(writeConcern) { + if(writeConcern.w + || writeConcern.wtimeout + || writeConcern.j == true + || writeConcern.fsync == true + || Object.keys(writeConcern).length == 0) { + return true; + } + return false; +} + +var cloneWriteConcern = function(writeConcern) { + var wc = {}; + if(writeConcern.w != null) wc.w = writeConcern.w; + if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; + if(writeConcern.j != null) wc.j = writeConcern.j; + if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; + return wc; +} + +// +// Aggregate up all the results +// +var aggregateWriteOperationResults = function(opType, ops, results, connection) { + var finalResult = { ok: 1, n: 0 } + if(opType == 'update') { + finalResult.nModified = 0; + } + + // Map all the results coming back + for(var i = 0; i < results.length; i++) { + var result = results[i]; + var op = ops[i]; + + if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { + finalResult.upserted = []; + } + + // Push the upserted document to the list of upserted values + if(result.upserted) { + finalResult.upserted.push({index: i, _id: result.upserted}); + } + + // We have an upsert where we passed in a _id + if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { + finalResult.upserted.push({index: i, _id: op.q._id}); + } else if(result.updatedExisting == true) { + finalResult.nModified += result.n; + } + + // We have an insert command + if(result.ok == 1 && opType == 'insert' && result.err == null) { + finalResult.n = finalResult.n + 1; + } + + // We have a command error + if(result != null && result.ok == 0 || result.err || result.errmsg) { + if(result.ok == 0) finalResult.ok = 0; + finalResult.code = result.code; + finalResult.errmsg = result.errmsg || result.err || result.errMsg; + + // Check if we have a write error + if(result.code == 11000 + || result.code == 11001 + || result.code == 12582 + || result.code == 16544 + || result.code == 16538 + || result.code == 16542 + || result.code == 14 + || result.code == 13511) { + if(finalResult.writeErrors == null) finalResult.writeErrors = []; + finalResult.writeErrors.push({ + index: i + , code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + }); + } else { + finalResult.writeConcernError = { + code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + } + } + } else if(typeof result.n == 'number') { + finalResult.n += result.n; + } else { + finalResult.n += 1; + } + + // Result as expected + if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; + } + + // Return finalResult aggregated results + return new CommandResult(finalResult, connection); +} + +// +// Execute all inserts in an ordered manner +// +var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, ops, options, callback) { + var _ops = ops.slice(0); + // Collect all the getLastErrors + var getLastErrors = []; + // Execute an operation + var executeOp = function(list, _callback) { + // No more items in the list + if(list.length == 0) { + return process.nextTick(function() { + _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + }); + } + + // Get the first operation + var doc = list.shift(); + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + + // Get the db name + var db = ns.split('.').shift(); + + try { + // Add binary message to list of commands to execute + var commands = [op]; + + // Add getLastOrdered + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var i = 0; i < writeConcernFields.length; i++) { + if(writeConcern[writeConcernFields[i]] != null) { + getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; + } + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Add getLastError command to list of ops to execute + commands.push(getLastErrorOp); + + // getLastError callback + var getLastErrorCallback = function(err, result) { + if(err) return callback(err); + // Get the document + var doc = result.result; + // Save the getLastError document + getLastErrors.push(doc); + + // If we have an error terminate + if(doc.ok == 0 || doc.err || doc.errmsg) { + return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection)); + } + + // Execute the next op in the list + executeOp(list, callback); + } + + // Write both commands out at the same time + pool.write(commands, getLastErrorCallback); + } catch(err) { + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors.push({ ok: 1, errmsg: typeof err == 'string' ? err : err.message, code: 14 }); + // Return due to an error + process.nextTick(function() { + _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + }); + } + } + + // Execute the operations + executeOp(_ops, callback); +} + +var executeUnordered = function(opType, command, ismaster, ns, bson, pool, ops, options, callback) { + // Total operations to write + var totalOps = ops.length; + // Collect all the getLastErrors + var getLastErrors = []; + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + // Driver level error + var error; + + // Execute all the operations + for(var i = 0; i < ops.length; i++) { + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); + // Get db name + var db = ns.split('.').shift(); + + try { + // Add binary message to list of commands to execute + var commands = [op]; + + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var j = 0; j < writeConcernFields.length; j++) { + if(writeConcern[writeConcernFields[j]] != null) + getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Add getLastError command to list of ops to execute + commands.push(getLastErrorOp); + + // Give the result from getLastError the right index + var callbackOp = function(_index) { + return function(err, result) { + if(err) error = err; + // Update the number of operations executed + totalOps = totalOps - 1; + // Save the getLastError document + if(!err) getLastErrors[_index] = result.result; + // Check if we are done + if(totalOps == 0) { + process.nextTick(function() { + if(error) return callback(error); + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection)); + }); + } + } + } + + // Write both commands out at the same time + pool.write(commands, callbackOp(i)); + } else { + pool.write(commands, {immediateRelease:true, noResponse:true}); + } + } catch(err) { + // Update the number of operations executed + totalOps = totalOps - 1; + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors[i] = { ok: 1, errmsg: typeof err == 'string' ? err : err.message, code: 14 }; + // Check if we are done + if(totalOps == 0) { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + } + } + } + + // Empty w:0 return + if(writeConcern + && writeConcern.w == 0 && callback) { + callback(null, new CommandResult({ok:1}, null)); + } +} + +module.exports = WireProtocol; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js new file mode 100644 index 00000000..33cc6d07 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js @@ -0,0 +1,330 @@ +"use strict"; + +var copy = require('../connection/utils').copy + , retrieveBSON = require('../connection/utils').retrieveBSON + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , f = require('util').format + , MongoError = require('../error') + , getReadPreference = require('./shared').getReadPreference; + +var BSON = retrieveBSON(), + Long = BSON.Long; + +var WireProtocol = function() {} + +// +// Execute a write operation +var executeWrite = function(pool, bson, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + options = options || {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern; + + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + // Did we specify a write concern + if(writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + // Do we have bypassDocumentValidation set, then enable it on the write command + if(typeof options.bypassDocumentValidation == 'boolean') { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Options object + var opts = { command: true }; + var queryOptions = { checkKeys : false, numberToSkip: 0, numberToReturn: 1 }; + if(type == 'insert') queryOptions.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; + // Do not serialize the undefined fields + if(options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; + + try { + // Create write command + var cmd = new Query(bson, f("%s.$cmd", d), writeCommand, queryOptions); + // Execute command + pool.write(cmd, opts, callback); + } catch(err) { + callback(err); + } +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(pool && pool.isConnected()) { + pool.write(killCursor, { + immediateRelease:true, noResponse: true + }); + } + + // Callback + if(typeof callback == 'function') callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, result) { + if(err) return callback(err); + // Get the raw message + var r = result.message; + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor does not exist, was killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null, null, r.connection); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Check if we need to promote longs + if(typeof cursorState.promoteLongs == 'boolean') { + queryCallback.promoteLongs = cursorState.promoteLongs; + } + + if(typeof cursorState.promoteValues == 'boolean') { + queryCallback.promoteValues = cursorState.promoteValues; + } + + if(typeof cursorState.promoteBuffers == 'boolean') { + queryCallback.promoteBuffers = cursorState.promoteBuffers; + } + + // Write out the getMore command + connection.write(getMore, queryCallback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + return; + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + // Ensure we have at least some options + options = options || {}; + // Get the readPreference + var readPreference = getReadPreference(cmd, options); + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + if(cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') { + query.tailable = cmd.tailable; + } + + if(typeof cmd.oplogReplay == 'boolean') { + query.oplogReplay = cmd.oplogReplay; + } + + if(typeof cmd.noCursorTimeout == 'boolean') { + query.noCursorTimeout = cmd.noCursorTimeout; + } + + if(typeof cmd.awaitData == 'boolean') { + query.awaitData = cmd.awaitData; + } + + if(typeof cmd.partial == 'boolean') { + query.partial = cmd.partial; + } + + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + // Set empty options object + options = options || {} + // Get the readPreference + var readPreference = getReadPreference(cmd, options); + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +module.exports = WireProtocol; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js new file mode 100644 index 00000000..9f1410ee --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js @@ -0,0 +1,533 @@ +"use strict"; + +var Query = require('../connection/commands').Query + , retrieveBSON = require('../connection/utils').retrieveBSON + , f = require('util').format + , MongoError = require('../error') + , getReadPreference = require('./shared').getReadPreference; + +var BSON = retrieveBSON(), + Long = BSON.Long; + +var WireProtocol = function(legacyWireProtocol) { + this.legacyWireProtocol = legacyWireProtocol; +} + +// +// Execute a write operation +var executeWrite = function(pool, bson, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + options = options || {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern; + + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + // Did we specify a write concern + if(writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + // If we have collation passed in + if(options.collation) { + for(var i = 0; i < writeCommand[opsField].length; i++) { + if(!writeCommand[opsField][i].collation) { + writeCommand[opsField][i].collation = options.collation; + } + } + } + + // Do we have bypassDocumentValidation set, then enable it on the write command + if(typeof options.bypassDocumentValidation == 'boolean') { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Options object + var opts = { command: true }; + var queryOptions = { checkKeys : false, numberToSkip: 0, numberToReturn: 1 }; + if(type == 'insert') queryOptions.checkKeys = true; + + // Ensure we support serialization of functions + if(options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; + // Do not serialize the undefined fields + if(options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; + + try { + // Create write command + var cmd = new Query(bson, f("%s.$cmd", d), writeCommand, queryOptions); + // Execute command + pool.write(cmd, opts, callback); + } catch(err) { + callback(err); + } +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) { + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + // Create getMore command + var killcursorCmd = { + killCursors: parts.join('.'), + cursors: [cursorId] + } + + // Build Query object + var query = new Query(bson, commandns, killcursorCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = true; + + // Kill cursor callback + var killCursorCallback = function(err, result) { + if(err) { + if(typeof callback != 'function') return; + return callback(err); + } + + // Result + var r = result.message; + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + if(typeof callback != 'function') return; + return callback(new MongoError("cursor killed or timed out"), null); + } + + if(!Array.isArray(r.documents) || r.documents.length == 0) { + if(typeof callback != 'function') return; + return callback(new MongoError(f('invalid killCursors result returned for cursor id %s', cursorId))); + } + + // Return the result + if(typeof callback == 'function') { + callback(null, r.documents[0]); + } + } + + // Execute the kill cursor command + if(pool && pool.isConnected()) { + pool.write(query, { + command: true + }, killCursorCallback); + } +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) { + options = options || {}; + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Create getMore command + var getMoreCmd = { + getMore: cursorState.cursorId, + collection: parts.join('.'), + batchSize: Math.abs(batchSize) + } + + if(cursorState.cmd.tailable + && typeof cursorState.cmd.maxAwaitTimeMS == 'number') { + getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; + } + + // Build Query object + var query = new Query(bson, commandns, getMoreCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = true; + + // Query callback + var queryCallback = function(err, result) { + if(err) return callback(err); + // Get the raw message + var r = result.message; + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Raw, return all the extracted documents + if(raw) { + cursorState.documents = r.documents; + cursorState.cursorId = r.cursorId; + return callback(null, r.documents); + } + + // We have an error detected + if(r.documents[0].ok == 0) { + return callback(MongoError.create(r.documents[0])); + } + + // Ensure we have a Long valid cursor id + var cursorId = typeof r.documents[0].cursor.id == 'number' + ? Long.fromNumber(r.documents[0].cursor.id) + : r.documents[0].cursor.id; + + // Set all the values + cursorState.documents = r.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + // Return the result + callback(null, r.documents[0], r.connection); + } + + // Query options + var queryOptions = { command: true }; + + // If we have a raw query decorate the function + if(raw) { + queryOptions.raw = raw; + } + + // Add the result field needed + queryOptions.documentsReturnedIn = 'nextBatch'; + + // Check if we need to promote longs + if(typeof cursorState.promoteLongs == 'boolean') { + queryOptions.promoteLongs = cursorState.promoteLongs; + } + + if(typeof cursorState.promoteValues == 'boolean') { + queryCallback.promoteValues = cursorState.promoteValues; + } + + if(typeof cursorState.promoteBuffers == 'boolean') { + queryCallback.promoteBuffers = cursorState.promoteBuffers; + } + + // Write out the getMore command + connection.write(query, queryOptions, queryCallback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + // Create the find command + var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) + // Mark the cmd as virtual + cmd.virtual = false; + // Signal the documents are in the firstBatch value + query.documentsReturnedIn = 'firstBatch'; + // Return the query + return query; + } else if(cursorState.cursorId != null) { + return; + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// // Command +// { +// find: ns +// , query: <object> +// , limit: <n> +// , fields: <object> +// , skip: <n> +// , hint: <string> +// , explain: <boolean> +// , snapshot: <boolean> +// , batchSize: <n> +// , returnKey: <boolean> +// , maxScan: <n> +// , min: <n> +// , max: <n> +// , showDiskLoc: <boolean> +// , comment: <string> +// , maxTimeMS: <n> +// , raw: <boolean> +// , readPreference: <ReadPreference> +// , tailable: <boolean> +// , oplogReplay: <boolean> +// , noCursorTimeout: <boolean> +// , awaitdata: <boolean> +// , exhaust: <boolean> +// , partial: <boolean> +// } + +// FIND/GETMORE SPEC +// { +// “find”: <string>, +// “filter”: { ... }, +// “sort”: { ... }, +// “projection”: { ... }, +// “hint”: { ... }, +// “skip”: <int>, +// “limit”: <int>, +// “batchSize”: <int>, +// “singleBatch”: <bool>, +// “comment”: <string>, +// “maxScan”: <int>, +// “maxTimeMS”: <int>, +// “max”: { ... }, +// “min”: { ... }, +// “returnKey”: <bool>, +// “showRecordId”: <bool>, +// “snapshot”: <bool>, +// “tailable”: <bool>, +// “oplogReplay”: <bool>, +// “noCursorTimeout”: <bool>, +// “awaitData”: <bool>, +// “partial”: <bool>, +// “$readPreference”: { ... } +// } + +// +// Execute a find command +var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { + // Ensure we have at least some options + options = options || {}; + // Get the readPreference + var readPreference = getReadPreference(cmd, options); + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Build actual find command + var findCmd = { + find: parts.join('.') + }; + + // I we provided a filter + if(cmd.query) { + // Check if the user is passing in the $query parameter + if(cmd.query['$query']) { + findCmd.filter = cmd.query['$query']; + } else { + findCmd.filter = cmd.query; + } + } + + // Sort value + var sortValue = cmd.sort; + + // Handle issue of sort being an Array + if(Array.isArray(sortValue)) { + var sortObject = {}; + + if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { + var sortDirection = sortValue[1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[0]] = sortDirection; + } else { + for(var i = 0; i < sortValue.length; i++) { + sortDirection = sortValue[i][1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + } + + // Add sort to command + if(cmd.sort) findCmd.sort = sortValue; + // Add a projection to the command + if(cmd.fields) findCmd.projection = cmd.fields; + // Add a hint to the command + if(cmd.hint) findCmd.hint = cmd.hint; + // Add a skip + if(cmd.skip) findCmd.skip = cmd.skip; + // Add a limit + if(cmd.limit) findCmd.limit = cmd.limit; + // Add a batchSize + if(typeof cmd.batchSize == 'number') findCmd.batchSize = Math.abs(cmd.batchSize); + + // Check if we wish to have a singleBatch + if(cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + // If we have comment set + if(cmd.comment) findCmd.comment = cmd.comment; + + // If we have maxScan + if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; + + // If we have maxTimeMS set + if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + + // If we have min + if(cmd.min) findCmd.min = cmd.min; + + // If we have max + if(cmd.max) findCmd.max = cmd.max; + + // If we have returnKey set + if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; + + // If we have showDiskLoc set + if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; + + // If we have snapshot set + if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; + + // If we have tailable set + if(cmd.tailable) findCmd.tailable = cmd.tailable; + + // If we have oplogReplay set + if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + + // If we have noCursorTimeout set + if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + + // If we have awaitData set + if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + + // If we have partial set + if(cmd.partial) findCmd.partial = cmd.partial; + + // If we have collation passed in + if(cmd.collation) findCmd.collation = cmd.collation; + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if(cmd.explain) { + findCmd = { + explain: findCmd + } + } + + // Did we provide a readConcern + if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + findCmd = { + '$query': findCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, commandns, findCmd, { + numberToSkip: 0, numberToReturn: 1 + , checkKeys: false, returnFieldSelector: null + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + // Set empty options object + options = options || {} + // Get the readPreference + var readPreference = getReadPreference(cmd, options); + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +module.exports = WireProtocol; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js new file mode 100644 index 00000000..1b5d74b8 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js @@ -0,0 +1,357 @@ +"use strict"; + +var MongoError = require('../error'); + +// Wire command operation ids +var OP_UPDATE = 2001; +var OP_INSERT = 2002; +var OP_DELETE = 2006; + +var Insert = function(requestId, ismaster, bson, ns, documents, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new MongoError("namespace cannot contain a null character"); + } + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.documents = documents; + this.ismaster = ismaster; + + // Ensure empty options + options = options || {}; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; + // Set flags + this.flags = this.continueOnError ? 1 : 0; +} + +// To Binary +Insert.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(this.ns) + 1 // namespace + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize all the documents + for(var i = 0; i < this.documents.length; i++) { + var buffer = this.bson.serialize(this.documents[i], { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined, + }); + + // Document is larger than maxBsonObjectSize, terminate serialization + if(buffer.length > this.ismaster.maxBsonObjectSize) { + throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); + } + + // Add to total length of wire protocol message + totalLength = totalLength + buffer.length; + // Add to buffer + buffers.push(buffer); + } + + // Command is larger than maxMessageSizeBytes terminate serialization + if(totalLength > this.ismaster.maxMessageSizeBytes) { + throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); + } + + // Add all the metadata + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_INSERT >> 24) & 0xff; + header[index + 2] = (OP_INSERT >> 16) & 0xff; + header[index + 1] = (OP_INSERT >> 8) & 0xff; + header[index] = (OP_INSERT) & 0xff; + index = index + 4; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Return the buffers + return buffers; +} + +var Update = function(requestId, ismaster, bson, ns, update, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; + this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; + this.q = update[0].q; + this.u = update[0].u; + + // Create flag value + this.flags = this.upsert ? 1 : 0; + this.flags = this.multi ? this.flags | 2 : this.flags; +} + +// To Binary +Update.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined, + }); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Serialize the update + var update = this.bson.serialize(this.u, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined, + }); + buffers.push(update); + totalLength = totalLength + update.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_UPDATE >> 24) & 0xff; + header[index + 2] = (OP_UPDATE >> 16) & 0xff; + header[index + 1] = (OP_UPDATE >> 8) & 0xff; + header[index] = (OP_UPDATE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +var Remove = function(requestId, ismaster, bson, ns, remove, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; + this.q = remove[0].q; + + // Create flag value + this.flags = this.limit == 1 ? 1 : 0; +} + +// To Binary +Remove.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined, + }); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_DELETE >> 24) & 0xff; + header[index + 2] = (OP_DELETE >> 16) & 0xff; + header[index + 1] = (OP_DELETE >> 8) & 0xff; + header[index] = (OP_DELETE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write ZERO + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +module.exports = { + Insert: Insert + , Update: Update + , Remove: Remove +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/shared.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/shared.js new file mode 100644 index 00000000..25bd3946 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/shared.js @@ -0,0 +1,27 @@ +"use strict" + +var ReadPreference = require('../topologies/read_preference'), + MongoError = require('../error'); + +var getReadPreference = function(cmd, options) { + // Default to command version of the readPreference + var readPreference = cmd.readPreference || new ReadPreference('primary'); + // If we have an option readPreference override the command one + if(options.readPreference) { + readPreference = options.readPreference; + } + + if(typeof readPreference == 'string') { + readPreference = new ReadPreference(readPreference); + } + + if(!(readPreference instanceof ReadPreference)) { + throw new MongoError('readPreference must be a ReadPreference instance'); + } + + return readPreference; +} + +module.exports = { + getReadPreference: getReadPreference +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY.md new file mode 100644 index 00000000..1eb8116b --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY.md @@ -0,0 +1,191 @@ +1.0.2 2016-12-06 +---------------- +- Minor optimizations for ObjectID to use Buffer.from where available. + +1.0.1 2016-12-06 +---------------- +- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. + +1.0.0 2016-12-06 +---------------- +- Introduced new BSON API and documentation. + +0.5.7 2016-11-18 +----------------- +- NODE-848 BSON Regex flags must be alphabetically ordered. + +0.5.6 2016-10-19 +----------------- +- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. +- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). + +0.5.5 2016-09-15 +----------------- +- Added DBPointer up conversion to DBRef + +0.5.4 2016-08-23 +----------------- +- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. + +0.5.3 2016-07-11 +----------------- +- Throw error if ObjectId is not a string or a buffer. + +0.5.2 2016-07-11 +----------------- +- All values encoded big-endian style for ObjectId. + +0.5.1 2016-07-11 +----------------- +- Fixed encoding/decoding issue in ObjectId timestamp generation. +- Removed BinaryParser dependency from the serializer/deserializer. + +0.5.0 2016-07-05 +----------------- +- Added Decimal128 type and extended test suite to include entire bson corpus. + +0.4.23 2016-04-08 +----------------- +- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. +- Remove one package from dependency due to having been pulled from NPM. + +0.4.22 2016-03-04 +----------------- +- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). +- Fixed issue with undefined type on deserializing. + +0.4.21 2016-01-12 +----------------- +- Minor optimizations to avoid non needed object creation. + +0.4.20 2015-10-15 +----------------- +- Added bower file to repository. +- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) + +0.4.19 2015-10-15 +----------------- +- Remove all support for bson-ext. + +0.4.18 2015-10-15 +----------------- +- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 +- add option for deserializing binary into Buffer object #116 + +0.4.17 2015-10-15 +----------------- +- Validate regexp string for null bytes and throw if there is one. + +0.4.16 2015-10-07 +----------------- +- Fixed issue with return statement in Map.js. + +0.4.15 2015-10-06 +----------------- +- Exposed Map correctly via index.js file. + +0.4.14 2015-10-06 +----------------- +- Exposed Map correctly via bson.js file. + +0.4.13 2015-10-06 +----------------- +- Added ES6 Map type serialization as well as a polyfill for ES5. + +0.4.12 2015-09-18 +----------------- +- Made ignore undefined an optional parameter. + +0.4.11 2015-08-06 +----------------- +- Minor fix for invalid key checking. + +0.4.10 2015-08-06 +----------------- +- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. +- Some performance improvements by in lining code. + +0.4.9 2015-08-06 +---------------- +- Undefined fields are omitted from serialization in objects. + +0.4.8 2015-07-14 +---------------- +- Fixed size validation to ensure we can deserialize from dumped files. + +0.4.7 2015-06-26 +---------------- +- Added ability to instruct deserializer to return raw BSON buffers for named array fields. +- Minor deserialization optimization by moving inlined function out. + +0.4.6 2015-06-17 +---------------- +- Fixed serializeWithBufferAndIndex bug. + +0.4.5 2015-06-17 +---------------- +- Removed any references to the shared buffer to avoid non GC collectible bson instances. + +0.4.4 2015-06-17 +---------------- +- Fixed rethrowing of error when not RangeError. + +0.4.3 2015-06-17 +---------------- +- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. + +0.4.2 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.1 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.0 2015-06-16 +---------------- +- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. +- Removed bson-ext extension dependency for now. + +0.3.2 2015-03-27 +---------------- +- Removed node-gyp from install script in package.json. + +0.3.1 2015-03-27 +---------------- +- Return pure js version on native() call if failed to initialize. + +0.3.0 2015-03-26 +---------------- +- Pulled out all C++ code into bson-ext and made it an optional dependency. + +0.2.21 2015-03-21 +----------------- +- Updated Nan to 1.7.0 to support io.js and node 0.12.0 + +0.2.19 2015-02-16 +----------------- +- Updated Nan to 1.6.2 to support io.js and node 0.12.0 + +0.2.18 2015-01-20 +----------------- +- Updated Nan to 1.5.1 to support io.js + +0.2.16 2014-12-17 +----------------- +- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's + +0.2.12 2014-08-24 +----------------- +- Fixes for fortify review of c++ extension +- toBSON correctly allows returns of non objects + +0.2.3 2013-10-01 +---------------- +- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) +- Fixed issue where corrupt CString's could cause endless loop +- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) + +0.1.4 2012-09-25 +---------------- +- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE.md new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE.md @@ -0,0 +1,201 @@ + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md new file mode 100644 index 00000000..af25c3c0 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md @@ -0,0 +1,141 @@ +# BSON parser + +If you don't yet know what BSON actually is, read [the spec](http://bsonspec.org). + +The browser version of the BSON parser is compiled using webpack and the current +version is pre-compiled in the browser_build directory. To build a new version perform the following operation. + +``` +npm install +npm run build +``` + +A simple example of how to use BSON in the browser: + +```html +<script src="./browser_build/bson.js"></script> + +<script> + function start() { + // Get the Long type + var Long = BSON.Long; + // Create a bson parser instance + var bson = new BSON(); + + // Serialize document + var doc = { long: Long.fromNumber(100) } + + // Serialize a document + var data = bson.serialize(doc) + // De serialize it again + var doc_2 = bson.deserialize(data) + } +</script> +``` + +A simple example of how to use BSON in `node.js`: + +```js +// Get BSON parser class +var BSON = require('bson') +// Get the Long type +var Long = BSON.Long; +// Create a bson parser instance +var bson = new BSON(); + +// Serialize document +var doc = { long: Long.fromNumber(100) } + +// Serialize a document +var data = bson.serialize(doc) +console.log('data:', data) + +// Deserialize the resulting Buffer +var doc_2 = bson.deserialize(data) +console.log('doc_2:', doc_2) +``` + +## Installation + +`npm install bson` + +## API + +### BSON types + +For all BSON types documentation, please refer to the documentation for the mongodb driver. + +https://github.com/mongodb/node-mongodb-native + +### BSON serialization and deserialiation + +**`new BSON()`** - Creates a new BSON seralizer/deserializer you can use to serialize and deserialize BSON. + +#### BSON.serialize + +The BSON serialize method takes a javascript object and an optional options object and returns a Node.js Buffer. + + * BSON.serialize(object, options) + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript. functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.serializeWithBufferAndIndex + +The BSON serializeWithBufferAndIndex method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. + + * BSON.serializeWithBufferAndIndex(object, buffer, options) + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. + * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + +#### BSON.calculateObjectSize + +The BSON calculateObjectSize method takes a javascript object and an optional options object and returns the size of the BSON object. + + * BSON.calculateObjectSize(object, options) + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript. functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.deserialize + +The BSON deserialize method takes a node.js Buffer and an optional options object and returns a deserialized Javascript object. + + * BSON.deserialize(buffer, options) + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + +#### BSON.deserializeStream + +The BSON deserializeStream method takes a node.js Buffer, startIndex and allow more control over deserialization of a Buffer containing concatenated BSON documents. + + * BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options) + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/bower.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/bower.json new file mode 100644 index 00000000..b32140ea --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/bower.json @@ -0,0 +1,25 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "author": "Christian Amor Kvalheim <christkv@gmail.com>", + "main": "./browser_build/bson.js", + "license": "Apache-2.0", + "moduleType": [ + "globals", + "node" + ], + "ignore": [ + "**/.*", + "alternate_parsers", + "benchmarks", + "bower_components", + "node_modules", + "test", + "tools" + ] +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js new file mode 100644 index 00000000..6021fcad --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js @@ -0,0 +1,16734 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else { + var a = factory(); + for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; + } +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(1); + module.exports = __webpack_require__(298); + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {"use strict"; + + __webpack_require__(2); + + __webpack_require__(293); + + __webpack_require__(295); + + if (global._babelPolyfill) { + throw new Error("only one instance of babel-polyfill is allowed"); + } + global._babelPolyfill = true; + + var DEFINE_PROPERTY = "defineProperty"; + function define(O, key, value) { + O[key] || Object[DEFINE_PROPERTY](O, key, { + writable: true, + configurable: true, + value: value + }); + } + + define(String.prototype, "padLeft", "".padStart); + define(String.prototype, "padRight", "".padEnd); + + "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { + [][key] && define(Array, key, Function.call.bind([][key])); + }); + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(3); + __webpack_require__(52); + __webpack_require__(53); + __webpack_require__(54); + __webpack_require__(55); + __webpack_require__(57); + __webpack_require__(60); + __webpack_require__(61); + __webpack_require__(62); + __webpack_require__(63); + __webpack_require__(64); + __webpack_require__(65); + __webpack_require__(66); + __webpack_require__(67); + __webpack_require__(68); + __webpack_require__(70); + __webpack_require__(72); + __webpack_require__(74); + __webpack_require__(76); + __webpack_require__(79); + __webpack_require__(80); + __webpack_require__(81); + __webpack_require__(85); + __webpack_require__(87); + __webpack_require__(89); + __webpack_require__(92); + __webpack_require__(93); + __webpack_require__(94); + __webpack_require__(95); + __webpack_require__(97); + __webpack_require__(98); + __webpack_require__(99); + __webpack_require__(100); + __webpack_require__(101); + __webpack_require__(102); + __webpack_require__(103); + __webpack_require__(105); + __webpack_require__(106); + __webpack_require__(107); + __webpack_require__(109); + __webpack_require__(110); + __webpack_require__(111); + __webpack_require__(113); + __webpack_require__(114); + __webpack_require__(115); + __webpack_require__(116); + __webpack_require__(117); + __webpack_require__(118); + __webpack_require__(119); + __webpack_require__(120); + __webpack_require__(121); + __webpack_require__(122); + __webpack_require__(123); + __webpack_require__(124); + __webpack_require__(125); + __webpack_require__(126); + __webpack_require__(131); + __webpack_require__(132); + __webpack_require__(136); + __webpack_require__(137); + __webpack_require__(138); + __webpack_require__(139); + __webpack_require__(141); + __webpack_require__(142); + __webpack_require__(143); + __webpack_require__(144); + __webpack_require__(145); + __webpack_require__(146); + __webpack_require__(147); + __webpack_require__(148); + __webpack_require__(149); + __webpack_require__(150); + __webpack_require__(151); + __webpack_require__(152); + __webpack_require__(153); + __webpack_require__(154); + __webpack_require__(155); + __webpack_require__(156); + __webpack_require__(157); + __webpack_require__(159); + __webpack_require__(160); + __webpack_require__(166); + __webpack_require__(167); + __webpack_require__(169); + __webpack_require__(170); + __webpack_require__(171); + __webpack_require__(175); + __webpack_require__(176); + __webpack_require__(177); + __webpack_require__(178); + __webpack_require__(179); + __webpack_require__(181); + __webpack_require__(182); + __webpack_require__(183); + __webpack_require__(184); + __webpack_require__(187); + __webpack_require__(189); + __webpack_require__(190); + __webpack_require__(191); + __webpack_require__(193); + __webpack_require__(195); + __webpack_require__(197); + __webpack_require__(198); + __webpack_require__(199); + __webpack_require__(201); + __webpack_require__(202); + __webpack_require__(203); + __webpack_require__(204); + __webpack_require__(211); + __webpack_require__(214); + __webpack_require__(215); + __webpack_require__(217); + __webpack_require__(218); + __webpack_require__(221); + __webpack_require__(222); + __webpack_require__(224); + __webpack_require__(225); + __webpack_require__(226); + __webpack_require__(227); + __webpack_require__(228); + __webpack_require__(229); + __webpack_require__(230); + __webpack_require__(231); + __webpack_require__(232); + __webpack_require__(233); + __webpack_require__(234); + __webpack_require__(235); + __webpack_require__(236); + __webpack_require__(237); + __webpack_require__(238); + __webpack_require__(239); + __webpack_require__(240); + __webpack_require__(241); + __webpack_require__(242); + __webpack_require__(244); + __webpack_require__(245); + __webpack_require__(246); + __webpack_require__(247); + __webpack_require__(248); + __webpack_require__(249); + __webpack_require__(251); + __webpack_require__(252); + __webpack_require__(253); + __webpack_require__(254); + __webpack_require__(255); + __webpack_require__(256); + __webpack_require__(257); + __webpack_require__(258); + __webpack_require__(260); + __webpack_require__(261); + __webpack_require__(263); + __webpack_require__(264); + __webpack_require__(265); + __webpack_require__(266); + __webpack_require__(269); + __webpack_require__(270); + __webpack_require__(271); + __webpack_require__(272); + __webpack_require__(273); + __webpack_require__(274); + __webpack_require__(275); + __webpack_require__(276); + __webpack_require__(278); + __webpack_require__(279); + __webpack_require__(280); + __webpack_require__(281); + __webpack_require__(282); + __webpack_require__(283); + __webpack_require__(284); + __webpack_require__(285); + __webpack_require__(286); + __webpack_require__(287); + __webpack_require__(288); + __webpack_require__(291); + __webpack_require__(292); + module.exports = __webpack_require__(9); + +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // ECMAScript 6 symbols shim + var global = __webpack_require__(4) + , has = __webpack_require__(5) + , DESCRIPTORS = __webpack_require__(6) + , $export = __webpack_require__(8) + , redefine = __webpack_require__(18) + , META = __webpack_require__(22).KEY + , $fails = __webpack_require__(7) + , shared = __webpack_require__(23) + , setToStringTag = __webpack_require__(24) + , uid = __webpack_require__(19) + , wks = __webpack_require__(25) + , wksExt = __webpack_require__(26) + , wksDefine = __webpack_require__(27) + , keyOf = __webpack_require__(29) + , enumKeys = __webpack_require__(42) + , isArray = __webpack_require__(45) + , anObject = __webpack_require__(12) + , toIObject = __webpack_require__(32) + , toPrimitive = __webpack_require__(16) + , createDesc = __webpack_require__(17) + , _create = __webpack_require__(46) + , gOPNExt = __webpack_require__(49) + , $GOPD = __webpack_require__(51) + , $DP = __webpack_require__(11) + , $keys = __webpack_require__(30) + , gOPD = $GOPD.f + , dP = $DP.f + , gOPN = gOPNExt.f + , $Symbol = global.Symbol + , $JSON = global.JSON + , _stringify = $JSON && $JSON.stringify + , PROTOTYPE = 'prototype' + , HIDDEN = wks('_hidden') + , TO_PRIMITIVE = wks('toPrimitive') + , isEnum = {}.propertyIsEnumerable + , SymbolRegistry = shared('symbol-registry') + , AllSymbols = shared('symbols') + , OPSymbols = shared('op-symbols') + , ObjectProto = Object[PROTOTYPE] + , USE_NATIVE = typeof $Symbol == 'function' + , QObject = global.QObject; + // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 + var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + + // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 + var setSymbolDesc = DESCRIPTORS && $fails(function(){ + return _create(dP({}, 'a', { + get: function(){ return dP(this, 'a', {value: 7}).a; } + })).a != 7; + }) ? function(it, key, D){ + var protoDesc = gOPD(ObjectProto, key); + if(protoDesc)delete ObjectProto[key]; + dP(it, key, D); + if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); + } : dP; + + var wrap = function(tag){ + var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); + sym._k = tag; + return sym; + }; + + var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ + return typeof it == 'symbol'; + } : function(it){ + return it instanceof $Symbol; + }; + + var $defineProperty = function defineProperty(it, key, D){ + if(it === ObjectProto)$defineProperty(OPSymbols, key, D); + anObject(it); + key = toPrimitive(key, true); + anObject(D); + if(has(AllSymbols, key)){ + if(!D.enumerable){ + if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; + D = _create(D, {enumerable: createDesc(0, false)}); + } return setSymbolDesc(it, key, D); + } return dP(it, key, D); + }; + var $defineProperties = function defineProperties(it, P){ + anObject(it); + var keys = enumKeys(P = toIObject(P)) + , i = 0 + , l = keys.length + , key; + while(l > i)$defineProperty(it, key = keys[i++], P[key]); + return it; + }; + var $create = function create(it, P){ + return P === undefined ? _create(it) : $defineProperties(_create(it), P); + }; + var $propertyIsEnumerable = function propertyIsEnumerable(key){ + var E = isEnum.call(this, key = toPrimitive(key, true)); + if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; + return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; + }; + var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ + it = toIObject(it); + key = toPrimitive(key, true); + if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; + var D = gOPD(it, key); + if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; + return D; + }; + var $getOwnPropertyNames = function getOwnPropertyNames(it){ + var names = gOPN(toIObject(it)) + , result = [] + , i = 0 + , key; + while(names.length > i){ + if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); + } return result; + }; + var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ + var IS_OP = it === ObjectProto + , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) + , result = [] + , i = 0 + , key; + while(names.length > i){ + if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); + } return result; + }; + + // 19.4.1.1 Symbol([description]) + if(!USE_NATIVE){ + $Symbol = function Symbol(){ + if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); + var tag = uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function(value){ + if(this === ObjectProto)$set.call(OPSymbols, value); + if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, createDesc(1, value)); + }; + if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); + return wrap(tag); + }; + redefine($Symbol[PROTOTYPE], 'toString', function toString(){ + return this._k; + }); + + $GOPD.f = $getOwnPropertyDescriptor; + $DP.f = $defineProperty; + __webpack_require__(50).f = gOPNExt.f = $getOwnPropertyNames; + __webpack_require__(44).f = $propertyIsEnumerable; + __webpack_require__(43).f = $getOwnPropertySymbols; + + if(DESCRIPTORS && !__webpack_require__(28)){ + redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + wksExt.f = function(name){ + return wrap(wks(name)); + } + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); + + for(var symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' + ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); + + for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); + + $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function(key){ + return has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(key){ + if(isSymbol(key))return keyOf(SymbolRegistry, key); + throw TypeError(key + ' is not a symbol!'); + }, + useSetter: function(){ setter = true; }, + useSimple: function(){ setter = false; } + }); + + $export($export.S + $export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols + }); + + // 24.3.2 JSON.stringify(value [, replacer [, space]]) + $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; + })), 'JSON', { + stringify: function stringify(it){ + if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined + var args = [it] + , i = 1 + , replacer, $replacer; + while(arguments.length > i)args.push(arguments[i++]); + replacer = args[1]; + if(typeof replacer == 'function')$replacer = replacer; + if($replacer || !isArray(replacer))replacer = function(key, value){ + if($replacer)value = $replacer.call(this, key, value); + if(!isSymbol(value))return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } + }); + + // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) + $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); + // 19.4.3.5 Symbol.prototype[@@toStringTag] + setToStringTag($Symbol, 'Symbol'); + // 20.2.1.9 Math[@@toStringTag] + setToStringTag(Math, 'Math', true); + // 24.3.3 JSON[@@toStringTag] + setToStringTag(global.JSON, 'JSON', true); + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); + if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef + +/***/ }, +/* 5 */ +/***/ function(module, exports) { + + var hasOwnProperty = {}.hasOwnProperty; + module.exports = function(it, key){ + return hasOwnProperty.call(it, key); + }; + +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { + + // Thank's IE8 for his funny defineProperty + module.exports = !__webpack_require__(7)(function(){ + return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; + }); + +/***/ }, +/* 7 */ +/***/ function(module, exports) { + + module.exports = function(exec){ + try { + return !!exec(); + } catch(e){ + return true; + } + }; + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4) + , core = __webpack_require__(9) + , hide = __webpack_require__(10) + , redefine = __webpack_require__(18) + , ctx = __webpack_require__(20) + , PROTOTYPE = 'prototype'; + + var $export = function(type, name, source){ + var IS_FORCED = type & $export.F + , IS_GLOBAL = type & $export.G + , IS_STATIC = type & $export.S + , IS_PROTO = type & $export.P + , IS_BIND = type & $export.B + , target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE] + , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) + , expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}) + , key, own, out, exp; + if(IS_GLOBAL)source = name; + for(key in source){ + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + // export native or passed + out = (own ? target : source)[key]; + // bind timers to global for call from export context + exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // extend global + if(target)redefine(target, key, out, type & $export.U); + // export + if(exports[key] != out)hide(exports, key, exp); + if(IS_PROTO && expProto[key] != out)expProto[key] = out; + } + }; + global.core = core; + // type bitmap + $export.F = 1; // forced + $export.G = 2; // global + $export.S = 4; // static + $export.P = 8; // proto + $export.B = 16; // bind + $export.W = 32; // wrap + $export.U = 64; // safe + $export.R = 128; // real proto method for `library` + module.exports = $export; + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + var core = module.exports = {version: '2.4.0'}; + if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef + +/***/ }, +/* 10 */ +/***/ function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11) + , createDesc = __webpack_require__(17); + module.exports = __webpack_require__(6) ? function(object, key, value){ + return dP.f(object, key, createDesc(1, value)); + } : function(object, key, value){ + object[key] = value; + return object; + }; + +/***/ }, +/* 11 */ +/***/ function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12) + , IE8_DOM_DEFINE = __webpack_require__(14) + , toPrimitive = __webpack_require__(16) + , dP = Object.defineProperty; + + exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes){ + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if(IE8_DOM_DEFINE)try { + return dP(O, P, Attributes); + } catch(e){ /* empty */ } + if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); + if('value' in Attributes)O[P] = Attributes.value; + return O; + }; + +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function(it){ + if(!isObject(it))throw TypeError(it + ' is not an object!'); + return it; + }; + +/***/ }, +/* 13 */ +/***/ function(module, exports) { + + module.exports = function(it){ + return typeof it === 'object' ? it !== null : typeof it === 'function'; + }; + +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function(){ + return Object.defineProperty(__webpack_require__(15)('div'), 'a', {get: function(){ return 7; }}).a != 7; + }); + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13) + , document = __webpack_require__(4).document + // in old IE typeof document.createElement is 'object' + , is = isObject(document) && isObject(document.createElement); + module.exports = function(it){ + return is ? document.createElement(it) : {}; + }; + +/***/ }, +/* 16 */ +/***/ function(module, exports, __webpack_require__) { + + // 7.1.1 ToPrimitive(input [, PreferredType]) + var isObject = __webpack_require__(13); + // instead of the ES6 spec version, we didn't implement @@toPrimitive case + // and the second argument - flag - preferred type is a string + module.exports = function(it, S){ + if(!isObject(it))return it; + var fn, val; + if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; + if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; + if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; + throw TypeError("Can't convert object to primitive value"); + }; + +/***/ }, +/* 17 */ +/***/ function(module, exports) { + + module.exports = function(bitmap, value){ + return { + enumerable : !(bitmap & 1), + configurable: !(bitmap & 2), + writable : !(bitmap & 4), + value : value + }; + }; + +/***/ }, +/* 18 */ +/***/ function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4) + , hide = __webpack_require__(10) + , has = __webpack_require__(5) + , SRC = __webpack_require__(19)('src') + , TO_STRING = 'toString' + , $toString = Function[TO_STRING] + , TPL = ('' + $toString).split(TO_STRING); + + __webpack_require__(9).inspectSource = function(it){ + return $toString.call(it); + }; + + (module.exports = function(O, key, val, safe){ + var isFunction = typeof val == 'function'; + if(isFunction)has(val, 'name') || hide(val, 'name', key); + if(O[key] === val)return; + if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); + if(O === global){ + O[key] = val; + } else { + if(!safe){ + delete O[key]; + hide(O, key, val); + } else { + if(O[key])O[key] = val; + else hide(O, key, val); + } + } + // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative + })(Function.prototype, TO_STRING, function toString(){ + return typeof this == 'function' && this[SRC] || $toString.call(this); + }); + +/***/ }, +/* 19 */ +/***/ function(module, exports) { + + var id = 0 + , px = Math.random(); + module.exports = function(key){ + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); + }; + +/***/ }, +/* 20 */ +/***/ function(module, exports, __webpack_require__) { + + // optional / simple context binding + var aFunction = __webpack_require__(21); + module.exports = function(fn, that, length){ + aFunction(fn); + if(that === undefined)return fn; + switch(length){ + case 1: return function(a){ + return fn.call(that, a); + }; + case 2: return function(a, b){ + return fn.call(that, a, b); + }; + case 3: return function(a, b, c){ + return fn.call(that, a, b, c); + }; + } + return function(/* ...args */){ + return fn.apply(that, arguments); + }; + }; + +/***/ }, +/* 21 */ +/***/ function(module, exports) { + + module.exports = function(it){ + if(typeof it != 'function')throw TypeError(it + ' is not a function!'); + return it; + }; + +/***/ }, +/* 22 */ +/***/ function(module, exports, __webpack_require__) { + + var META = __webpack_require__(19)('meta') + , isObject = __webpack_require__(13) + , has = __webpack_require__(5) + , setDesc = __webpack_require__(11).f + , id = 0; + var isExtensible = Object.isExtensible || function(){ + return true; + }; + var FREEZE = !__webpack_require__(7)(function(){ + return isExtensible(Object.preventExtensions({})); + }); + var setMeta = function(it){ + setDesc(it, META, {value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + }}); + }; + var fastKey = function(it, create){ + // return primitive with prefix + if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if(!has(it, META)){ + // can't set metadata to uncaught frozen object + if(!isExtensible(it))return 'F'; + // not necessary to add metadata + if(!create)return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; + }; + var getWeak = function(it, create){ + if(!has(it, META)){ + // can't set metadata to uncaught frozen object + if(!isExtensible(it))return true; + // not necessary to add metadata + if(!create)return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; + }; + // add metadata on freeze-family methods calling + var onFreeze = function(it){ + if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); + return it; + }; + var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze + }; + +/***/ }, +/* 23 */ +/***/ function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4) + , SHARED = '__core-js_shared__' + , store = global[SHARED] || (global[SHARED] = {}); + module.exports = function(key){ + return store[key] || (store[key] = {}); + }; + +/***/ }, +/* 24 */ +/***/ function(module, exports, __webpack_require__) { + + var def = __webpack_require__(11).f + , has = __webpack_require__(5) + , TAG = __webpack_require__(25)('toStringTag'); + + module.exports = function(it, tag, stat){ + if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); + }; + +/***/ }, +/* 25 */ +/***/ function(module, exports, __webpack_require__) { + + var store = __webpack_require__(23)('wks') + , uid = __webpack_require__(19) + , Symbol = __webpack_require__(4).Symbol + , USE_SYMBOL = typeof Symbol == 'function'; + + var $exports = module.exports = function(name){ + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); + }; + + $exports.store = store; + +/***/ }, +/* 26 */ +/***/ function(module, exports, __webpack_require__) { + + exports.f = __webpack_require__(25); + +/***/ }, +/* 27 */ +/***/ function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4) + , core = __webpack_require__(9) + , LIBRARY = __webpack_require__(28) + , wksExt = __webpack_require__(26) + , defineProperty = __webpack_require__(11).f; + module.exports = function(name){ + var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); + if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); + }; + +/***/ }, +/* 28 */ +/***/ function(module, exports) { + + module.exports = false; + +/***/ }, +/* 29 */ +/***/ function(module, exports, __webpack_require__) { + + var getKeys = __webpack_require__(30) + , toIObject = __webpack_require__(32); + module.exports = function(object, el){ + var O = toIObject(object) + , keys = getKeys(O) + , length = keys.length + , index = 0 + , key; + while(length > index)if(O[key = keys[index++]] === el)return key; + }; + +/***/ }, +/* 30 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.14 / 15.2.3.14 Object.keys(O) + var $keys = __webpack_require__(31) + , enumBugKeys = __webpack_require__(41); + + module.exports = Object.keys || function keys(O){ + return $keys(O, enumBugKeys); + }; + +/***/ }, +/* 31 */ +/***/ function(module, exports, __webpack_require__) { + + var has = __webpack_require__(5) + , toIObject = __webpack_require__(32) + , arrayIndexOf = __webpack_require__(36)(false) + , IE_PROTO = __webpack_require__(40)('IE_PROTO'); + + module.exports = function(object, names){ + var O = toIObject(object) + , i = 0 + , result = [] + , key; + for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while(names.length > i)if(has(O, key = names[i++])){ + ~arrayIndexOf(result, key) || result.push(key); + } + return result; + }; + +/***/ }, +/* 32 */ +/***/ function(module, exports, __webpack_require__) { + + // to indexed object, toObject with fallback for non-array-like ES3 strings + var IObject = __webpack_require__(33) + , defined = __webpack_require__(35); + module.exports = function(it){ + return IObject(defined(it)); + }; + +/***/ }, +/* 33 */ +/***/ function(module, exports, __webpack_require__) { + + // fallback for non-array-like ES3 and non-enumerable old V8 strings + var cof = __webpack_require__(34); + module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ + return cof(it) == 'String' ? it.split('') : Object(it); + }; + +/***/ }, +/* 34 */ +/***/ function(module, exports) { + + var toString = {}.toString; + + module.exports = function(it){ + return toString.call(it).slice(8, -1); + }; + +/***/ }, +/* 35 */ +/***/ function(module, exports) { + + // 7.2.1 RequireObjectCoercible(argument) + module.exports = function(it){ + if(it == undefined)throw TypeError("Can't call method on " + it); + return it; + }; + +/***/ }, +/* 36 */ +/***/ function(module, exports, __webpack_require__) { + + // false -> Array#indexOf + // true -> Array#includes + var toIObject = __webpack_require__(32) + , toLength = __webpack_require__(37) + , toIndex = __webpack_require__(39); + module.exports = function(IS_INCLUDES){ + return function($this, el, fromIndex){ + var O = toIObject($this) + , length = toLength(O.length) + , index = toIndex(fromIndex, length) + , value; + // Array#includes uses SameValueZero equality algorithm + if(IS_INCLUDES && el != el)while(length > index){ + value = O[index++]; + if(value != value)return true; + // Array#toIndex ignores holes, Array#includes - not + } else for(;length > index; index++)if(IS_INCLUDES || index in O){ + if(O[index] === el)return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; + }; + +/***/ }, +/* 37 */ +/***/ function(module, exports, __webpack_require__) { + + // 7.1.15 ToLength + var toInteger = __webpack_require__(38) + , min = Math.min; + module.exports = function(it){ + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 + }; + +/***/ }, +/* 38 */ +/***/ function(module, exports) { + + // 7.1.4 ToInteger + var ceil = Math.ceil + , floor = Math.floor; + module.exports = function(it){ + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); + }; + +/***/ }, +/* 39 */ +/***/ function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38) + , max = Math.max + , min = Math.min; + module.exports = function(index, length){ + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); + }; + +/***/ }, +/* 40 */ +/***/ function(module, exports, __webpack_require__) { + + var shared = __webpack_require__(23)('keys') + , uid = __webpack_require__(19); + module.exports = function(key){ + return shared[key] || (shared[key] = uid(key)); + }; + +/***/ }, +/* 41 */ +/***/ function(module, exports) { + + // IE 8- don't enum bug keys + module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' + ).split(','); + +/***/ }, +/* 42 */ +/***/ function(module, exports, __webpack_require__) { + + // all enumerable object keys, includes symbols + var getKeys = __webpack_require__(30) + , gOPS = __webpack_require__(43) + , pIE = __webpack_require__(44); + module.exports = function(it){ + var result = getKeys(it) + , getSymbols = gOPS.f; + if(getSymbols){ + var symbols = getSymbols(it) + , isEnum = pIE.f + , i = 0 + , key; + while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); + } return result; + }; + +/***/ }, +/* 43 */ +/***/ function(module, exports) { + + exports.f = Object.getOwnPropertySymbols; + +/***/ }, +/* 44 */ +/***/ function(module, exports) { + + exports.f = {}.propertyIsEnumerable; + +/***/ }, +/* 45 */ +/***/ function(module, exports, __webpack_require__) { + + // 7.2.2 IsArray(argument) + var cof = __webpack_require__(34); + module.exports = Array.isArray || function isArray(arg){ + return cof(arg) == 'Array'; + }; + +/***/ }, +/* 46 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + var anObject = __webpack_require__(12) + , dPs = __webpack_require__(47) + , enumBugKeys = __webpack_require__(41) + , IE_PROTO = __webpack_require__(40)('IE_PROTO') + , Empty = function(){ /* empty */ } + , PROTOTYPE = 'prototype'; + + // Create object with fake `null` prototype: use iframe Object with cleared prototype + var createDict = function(){ + // Thrash, waste and sodomy: IE GC bug + var iframe = __webpack_require__(15)('iframe') + , i = enumBugKeys.length + , lt = '<' + , gt = '>' + , iframeDocument; + iframe.style.display = 'none'; + __webpack_require__(48).appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); + }; + + module.exports = Object.create || function create(O, Properties){ + var result; + if(O !== null){ + Empty[PROTOTYPE] = anObject(O); + result = new Empty; + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : dPs(result, Properties); + }; + + +/***/ }, +/* 47 */ +/***/ function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11) + , anObject = __webpack_require__(12) + , getKeys = __webpack_require__(30); + + module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties){ + anObject(O); + var keys = getKeys(Properties) + , length = keys.length + , i = 0 + , P; + while(length > i)dP.f(O, P = keys[i++], Properties[P]); + return O; + }; + +/***/ }, +/* 48 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = __webpack_require__(4).document && document.documentElement; + +/***/ }, +/* 49 */ +/***/ function(module, exports, __webpack_require__) { + + // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + var toIObject = __webpack_require__(32) + , gOPN = __webpack_require__(50).f + , toString = {}.toString; + + var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + + var getWindowNames = function(it){ + try { + return gOPN(it); + } catch(e){ + return windowNames.slice(); + } + }; + + module.exports.f = function getOwnPropertyNames(it){ + return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); + }; + + +/***/ }, +/* 50 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + var $keys = __webpack_require__(31) + , hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); + + exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ + return $keys(O, hiddenKeys); + }; + +/***/ }, +/* 51 */ +/***/ function(module, exports, __webpack_require__) { + + var pIE = __webpack_require__(44) + , createDesc = __webpack_require__(17) + , toIObject = __webpack_require__(32) + , toPrimitive = __webpack_require__(16) + , has = __webpack_require__(5) + , IE8_DOM_DEFINE = __webpack_require__(14) + , gOPD = Object.getOwnPropertyDescriptor; + + exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P){ + O = toIObject(O); + P = toPrimitive(P, true); + if(IE8_DOM_DEFINE)try { + return gOPD(O, P); + } catch(e){ /* empty */ } + if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); + }; + +/***/ }, +/* 52 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + $export($export.S, 'Object', {create: __webpack_require__(46)}); + +/***/ }, +/* 53 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', {defineProperty: __webpack_require__(11).f}); + +/***/ }, +/* 54 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', {defineProperties: __webpack_require__(47)}); + +/***/ }, +/* 55 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + var toIObject = __webpack_require__(32) + , $getOwnPropertyDescriptor = __webpack_require__(51).f; + + __webpack_require__(56)('getOwnPropertyDescriptor', function(){ + return function getOwnPropertyDescriptor(it, key){ + return $getOwnPropertyDescriptor(toIObject(it), key); + }; + }); + +/***/ }, +/* 56 */ +/***/ function(module, exports, __webpack_require__) { + + // most Object methods by ES6 should accept primitives + var $export = __webpack_require__(8) + , core = __webpack_require__(9) + , fails = __webpack_require__(7); + module.exports = function(KEY, exec){ + var fn = (core.Object || {})[KEY] || Object[KEY] + , exp = {}; + exp[KEY] = exec(fn); + $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); + }; + +/***/ }, +/* 57 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.9 Object.getPrototypeOf(O) + var toObject = __webpack_require__(58) + , $getPrototypeOf = __webpack_require__(59); + + __webpack_require__(56)('getPrototypeOf', function(){ + return function getPrototypeOf(it){ + return $getPrototypeOf(toObject(it)); + }; + }); + +/***/ }, +/* 58 */ +/***/ function(module, exports, __webpack_require__) { + + // 7.1.13 ToObject(argument) + var defined = __webpack_require__(35); + module.exports = function(it){ + return Object(defined(it)); + }; + +/***/ }, +/* 59 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) + var has = __webpack_require__(5) + , toObject = __webpack_require__(58) + , IE_PROTO = __webpack_require__(40)('IE_PROTO') + , ObjectProto = Object.prototype; + + module.exports = Object.getPrototypeOf || function(O){ + O = toObject(O); + if(has(O, IE_PROTO))return O[IE_PROTO]; + if(typeof O.constructor == 'function' && O instanceof O.constructor){ + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; + }; + +/***/ }, +/* 60 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.14 Object.keys(O) + var toObject = __webpack_require__(58) + , $keys = __webpack_require__(30); + + __webpack_require__(56)('keys', function(){ + return function keys(it){ + return $keys(toObject(it)); + }; + }); + +/***/ }, +/* 61 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.7 Object.getOwnPropertyNames(O) + __webpack_require__(56)('getOwnPropertyNames', function(){ + return __webpack_require__(49).f; + }); + +/***/ }, +/* 62 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.5 Object.freeze(O) + var isObject = __webpack_require__(13) + , meta = __webpack_require__(22).onFreeze; + + __webpack_require__(56)('freeze', function($freeze){ + return function freeze(it){ + return $freeze && isObject(it) ? $freeze(meta(it)) : it; + }; + }); + +/***/ }, +/* 63 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.17 Object.seal(O) + var isObject = __webpack_require__(13) + , meta = __webpack_require__(22).onFreeze; + + __webpack_require__(56)('seal', function($seal){ + return function seal(it){ + return $seal && isObject(it) ? $seal(meta(it)) : it; + }; + }); + +/***/ }, +/* 64 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.15 Object.preventExtensions(O) + var isObject = __webpack_require__(13) + , meta = __webpack_require__(22).onFreeze; + + __webpack_require__(56)('preventExtensions', function($preventExtensions){ + return function preventExtensions(it){ + return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; + }; + }); + +/***/ }, +/* 65 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.12 Object.isFrozen(O) + var isObject = __webpack_require__(13); + + __webpack_require__(56)('isFrozen', function($isFrozen){ + return function isFrozen(it){ + return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; + }; + }); + +/***/ }, +/* 66 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.13 Object.isSealed(O) + var isObject = __webpack_require__(13); + + __webpack_require__(56)('isSealed', function($isSealed){ + return function isSealed(it){ + return isObject(it) ? $isSealed ? $isSealed(it) : false : true; + }; + }); + +/***/ }, +/* 67 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.2.11 Object.isExtensible(O) + var isObject = __webpack_require__(13); + + __webpack_require__(56)('isExtensible', function($isExtensible){ + return function isExtensible(it){ + return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; + }; + }); + +/***/ }, +/* 68 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.3.1 Object.assign(target, source) + var $export = __webpack_require__(8); + + $export($export.S + $export.F, 'Object', {assign: __webpack_require__(69)}); + +/***/ }, +/* 69 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.2.1 Object.assign(target, source, ...) + var getKeys = __webpack_require__(30) + , gOPS = __webpack_require__(43) + , pIE = __webpack_require__(44) + , toObject = __webpack_require__(58) + , IObject = __webpack_require__(33) + , $assign = Object.assign; + + // should work with symbols and should have deterministic property order (V8 bug) + module.exports = !$assign || __webpack_require__(7)(function(){ + var A = {} + , B = {} + , S = Symbol() + , K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function(k){ B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; + }) ? function assign(target, source){ // eslint-disable-line no-unused-vars + var T = toObject(target) + , aLen = arguments.length + , index = 1 + , getSymbols = gOPS.f + , isEnum = pIE.f; + while(aLen > index){ + var S = IObject(arguments[index++]) + , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) + , length = keys.length + , j = 0 + , key; + while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; + } return T; + } : $assign; + +/***/ }, +/* 70 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.3.10 Object.is(value1, value2) + var $export = __webpack_require__(8); + $export($export.S, 'Object', {is: __webpack_require__(71)}); + +/***/ }, +/* 71 */ +/***/ function(module, exports) { + + // 7.2.9 SameValue(x, y) + module.exports = Object.is || function is(x, y){ + return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; + }; + +/***/ }, +/* 72 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.1.3.19 Object.setPrototypeOf(O, proto) + var $export = __webpack_require__(8); + $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(73).set}); + +/***/ }, +/* 73 */ +/***/ function(module, exports, __webpack_require__) { + + // Works with __proto__ only. Old v8 can't work with null proto objects. + /* eslint-disable no-proto */ + var isObject = __webpack_require__(13) + , anObject = __webpack_require__(12); + var check = function(O, proto){ + anObject(O); + if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); + }; + module.exports = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function(test, buggy, set){ + try { + set = __webpack_require__(20)(Function.call, __webpack_require__(51).f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch(e){ buggy = true; } + return function setPrototypeOf(O, proto){ + check(O, proto); + if(buggy)O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check + }; + +/***/ }, +/* 74 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.3.6 Object.prototype.toString() + var classof = __webpack_require__(75) + , test = {}; + test[__webpack_require__(25)('toStringTag')] = 'z'; + if(test + '' != '[object z]'){ + __webpack_require__(18)(Object.prototype, 'toString', function toString(){ + return '[object ' + classof(this) + ']'; + }, true); + } + +/***/ }, +/* 75 */ +/***/ function(module, exports, __webpack_require__) { + + // getting tag from 19.1.3.6 Object.prototype.toString() + var cof = __webpack_require__(34) + , TAG = __webpack_require__(25)('toStringTag') + // ES3 wrong here + , ARG = cof(function(){ return arguments; }()) == 'Arguments'; + + // fallback for IE11 Script Access Denied error + var tryGet = function(it, key){ + try { + return it[key]; + } catch(e){ /* empty */ } + }; + + module.exports = function(it){ + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; + }; + +/***/ }, +/* 76 */ +/***/ function(module, exports, __webpack_require__) { + + // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) + var $export = __webpack_require__(8); + + $export($export.P, 'Function', {bind: __webpack_require__(77)}); + +/***/ }, +/* 77 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var aFunction = __webpack_require__(21) + , isObject = __webpack_require__(13) + , invoke = __webpack_require__(78) + , arraySlice = [].slice + , factories = {}; + + var construct = function(F, len, args){ + if(!(len in factories)){ + for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']'; + factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); + } return factories[len](F, args); + }; + + module.exports = Function.bind || function bind(that /*, args... */){ + var fn = aFunction(this) + , partArgs = arraySlice.call(arguments, 1); + var bound = function(/* args... */){ + var args = partArgs.concat(arraySlice.call(arguments)); + return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); + }; + if(isObject(fn.prototype))bound.prototype = fn.prototype; + return bound; + }; + +/***/ }, +/* 78 */ +/***/ function(module, exports) { + + // fast apply, http://jsperf.lnkit.com/fast-apply/5 + module.exports = function(fn, args, that){ + var un = that === undefined; + switch(args.length){ + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); + }; + +/***/ }, +/* 79 */ +/***/ function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11).f + , createDesc = __webpack_require__(17) + , has = __webpack_require__(5) + , FProto = Function.prototype + , nameRE = /^\s*function ([^ (]*)/ + , NAME = 'name'; + + var isExtensible = Object.isExtensible || function(){ + return true; + }; + + // 19.2.4.2 name + NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { + configurable: true, + get: function(){ + try { + var that = this + , name = ('' + that).match(nameRE)[1]; + has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name)); + return name; + } catch(e){ + return ''; + } + } + }); + +/***/ }, +/* 80 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var isObject = __webpack_require__(13) + , getPrototypeOf = __webpack_require__(59) + , HAS_INSTANCE = __webpack_require__(25)('hasInstance') + , FunctionProto = Function.prototype; + // 19.2.3.6 Function.prototype[@@hasInstance](V) + if(!(HAS_INSTANCE in FunctionProto))__webpack_require__(11).f(FunctionProto, HAS_INSTANCE, {value: function(O){ + if(typeof this != 'function' || !isObject(O))return false; + if(!isObject(this.prototype))return O instanceof this; + // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: + while(O = getPrototypeOf(O))if(this.prototype === O)return true; + return false; + }}); + +/***/ }, +/* 81 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , $parseInt = __webpack_require__(82); + // 18.2.5 parseInt(string, radix) + $export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt}); + +/***/ }, +/* 82 */ +/***/ function(module, exports, __webpack_require__) { + + var $parseInt = __webpack_require__(4).parseInt + , $trim = __webpack_require__(83).trim + , ws = __webpack_require__(84) + , hex = /^[\-+]?0[xX]/; + + module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){ + var string = $trim(String(str), 3); + return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); + } : $parseInt; + +/***/ }, +/* 83 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , defined = __webpack_require__(35) + , fails = __webpack_require__(7) + , spaces = __webpack_require__(84) + , space = '[' + spaces + ']' + , non = '\u200b\u0085' + , ltrim = RegExp('^' + space + space + '*') + , rtrim = RegExp(space + space + '*$'); + + var exporter = function(KEY, exec, ALIAS){ + var exp = {}; + var FORCE = fails(function(){ + return !!spaces[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; + if(ALIAS)exp[ALIAS] = fn; + $export($export.P + $export.F * FORCE, 'String', exp); + }; + + // 1 -> String#trimLeft + // 2 -> String#trimRight + // 3 -> String#trim + var trim = exporter.trim = function(string, TYPE){ + string = String(defined(string)); + if(TYPE & 1)string = string.replace(ltrim, ''); + if(TYPE & 2)string = string.replace(rtrim, ''); + return string; + }; + + module.exports = exporter; + +/***/ }, +/* 84 */ +/***/ function(module, exports) { + + module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + +/***/ }, +/* 85 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , $parseFloat = __webpack_require__(86); + // 18.2.4 parseFloat(string) + $export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat}); + +/***/ }, +/* 86 */ +/***/ function(module, exports, __webpack_require__) { + + var $parseFloat = __webpack_require__(4).parseFloat + , $trim = __webpack_require__(83).trim; + + module.exports = 1 / $parseFloat(__webpack_require__(84) + '-0') !== -Infinity ? function parseFloat(str){ + var string = $trim(String(str), 3) + , result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; + } : $parseFloat; + +/***/ }, +/* 87 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4) + , has = __webpack_require__(5) + , cof = __webpack_require__(34) + , inheritIfRequired = __webpack_require__(88) + , toPrimitive = __webpack_require__(16) + , fails = __webpack_require__(7) + , gOPN = __webpack_require__(50).f + , gOPD = __webpack_require__(51).f + , dP = __webpack_require__(11).f + , $trim = __webpack_require__(83).trim + , NUMBER = 'Number' + , $Number = global[NUMBER] + , Base = $Number + , proto = $Number.prototype + // Opera ~12 has broken Object#toString + , BROKEN_COF = cof(__webpack_require__(46)(proto)) == NUMBER + , TRIM = 'trim' in String.prototype; + + // 7.1.3 ToNumber(argument) + var toNumber = function(argument){ + var it = toPrimitive(argument, false); + if(typeof it == 'string' && it.length > 2){ + it = TRIM ? it.trim() : $trim(it, 3); + var first = it.charCodeAt(0) + , third, radix, maxCode; + if(first === 43 || first === 45){ + third = it.charCodeAt(2); + if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix + } else if(first === 48){ + switch(it.charCodeAt(1)){ + case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i + case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i + default : return +it; + } + for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){ + code = digits.charCodeAt(i); + // parseInt parses a string to a first unavailable symbol + // but ToNumber should return NaN if a string contains unavailable symbols + if(code < 48 || code > maxCode)return NaN; + } return parseInt(digits, radix); + } + } return +it; + }; + + if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){ + $Number = function Number(value){ + var it = arguments.length < 1 ? 0 : value + , that = this; + return that instanceof $Number + // check on 1..constructor(foo) case + && (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER) + ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); + }; + for(var keys = __webpack_require__(6) ? gOPN(Base) : ( + // ES3: + 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + + // ES6 (in case, if modules with ES6 Number statics required before): + 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' + ).split(','), j = 0, key; keys.length > j; j++){ + if(has(Base, key = keys[j]) && !has($Number, key)){ + dP($Number, key, gOPD(Base, key)); + } + } + $Number.prototype = proto; + proto.constructor = $Number; + __webpack_require__(18)(global, NUMBER, $Number); + } + +/***/ }, +/* 88 */ +/***/ function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13) + , setPrototypeOf = __webpack_require__(73).set; + module.exports = function(that, target, C){ + var P, S = target.constructor; + if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){ + setPrototypeOf(that, P); + } return that; + }; + +/***/ }, +/* 89 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , toInteger = __webpack_require__(38) + , aNumberValue = __webpack_require__(90) + , repeat = __webpack_require__(91) + , $toFixed = 1..toFixed + , floor = Math.floor + , data = [0, 0, 0, 0, 0, 0] + , ERROR = 'Number.toFixed: incorrect invocation!' + , ZERO = '0'; + + var multiply = function(n, c){ + var i = -1 + , c2 = c; + while(++i < 6){ + c2 += n * data[i]; + data[i] = c2 % 1e7; + c2 = floor(c2 / 1e7); + } + }; + var divide = function(n){ + var i = 6 + , c = 0; + while(--i >= 0){ + c += data[i]; + data[i] = floor(c / n); + c = (c % n) * 1e7; + } + }; + var numToString = function(){ + var i = 6 + , s = ''; + while(--i >= 0){ + if(s !== '' || i === 0 || data[i] !== 0){ + var t = String(data[i]); + s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; + } + } return s; + }; + var pow = function(x, n, acc){ + return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); + }; + var log = function(x){ + var n = 0 + , x2 = x; + while(x2 >= 4096){ + n += 12; + x2 /= 4096; + } + while(x2 >= 2){ + n += 1; + x2 /= 2; + } return n; + }; + + $export($export.P + $export.F * (!!$toFixed && ( + 0.00008.toFixed(3) !== '0.000' || + 0.9.toFixed(0) !== '1' || + 1.255.toFixed(2) !== '1.25' || + 1000000000000000128..toFixed(0) !== '1000000000000000128' + ) || !__webpack_require__(7)(function(){ + // V8 ~ Android 4.3- + $toFixed.call({}); + })), 'Number', { + toFixed: function toFixed(fractionDigits){ + var x = aNumberValue(this, ERROR) + , f = toInteger(fractionDigits) + , s = '' + , m = ZERO + , e, z, j, k; + if(f < 0 || f > 20)throw RangeError(ERROR); + if(x != x)return 'NaN'; + if(x <= -1e21 || x >= 1e21)return String(x); + if(x < 0){ + s = '-'; + x = -x; + } + if(x > 1e-21){ + e = log(x * pow(2, 69, 1)) - 69; + z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); + z *= 0x10000000000000; + e = 52 - e; + if(e > 0){ + multiply(0, z); + j = f; + while(j >= 7){ + multiply(1e7, 0); + j -= 7; + } + multiply(pow(10, j, 1), 0); + j = e - 1; + while(j >= 23){ + divide(1 << 23); + j -= 23; + } + divide(1 << j); + multiply(1, 1); + divide(2); + m = numToString(); + } else { + multiply(0, z); + multiply(1 << -e, 0); + m = numToString() + repeat.call(ZERO, f); + } + } + if(f > 0){ + k = m.length; + m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); + } else { + m = s + m; + } return m; + } + }); + +/***/ }, +/* 90 */ +/***/ function(module, exports, __webpack_require__) { + + var cof = __webpack_require__(34); + module.exports = function(it, msg){ + if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg); + return +it; + }; + +/***/ }, +/* 91 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var toInteger = __webpack_require__(38) + , defined = __webpack_require__(35); + + module.exports = function repeat(count){ + var str = String(defined(this)) + , res = '' + , n = toInteger(count); + if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); + for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; + return res; + }; + +/***/ }, +/* 92 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $fails = __webpack_require__(7) + , aNumberValue = __webpack_require__(90) + , $toPrecision = 1..toPrecision; + + $export($export.P + $export.F * ($fails(function(){ + // IE7- + return $toPrecision.call(1, undefined) !== '1'; + }) || !$fails(function(){ + // V8 ~ Android 4.3- + $toPrecision.call({}); + })), 'Number', { + toPrecision: function toPrecision(precision){ + var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); + return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); + } + }); + +/***/ }, +/* 93 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.1.2.1 Number.EPSILON + var $export = __webpack_require__(8); + + $export($export.S, 'Number', {EPSILON: Math.pow(2, -52)}); + +/***/ }, +/* 94 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.1.2.2 Number.isFinite(number) + var $export = __webpack_require__(8) + , _isFinite = __webpack_require__(4).isFinite; + + $export($export.S, 'Number', { + isFinite: function isFinite(it){ + return typeof it == 'number' && _isFinite(it); + } + }); + +/***/ }, +/* 95 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', {isInteger: __webpack_require__(96)}); + +/***/ }, +/* 96 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var isObject = __webpack_require__(13) + , floor = Math.floor; + module.exports = function isInteger(it){ + return !isObject(it) && isFinite(it) && floor(it) === it; + }; + +/***/ }, +/* 97 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.1.2.4 Number.isNaN(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { + isNaN: function isNaN(number){ + return number != number; + } + }); + +/***/ }, +/* 98 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.1.2.5 Number.isSafeInteger(number) + var $export = __webpack_require__(8) + , isInteger = __webpack_require__(96) + , abs = Math.abs; + + $export($export.S, 'Number', { + isSafeInteger: function isSafeInteger(number){ + return isInteger(number) && abs(number) <= 0x1fffffffffffff; + } + }); + +/***/ }, +/* 99 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.1.2.6 Number.MAX_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff}); + +/***/ }, +/* 100 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.1.2.10 Number.MIN_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff}); + +/***/ }, +/* 101 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , $parseFloat = __webpack_require__(86); + // 20.1.2.12 Number.parseFloat(string) + $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat}); + +/***/ }, +/* 102 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , $parseInt = __webpack_require__(82); + // 20.1.2.13 Number.parseInt(string, radix) + $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt}); + +/***/ }, +/* 103 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.3 Math.acosh(x) + var $export = __webpack_require__(8) + , log1p = __webpack_require__(104) + , sqrt = Math.sqrt + , $acosh = Math.acosh; + + $export($export.S + $export.F * !($acosh + // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 + && Math.floor($acosh(Number.MAX_VALUE)) == 710 + // Tor Browser bug: Math.acosh(Infinity) -> NaN + && $acosh(Infinity) == Infinity + ), 'Math', { + acosh: function acosh(x){ + return (x = +x) < 1 ? NaN : x > 94906265.62425156 + ? Math.log(x) + Math.LN2 + : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); + } + }); + +/***/ }, +/* 104 */ +/***/ function(module, exports) { + + // 20.2.2.20 Math.log1p(x) + module.exports = Math.log1p || function log1p(x){ + return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); + }; + +/***/ }, +/* 105 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.5 Math.asinh(x) + var $export = __webpack_require__(8) + , $asinh = Math.asinh; + + function asinh(x){ + return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); + } + + // Tor Browser bug: Math.asinh(0) -> -0 + $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh}); + +/***/ }, +/* 106 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.7 Math.atanh(x) + var $export = __webpack_require__(8) + , $atanh = Math.atanh; + + // Tor Browser bug: Math.atanh(-0) -> 0 + $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { + atanh: function atanh(x){ + return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; + } + }); + +/***/ }, +/* 107 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.9 Math.cbrt(x) + var $export = __webpack_require__(8) + , sign = __webpack_require__(108); + + $export($export.S, 'Math', { + cbrt: function cbrt(x){ + return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); + } + }); + +/***/ }, +/* 108 */ +/***/ function(module, exports) { + + // 20.2.2.28 Math.sign(x) + module.exports = Math.sign || function sign(x){ + return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; + }; + +/***/ }, +/* 109 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.11 Math.clz32(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clz32: function clz32(x){ + return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; + } + }); + +/***/ }, +/* 110 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.12 Math.cosh(x) + var $export = __webpack_require__(8) + , exp = Math.exp; + + $export($export.S, 'Math', { + cosh: function cosh(x){ + return (exp(x = +x) + exp(-x)) / 2; + } + }); + +/***/ }, +/* 111 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.14 Math.expm1(x) + var $export = __webpack_require__(8) + , $expm1 = __webpack_require__(112); + + $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1}); + +/***/ }, +/* 112 */ +/***/ function(module, exports) { + + // 20.2.2.14 Math.expm1(x) + var $expm1 = Math.expm1; + module.exports = (!$expm1 + // Old FF bug + || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 + // Tor Browser bug + || $expm1(-2e-17) != -2e-17 + ) ? function expm1(x){ + return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; + } : $expm1; + +/***/ }, +/* 113 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var $export = __webpack_require__(8) + , sign = __webpack_require__(108) + , pow = Math.pow + , EPSILON = pow(2, -52) + , EPSILON32 = pow(2, -23) + , MAX32 = pow(2, 127) * (2 - EPSILON32) + , MIN32 = pow(2, -126); + + var roundTiesToEven = function(n){ + return n + 1 / EPSILON - 1 / EPSILON; + }; + + + $export($export.S, 'Math', { + fround: function fround(x){ + var $abs = Math.abs(x) + , $sign = sign(x) + , a, result; + if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; + a = (1 + EPSILON32 / EPSILON) * $abs; + result = a - (a - $abs); + if(result > MAX32 || result != result)return $sign * Infinity; + return $sign * result; + } + }); + +/***/ }, +/* 114 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) + var $export = __webpack_require__(8) + , abs = Math.abs; + + $export($export.S, 'Math', { + hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars + var sum = 0 + , i = 0 + , aLen = arguments.length + , larg = 0 + , arg, div; + while(i < aLen){ + arg = abs(arguments[i++]); + if(larg < arg){ + div = larg / arg; + sum = sum * div * div + 1; + larg = arg; + } else if(arg > 0){ + div = arg / larg; + sum += div * div; + } else sum += arg; + } + return larg === Infinity ? Infinity : larg * Math.sqrt(sum); + } + }); + +/***/ }, +/* 115 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.18 Math.imul(x, y) + var $export = __webpack_require__(8) + , $imul = Math.imul; + + // some WebKit versions fails with big numbers, some has wrong arity + $export($export.S + $export.F * __webpack_require__(7)(function(){ + return $imul(0xffffffff, 5) != -5 || $imul.length != 2; + }), 'Math', { + imul: function imul(x, y){ + var UINT16 = 0xffff + , xn = +x + , yn = +y + , xl = UINT16 & xn + , yl = UINT16 & yn; + return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); + } + }); + +/***/ }, +/* 116 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.21 Math.log10(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log10: function log10(x){ + return Math.log(x) / Math.LN10; + } + }); + +/***/ }, +/* 117 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.20 Math.log1p(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', {log1p: __webpack_require__(104)}); + +/***/ }, +/* 118 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.22 Math.log2(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log2: function log2(x){ + return Math.log(x) / Math.LN2; + } + }); + +/***/ }, +/* 119 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.28 Math.sign(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', {sign: __webpack_require__(108)}); + +/***/ }, +/* 120 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.30 Math.sinh(x) + var $export = __webpack_require__(8) + , expm1 = __webpack_require__(112) + , exp = Math.exp; + + // V8 near Chromium 38 has a problem with very small numbers + $export($export.S + $export.F * __webpack_require__(7)(function(){ + return !Math.sinh(-2e-17) != -2e-17; + }), 'Math', { + sinh: function sinh(x){ + return Math.abs(x = +x) < 1 + ? (expm1(x) - expm1(-x)) / 2 + : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); + } + }); + +/***/ }, +/* 121 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.33 Math.tanh(x) + var $export = __webpack_require__(8) + , expm1 = __webpack_require__(112) + , exp = Math.exp; + + $export($export.S, 'Math', { + tanh: function tanh(x){ + var a = expm1(x = +x) + , b = expm1(-x); + return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); + } + }); + +/***/ }, +/* 122 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.2.2.34 Math.trunc(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + trunc: function trunc(it){ + return (it > 0 ? Math.floor : Math.ceil)(it); + } + }); + +/***/ }, +/* 123 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , toIndex = __webpack_require__(39) + , fromCharCode = String.fromCharCode + , $fromCodePoint = String.fromCodePoint; + + // length should be 1, old FF problem + $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { + // 21.1.2.2 String.fromCodePoint(...codePoints) + fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars + var res = [] + , aLen = arguments.length + , i = 0 + , code; + while(aLen > i){ + code = +arguments[i++]; + if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); + res.push(code < 0x10000 + ? fromCharCode(code) + : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) + ); + } return res.join(''); + } + }); + +/***/ }, +/* 124 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , toIObject = __webpack_require__(32) + , toLength = __webpack_require__(37); + + $export($export.S, 'String', { + // 21.1.2.4 String.raw(callSite, ...substitutions) + raw: function raw(callSite){ + var tpl = toIObject(callSite.raw) + , len = toLength(tpl.length) + , aLen = arguments.length + , res = [] + , i = 0; + while(len > i){ + res.push(String(tpl[i++])); + if(i < aLen)res.push(String(arguments[i])); + } return res.join(''); + } + }); + +/***/ }, +/* 125 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.1.3.25 String.prototype.trim() + __webpack_require__(83)('trim', function($trim){ + return function trim(){ + return $trim(this, 3); + }; + }); + +/***/ }, +/* 126 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $at = __webpack_require__(127)(true); + + // 21.1.3.27 String.prototype[@@iterator]() + __webpack_require__(128)(String, 'String', function(iterated){ + this._t = String(iterated); // target + this._i = 0; // next index + // 21.1.5.2.1 %StringIteratorPrototype%.next() + }, function(){ + var O = this._t + , index = this._i + , point; + if(index >= O.length)return {value: undefined, done: true}; + point = $at(O, index); + this._i += point.length; + return {value: point, done: false}; + }); + +/***/ }, +/* 127 */ +/***/ function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38) + , defined = __webpack_require__(35); + // true -> String#at + // false -> String#codePointAt + module.exports = function(TO_STRING){ + return function(that, pos){ + var s = String(defined(that)) + , i = toInteger(pos) + , l = s.length + , a, b; + if(i < 0 || i >= l)return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; + }; + +/***/ }, +/* 128 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(28) + , $export = __webpack_require__(8) + , redefine = __webpack_require__(18) + , hide = __webpack_require__(10) + , has = __webpack_require__(5) + , Iterators = __webpack_require__(129) + , $iterCreate = __webpack_require__(130) + , setToStringTag = __webpack_require__(24) + , getPrototypeOf = __webpack_require__(59) + , ITERATOR = __webpack_require__(25)('iterator') + , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` + , FF_ITERATOR = '@@iterator' + , KEYS = 'keys' + , VALUES = 'values'; + + var returnThis = function(){ return this; }; + + module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ + $iterCreate(Constructor, NAME, next); + var getMethod = function(kind){ + if(!BUGGY && kind in proto)return proto[kind]; + switch(kind){ + case KEYS: return function keys(){ return new Constructor(this, kind); }; + case VALUES: return function values(){ return new Constructor(this, kind); }; + } return function entries(){ return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator' + , DEF_VALUES = DEFAULT == VALUES + , VALUES_BUG = false + , proto = Base.prototype + , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] + , $default = $native || getMethod(DEFAULT) + , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined + , $anyNative = NAME == 'Array' ? proto.entries || $native : $native + , methods, key, IteratorPrototype; + // Fix native + if($anyNative){ + IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); + if(IteratorPrototype !== Object.prototype){ + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if(DEF_VALUES && $native && $native.name !== VALUES){ + VALUES_BUG = true; + $default = function values(){ return $native.call(this); }; + } + // Define iterator + if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ + hide(proto, ITERATOR, $default); + } + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if(DEFAULT){ + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if(FORCED)for(key in methods){ + if(!(key in proto))redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; + }; + +/***/ }, +/* 129 */ +/***/ function(module, exports) { + + module.exports = {}; + +/***/ }, +/* 130 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var create = __webpack_require__(46) + , descriptor = __webpack_require__(17) + , setToStringTag = __webpack_require__(24) + , IteratorPrototype = {}; + + // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() + __webpack_require__(10)(IteratorPrototype, __webpack_require__(25)('iterator'), function(){ return this; }); + + module.exports = function(Constructor, NAME, next){ + Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); + setToStringTag(Constructor, NAME + ' Iterator'); + }; + +/***/ }, +/* 131 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $at = __webpack_require__(127)(false); + $export($export.P, 'String', { + // 21.1.3.3 String.prototype.codePointAt(pos) + codePointAt: function codePointAt(pos){ + return $at(this, pos); + } + }); + +/***/ }, +/* 132 */ +/***/ function(module, exports, __webpack_require__) { + + // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) + 'use strict'; + var $export = __webpack_require__(8) + , toLength = __webpack_require__(37) + , context = __webpack_require__(133) + , ENDS_WITH = 'endsWith' + , $endsWith = ''[ENDS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { + endsWith: function endsWith(searchString /*, endPosition = @length */){ + var that = context(this, searchString, ENDS_WITH) + , endPosition = arguments.length > 1 ? arguments[1] : undefined + , len = toLength(that.length) + , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len) + , search = String(searchString); + return $endsWith + ? $endsWith.call(that, search, end) + : that.slice(end - search.length, end) === search; + } + }); + +/***/ }, +/* 133 */ +/***/ function(module, exports, __webpack_require__) { + + // helper for String#{startsWith, endsWith, includes} + var isRegExp = __webpack_require__(134) + , defined = __webpack_require__(35); + + module.exports = function(that, searchString, NAME){ + if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!"); + return String(defined(that)); + }; + +/***/ }, +/* 134 */ +/***/ function(module, exports, __webpack_require__) { + + // 7.2.8 IsRegExp(argument) + var isObject = __webpack_require__(13) + , cof = __webpack_require__(34) + , MATCH = __webpack_require__(25)('match'); + module.exports = function(it){ + var isRegExp; + return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); + }; + +/***/ }, +/* 135 */ +/***/ function(module, exports, __webpack_require__) { + + var MATCH = __webpack_require__(25)('match'); + module.exports = function(KEY){ + var re = /./; + try { + '/./'[KEY](re); + } catch(e){ + try { + re[MATCH] = false; + return !'/./'[KEY](re); + } catch(f){ /* empty */ } + } return true; + }; + +/***/ }, +/* 136 */ +/***/ function(module, exports, __webpack_require__) { + + // 21.1.3.7 String.prototype.includes(searchString, position = 0) + 'use strict'; + var $export = __webpack_require__(8) + , context = __webpack_require__(133) + , INCLUDES = 'includes'; + + $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { + includes: function includes(searchString /*, position = 0 */){ + return !!~context(this, searchString, INCLUDES) + .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); + } + }); + +/***/ }, +/* 137 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + + $export($export.P, 'String', { + // 21.1.3.13 String.prototype.repeat(count) + repeat: __webpack_require__(91) + }); + +/***/ }, +/* 138 */ +/***/ function(module, exports, __webpack_require__) { + + // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) + 'use strict'; + var $export = __webpack_require__(8) + , toLength = __webpack_require__(37) + , context = __webpack_require__(133) + , STARTS_WITH = 'startsWith' + , $startsWith = ''[STARTS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { + startsWith: function startsWith(searchString /*, position = 0 */){ + var that = context(this, searchString, STARTS_WITH) + , index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)) + , search = String(searchString); + return $startsWith + ? $startsWith.call(that, search, index) + : that.slice(index, index + search.length) === search; + } + }); + +/***/ }, +/* 139 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.2 String.prototype.anchor(name) + __webpack_require__(140)('anchor', function(createHTML){ + return function anchor(name){ + return createHTML(this, 'a', 'name', name); + } + }); + +/***/ }, +/* 140 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , fails = __webpack_require__(7) + , defined = __webpack_require__(35) + , quot = /"/g; + // B.2.3.2.1 CreateHTML(string, tag, attribute, value) + var createHTML = function(string, tag, attribute, value) { + var S = String(defined(string)) + , p1 = '<' + tag; + if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; + return p1 + '>' + S + '</' + tag + '>'; + }; + module.exports = function(NAME, exec){ + var O = {}; + O[NAME] = exec(createHTML); + $export($export.P + $export.F * fails(function(){ + var test = ''[NAME]('"'); + return test !== test.toLowerCase() || test.split('"').length > 3; + }), 'String', O); + }; + +/***/ }, +/* 141 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.3 String.prototype.big() + __webpack_require__(140)('big', function(createHTML){ + return function big(){ + return createHTML(this, 'big', '', ''); + } + }); + +/***/ }, +/* 142 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.4 String.prototype.blink() + __webpack_require__(140)('blink', function(createHTML){ + return function blink(){ + return createHTML(this, 'blink', '', ''); + } + }); + +/***/ }, +/* 143 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.5 String.prototype.bold() + __webpack_require__(140)('bold', function(createHTML){ + return function bold(){ + return createHTML(this, 'b', '', ''); + } + }); + +/***/ }, +/* 144 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.6 String.prototype.fixed() + __webpack_require__(140)('fixed', function(createHTML){ + return function fixed(){ + return createHTML(this, 'tt', '', ''); + } + }); + +/***/ }, +/* 145 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.7 String.prototype.fontcolor(color) + __webpack_require__(140)('fontcolor', function(createHTML){ + return function fontcolor(color){ + return createHTML(this, 'font', 'color', color); + } + }); + +/***/ }, +/* 146 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.8 String.prototype.fontsize(size) + __webpack_require__(140)('fontsize', function(createHTML){ + return function fontsize(size){ + return createHTML(this, 'font', 'size', size); + } + }); + +/***/ }, +/* 147 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.9 String.prototype.italics() + __webpack_require__(140)('italics', function(createHTML){ + return function italics(){ + return createHTML(this, 'i', '', ''); + } + }); + +/***/ }, +/* 148 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.10 String.prototype.link(url) + __webpack_require__(140)('link', function(createHTML){ + return function link(url){ + return createHTML(this, 'a', 'href', url); + } + }); + +/***/ }, +/* 149 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.11 String.prototype.small() + __webpack_require__(140)('small', function(createHTML){ + return function small(){ + return createHTML(this, 'small', '', ''); + } + }); + +/***/ }, +/* 150 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.12 String.prototype.strike() + __webpack_require__(140)('strike', function(createHTML){ + return function strike(){ + return createHTML(this, 'strike', '', ''); + } + }); + +/***/ }, +/* 151 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.13 String.prototype.sub() + __webpack_require__(140)('sub', function(createHTML){ + return function sub(){ + return createHTML(this, 'sub', '', ''); + } + }); + +/***/ }, +/* 152 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.14 String.prototype.sup() + __webpack_require__(140)('sup', function(createHTML){ + return function sup(){ + return createHTML(this, 'sup', '', ''); + } + }); + +/***/ }, +/* 153 */ +/***/ function(module, exports, __webpack_require__) { + + // 20.3.3.1 / 15.9.4.4 Date.now() + var $export = __webpack_require__(8); + + $export($export.S, 'Date', {now: function(){ return new Date().getTime(); }}); + +/***/ }, +/* 154 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , toObject = __webpack_require__(58) + , toPrimitive = __webpack_require__(16); + + $export($export.P + $export.F * __webpack_require__(7)(function(){ + return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1; + }), 'Date', { + toJSON: function toJSON(key){ + var O = toObject(this) + , pv = toPrimitive(O); + return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); + } + }); + +/***/ }, +/* 155 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var $export = __webpack_require__(8) + , fails = __webpack_require__(7) + , getTime = Date.prototype.getTime; + + var lz = function(num){ + return num > 9 ? num : '0' + num; + }; + + // PhantomJS / old WebKit has a broken implementations + $export($export.P + $export.F * (fails(function(){ + return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z'; + }) || !fails(function(){ + new Date(NaN).toISOString(); + })), 'Date', { + toISOString: function toISOString(){ + if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value'); + var d = this + , y = d.getUTCFullYear() + , m = d.getUTCMilliseconds() + , s = y < 0 ? '-' : y > 9999 ? '+' : ''; + return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; + } + }); + +/***/ }, +/* 156 */ +/***/ function(module, exports, __webpack_require__) { + + var DateProto = Date.prototype + , INVALID_DATE = 'Invalid Date' + , TO_STRING = 'toString' + , $toString = DateProto[TO_STRING] + , getTime = DateProto.getTime; + if(new Date(NaN) + '' != INVALID_DATE){ + __webpack_require__(18)(DateProto, TO_STRING, function toString(){ + var value = getTime.call(this); + return value === value ? $toString.call(this) : INVALID_DATE; + }); + } + +/***/ }, +/* 157 */ +/***/ function(module, exports, __webpack_require__) { + + var TO_PRIMITIVE = __webpack_require__(25)('toPrimitive') + , proto = Date.prototype; + + if(!(TO_PRIMITIVE in proto))__webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(158)); + +/***/ }, +/* 158 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var anObject = __webpack_require__(12) + , toPrimitive = __webpack_require__(16) + , NUMBER = 'number'; + + module.exports = function(hint){ + if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint'); + return toPrimitive(anObject(this), hint != NUMBER); + }; + +/***/ }, +/* 159 */ +/***/ function(module, exports, __webpack_require__) { + + // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) + var $export = __webpack_require__(8); + + $export($export.S, 'Array', {isArray: __webpack_require__(45)}); + +/***/ }, +/* 160 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var ctx = __webpack_require__(20) + , $export = __webpack_require__(8) + , toObject = __webpack_require__(58) + , call = __webpack_require__(161) + , isArrayIter = __webpack_require__(162) + , toLength = __webpack_require__(37) + , createProperty = __webpack_require__(163) + , getIterFn = __webpack_require__(164); + + $export($export.S + $export.F * !__webpack_require__(165)(function(iter){ Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ + var O = toObject(arrayLike) + , C = typeof this == 'function' ? this : Array + , aLen = arguments.length + , mapfn = aLen > 1 ? arguments[1] : undefined + , mapping = mapfn !== undefined + , index = 0 + , iterFn = getIterFn(O) + , length, result, step, iterator; + if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ + for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ + createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = toLength(O.length); + for(result = new C(length); length > index; index++){ + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } + }); + + +/***/ }, +/* 161 */ +/***/ function(module, exports, __webpack_require__) { + + // call something on iterator step with safe closing on error + var anObject = __webpack_require__(12); + module.exports = function(iterator, fn, value, entries){ + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch(e){ + var ret = iterator['return']; + if(ret !== undefined)anObject(ret.call(iterator)); + throw e; + } + }; + +/***/ }, +/* 162 */ +/***/ function(module, exports, __webpack_require__) { + + // check on default Array iterator + var Iterators = __webpack_require__(129) + , ITERATOR = __webpack_require__(25)('iterator') + , ArrayProto = Array.prototype; + + module.exports = function(it){ + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); + }; + +/***/ }, +/* 163 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $defineProperty = __webpack_require__(11) + , createDesc = __webpack_require__(17); + + module.exports = function(object, index, value){ + if(index in object)$defineProperty.f(object, index, createDesc(0, value)); + else object[index] = value; + }; + +/***/ }, +/* 164 */ +/***/ function(module, exports, __webpack_require__) { + + var classof = __webpack_require__(75) + , ITERATOR = __webpack_require__(25)('iterator') + , Iterators = __webpack_require__(129); + module.exports = __webpack_require__(9).getIteratorMethod = function(it){ + if(it != undefined)return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; + }; + +/***/ }, +/* 165 */ +/***/ function(module, exports, __webpack_require__) { + + var ITERATOR = __webpack_require__(25)('iterator') + , SAFE_CLOSING = false; + + try { + var riter = [7][ITERATOR](); + riter['return'] = function(){ SAFE_CLOSING = true; }; + Array.from(riter, function(){ throw 2; }); + } catch(e){ /* empty */ } + + module.exports = function(exec, skipClosing){ + if(!skipClosing && !SAFE_CLOSING)return false; + var safe = false; + try { + var arr = [7] + , iter = arr[ITERATOR](); + iter.next = function(){ return {done: safe = true}; }; + arr[ITERATOR] = function(){ return iter; }; + exec(arr); + } catch(e){ /* empty */ } + return safe; + }; + +/***/ }, +/* 166 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , createProperty = __webpack_require__(163); + + // WebKit Array.of isn't generic + $export($export.S + $export.F * __webpack_require__(7)(function(){ + function F(){} + return !(Array.of.call(F) instanceof F); + }), 'Array', { + // 22.1.2.3 Array.of( ...items) + of: function of(/* ...args */){ + var index = 0 + , aLen = arguments.length + , result = new (typeof this == 'function' ? this : Array)(aLen); + while(aLen > index)createProperty(result, index, arguments[index++]); + result.length = aLen; + return result; + } + }); + +/***/ }, +/* 167 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.13 Array.prototype.join(separator) + var $export = __webpack_require__(8) + , toIObject = __webpack_require__(32) + , arrayJoin = [].join; + + // fallback for not array-like strings + $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(168)(arrayJoin)), 'Array', { + join: function join(separator){ + return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); + } + }); + +/***/ }, +/* 168 */ +/***/ function(module, exports, __webpack_require__) { + + var fails = __webpack_require__(7); + + module.exports = function(method, arg){ + return !!method && fails(function(){ + arg ? method.call(null, function(){}, 1) : method.call(null); + }); + }; + +/***/ }, +/* 169 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , html = __webpack_require__(48) + , cof = __webpack_require__(34) + , toIndex = __webpack_require__(39) + , toLength = __webpack_require__(37) + , arraySlice = [].slice; + + // fallback for not array-like ES3 strings and DOM objects + $export($export.P + $export.F * __webpack_require__(7)(function(){ + if(html)arraySlice.call(html); + }), 'Array', { + slice: function slice(begin, end){ + var len = toLength(this.length) + , klass = cof(this); + end = end === undefined ? len : end; + if(klass == 'Array')return arraySlice.call(this, begin, end); + var start = toIndex(begin, len) + , upTo = toIndex(end, len) + , size = toLength(upTo - start) + , cloned = Array(size) + , i = 0; + for(; i < size; i++)cloned[i] = klass == 'String' + ? this.charAt(start + i) + : this[start + i]; + return cloned; + } + }); + +/***/ }, +/* 170 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , aFunction = __webpack_require__(21) + , toObject = __webpack_require__(58) + , fails = __webpack_require__(7) + , $sort = [].sort + , test = [1, 2, 3]; + + $export($export.P + $export.F * (fails(function(){ + // IE8- + test.sort(undefined); + }) || !fails(function(){ + // V8 bug + test.sort(null); + // Old WebKit + }) || !__webpack_require__(168)($sort)), 'Array', { + // 22.1.3.25 Array.prototype.sort(comparefn) + sort: function sort(comparefn){ + return comparefn === undefined + ? $sort.call(toObject(this)) + : $sort.call(toObject(this), aFunction(comparefn)); + } + }); + +/***/ }, +/* 171 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $forEach = __webpack_require__(172)(0) + , STRICT = __webpack_require__(168)([].forEach, true); + + $export($export.P + $export.F * !STRICT, 'Array', { + // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) + forEach: function forEach(callbackfn /* , thisArg */){ + return $forEach(this, callbackfn, arguments[1]); + } + }); + +/***/ }, +/* 172 */ +/***/ function(module, exports, __webpack_require__) { + + // 0 -> Array#forEach + // 1 -> Array#map + // 2 -> Array#filter + // 3 -> Array#some + // 4 -> Array#every + // 5 -> Array#find + // 6 -> Array#findIndex + var ctx = __webpack_require__(20) + , IObject = __webpack_require__(33) + , toObject = __webpack_require__(58) + , toLength = __webpack_require__(37) + , asc = __webpack_require__(173); + module.exports = function(TYPE, $create){ + var IS_MAP = TYPE == 1 + , IS_FILTER = TYPE == 2 + , IS_SOME = TYPE == 3 + , IS_EVERY = TYPE == 4 + , IS_FIND_INDEX = TYPE == 6 + , NO_HOLES = TYPE == 5 || IS_FIND_INDEX + , create = $create || asc; + return function($this, callbackfn, that){ + var O = toObject($this) + , self = IObject(O) + , f = ctx(callbackfn, that, 3) + , length = toLength(self.length) + , index = 0 + , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined + , val, res; + for(;length > index; index++)if(NO_HOLES || index in self){ + val = self[index]; + res = f(val, index, O); + if(TYPE){ + if(IS_MAP)result[index] = res; // map + else if(res)switch(TYPE){ + case 3: return true; // some + case 5: return val; // find + case 6: return index; // findIndex + case 2: result.push(val); // filter + } else if(IS_EVERY)return false; // every + } + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; + }; + }; + +/***/ }, +/* 173 */ +/***/ function(module, exports, __webpack_require__) { + + // 9.4.2.3 ArraySpeciesCreate(originalArray, length) + var speciesConstructor = __webpack_require__(174); + + module.exports = function(original, length){ + return new (speciesConstructor(original))(length); + }; + +/***/ }, +/* 174 */ +/***/ function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13) + , isArray = __webpack_require__(45) + , SPECIES = __webpack_require__(25)('species'); + + module.exports = function(original){ + var C; + if(isArray(original)){ + C = original.constructor; + // cross-realm fallback + if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined; + if(isObject(C)){ + C = C[SPECIES]; + if(C === null)C = undefined; + } + } return C === undefined ? Array : C; + }; + +/***/ }, +/* 175 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $map = __webpack_require__(172)(1); + + $export($export.P + $export.F * !__webpack_require__(168)([].map, true), 'Array', { + // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) + map: function map(callbackfn /* , thisArg */){ + return $map(this, callbackfn, arguments[1]); + } + }); + +/***/ }, +/* 176 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $filter = __webpack_require__(172)(2); + + $export($export.P + $export.F * !__webpack_require__(168)([].filter, true), 'Array', { + // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) + filter: function filter(callbackfn /* , thisArg */){ + return $filter(this, callbackfn, arguments[1]); + } + }); + +/***/ }, +/* 177 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $some = __webpack_require__(172)(3); + + $export($export.P + $export.F * !__webpack_require__(168)([].some, true), 'Array', { + // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) + some: function some(callbackfn /* , thisArg */){ + return $some(this, callbackfn, arguments[1]); + } + }); + +/***/ }, +/* 178 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $every = __webpack_require__(172)(4); + + $export($export.P + $export.F * !__webpack_require__(168)([].every, true), 'Array', { + // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) + every: function every(callbackfn /* , thisArg */){ + return $every(this, callbackfn, arguments[1]); + } + }); + +/***/ }, +/* 179 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $reduce = __webpack_require__(180); + + $export($export.P + $export.F * !__webpack_require__(168)([].reduce, true), 'Array', { + // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) + reduce: function reduce(callbackfn /* , initialValue */){ + return $reduce(this, callbackfn, arguments.length, arguments[1], false); + } + }); + +/***/ }, +/* 180 */ +/***/ function(module, exports, __webpack_require__) { + + var aFunction = __webpack_require__(21) + , toObject = __webpack_require__(58) + , IObject = __webpack_require__(33) + , toLength = __webpack_require__(37); + + module.exports = function(that, callbackfn, aLen, memo, isRight){ + aFunction(callbackfn); + var O = toObject(that) + , self = IObject(O) + , length = toLength(O.length) + , index = isRight ? length - 1 : 0 + , i = isRight ? -1 : 1; + if(aLen < 2)for(;;){ + if(index in self){ + memo = self[index]; + index += i; + break; + } + index += i; + if(isRight ? index < 0 : length <= index){ + throw TypeError('Reduce of empty array with no initial value'); + } + } + for(;isRight ? index >= 0 : length > index; index += i)if(index in self){ + memo = callbackfn(memo, self[index], index, O); + } + return memo; + }; + +/***/ }, +/* 181 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $reduce = __webpack_require__(180); + + $export($export.P + $export.F * !__webpack_require__(168)([].reduceRight, true), 'Array', { + // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) + reduceRight: function reduceRight(callbackfn /* , initialValue */){ + return $reduce(this, callbackfn, arguments.length, arguments[1], true); + } + }); + +/***/ }, +/* 182 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $indexOf = __webpack_require__(36)(false) + , $native = [].indexOf + , NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(168)($native)), 'Array', { + // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) + indexOf: function indexOf(searchElement /*, fromIndex = 0 */){ + return NEGATIVE_ZERO + // convert -0 to +0 + ? $native.apply(this, arguments) || 0 + : $indexOf(this, searchElement, arguments[1]); + } + }); + +/***/ }, +/* 183 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , toIObject = __webpack_require__(32) + , toInteger = __webpack_require__(38) + , toLength = __webpack_require__(37) + , $native = [].lastIndexOf + , NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(168)($native)), 'Array', { + // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) + lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){ + // convert -0 to +0 + if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0; + var O = toIObject(this) + , length = toLength(O.length) + , index = length - 1; + if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1])); + if(index < 0)index = length + index; + for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0; + return -1; + } + }); + +/***/ }, +/* 184 */ +/***/ function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', {copyWithin: __webpack_require__(185)}); + + __webpack_require__(186)('copyWithin'); + +/***/ }, +/* 185 */ +/***/ function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + 'use strict'; + var toObject = __webpack_require__(58) + , toIndex = __webpack_require__(39) + , toLength = __webpack_require__(37); + + module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){ + var O = toObject(this) + , len = toLength(O.length) + , to = toIndex(target, len) + , from = toIndex(start, len) + , end = arguments.length > 2 ? arguments[2] : undefined + , count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to) + , inc = 1; + if(from < to && to < from + count){ + inc = -1; + from += count - 1; + to += count - 1; + } + while(count-- > 0){ + if(from in O)O[to] = O[from]; + else delete O[to]; + to += inc; + from += inc; + } return O; + }; + +/***/ }, +/* 186 */ +/***/ function(module, exports, __webpack_require__) { + + // 22.1.3.31 Array.prototype[@@unscopables] + var UNSCOPABLES = __webpack_require__(25)('unscopables') + , ArrayProto = Array.prototype; + if(ArrayProto[UNSCOPABLES] == undefined)__webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); + module.exports = function(key){ + ArrayProto[UNSCOPABLES][key] = true; + }; + +/***/ }, +/* 187 */ +/***/ function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', {fill: __webpack_require__(188)}); + + __webpack_require__(186)('fill'); + +/***/ }, +/* 188 */ +/***/ function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + 'use strict'; + var toObject = __webpack_require__(58) + , toIndex = __webpack_require__(39) + , toLength = __webpack_require__(37); + module.exports = function fill(value /*, start = 0, end = @length */){ + var O = toObject(this) + , length = toLength(O.length) + , aLen = arguments.length + , index = toIndex(aLen > 1 ? arguments[1] : undefined, length) + , end = aLen > 2 ? arguments[2] : undefined + , endPos = end === undefined ? length : toIndex(end, length); + while(endPos > index)O[index++] = value; + return O; + }; + +/***/ }, +/* 189 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) + var $export = __webpack_require__(8) + , $find = __webpack_require__(172)(5) + , KEY = 'find' + , forced = true; + // Shouldn't skip holes + if(KEY in [])Array(1)[KEY](function(){ forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + find: function find(callbackfn/*, that = undefined */){ + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(186)(KEY); + +/***/ }, +/* 190 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) + var $export = __webpack_require__(8) + , $find = __webpack_require__(172)(6) + , KEY = 'findIndex' + , forced = true; + // Shouldn't skip holes + if(KEY in [])Array(1)[KEY](function(){ forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + findIndex: function findIndex(callbackfn/*, that = undefined */){ + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(186)(KEY); + +/***/ }, +/* 191 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(192)('Array'); + +/***/ }, +/* 192 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4) + , dP = __webpack_require__(11) + , DESCRIPTORS = __webpack_require__(6) + , SPECIES = __webpack_require__(25)('species'); + + module.exports = function(KEY){ + var C = global[KEY]; + if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { + configurable: true, + get: function(){ return this; } + }); + }; + +/***/ }, +/* 193 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var addToUnscopables = __webpack_require__(186) + , step = __webpack_require__(194) + , Iterators = __webpack_require__(129) + , toIObject = __webpack_require__(32); + + // 22.1.3.4 Array.prototype.entries() + // 22.1.3.13 Array.prototype.keys() + // 22.1.3.29 Array.prototype.values() + // 22.1.3.30 Array.prototype[@@iterator]() + module.exports = __webpack_require__(128)(Array, 'Array', function(iterated, kind){ + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind + // 22.1.5.2.1 %ArrayIteratorPrototype%.next() + }, function(){ + var O = this._t + , kind = this._k + , index = this._i++; + if(!O || index >= O.length){ + this._t = undefined; + return step(1); + } + if(kind == 'keys' )return step(0, index); + if(kind == 'values')return step(0, O[index]); + return step(0, [index, O[index]]); + }, 'values'); + + // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) + Iterators.Arguments = Iterators.Array; + + addToUnscopables('keys'); + addToUnscopables('values'); + addToUnscopables('entries'); + +/***/ }, +/* 194 */ +/***/ function(module, exports) { + + module.exports = function(done, value){ + return {value: value, done: !!done}; + }; + +/***/ }, +/* 195 */ +/***/ function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4) + , inheritIfRequired = __webpack_require__(88) + , dP = __webpack_require__(11).f + , gOPN = __webpack_require__(50).f + , isRegExp = __webpack_require__(134) + , $flags = __webpack_require__(196) + , $RegExp = global.RegExp + , Base = $RegExp + , proto = $RegExp.prototype + , re1 = /a/g + , re2 = /a/g + // "new" creates a new object, old webkit buggy here + , CORRECT_NEW = new $RegExp(re1) !== re1; + + if(__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function(){ + re2[__webpack_require__(25)('match')] = false; + // RegExp constructor can alter flags and IsRegExp works correct with @@match + return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; + }))){ + $RegExp = function RegExp(p, f){ + var tiRE = this instanceof $RegExp + , piRE = isRegExp(p) + , fiU = f === undefined; + return !tiRE && piRE && p.constructor === $RegExp && fiU ? p + : inheritIfRequired(CORRECT_NEW + ? new Base(piRE && !fiU ? p.source : p, f) + : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) + , tiRE ? this : proto, $RegExp); + }; + var proxy = function(key){ + key in $RegExp || dP($RegExp, key, { + configurable: true, + get: function(){ return Base[key]; }, + set: function(it){ Base[key] = it; } + }); + }; + for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]); + proto.constructor = $RegExp; + $RegExp.prototype = proto; + __webpack_require__(18)(global, 'RegExp', $RegExp); + } + + __webpack_require__(192)('RegExp'); + +/***/ }, +/* 196 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.2.5.3 get RegExp.prototype.flags + var anObject = __webpack_require__(12); + module.exports = function(){ + var that = anObject(this) + , result = ''; + if(that.global) result += 'g'; + if(that.ignoreCase) result += 'i'; + if(that.multiline) result += 'm'; + if(that.unicode) result += 'u'; + if(that.sticky) result += 'y'; + return result; + }; + +/***/ }, +/* 197 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + __webpack_require__(198); + var anObject = __webpack_require__(12) + , $flags = __webpack_require__(196) + , DESCRIPTORS = __webpack_require__(6) + , TO_STRING = 'toString' + , $toString = /./[TO_STRING]; + + var define = function(fn){ + __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); + }; + + // 21.2.5.14 RegExp.prototype.toString() + if(__webpack_require__(7)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){ + define(function toString(){ + var R = anObject(this); + return '/'.concat(R.source, '/', + 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); + }); + // FF44- RegExp#toString has a wrong name + } else if($toString.name != TO_STRING){ + define(function toString(){ + return $toString.call(this); + }); + } + +/***/ }, +/* 198 */ +/***/ function(module, exports, __webpack_require__) { + + // 21.2.5.3 get RegExp.prototype.flags() + if(__webpack_require__(6) && /./g.flags != 'g')__webpack_require__(11).f(RegExp.prototype, 'flags', { + configurable: true, + get: __webpack_require__(196) + }); + +/***/ }, +/* 199 */ +/***/ function(module, exports, __webpack_require__) { + + // @@match logic + __webpack_require__(200)('match', 1, function(defined, MATCH, $match){ + // 21.1.3.11 String.prototype.match(regexp) + return [function match(regexp){ + 'use strict'; + var O = defined(this) + , fn = regexp == undefined ? undefined : regexp[MATCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); + }, $match]; + }); + +/***/ }, +/* 200 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var hide = __webpack_require__(10) + , redefine = __webpack_require__(18) + , fails = __webpack_require__(7) + , defined = __webpack_require__(35) + , wks = __webpack_require__(25); + + module.exports = function(KEY, length, exec){ + var SYMBOL = wks(KEY) + , fns = exec(defined, SYMBOL, ''[KEY]) + , strfn = fns[0] + , rxfn = fns[1]; + if(fails(function(){ + var O = {}; + O[SYMBOL] = function(){ return 7; }; + return ''[KEY](O) != 7; + })){ + redefine(String.prototype, KEY, strfn); + hide(RegExp.prototype, SYMBOL, length == 2 + // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) + // 21.2.5.11 RegExp.prototype[@@split](string, limit) + ? function(string, arg){ return rxfn.call(string, this, arg); } + // 21.2.5.6 RegExp.prototype[@@match](string) + // 21.2.5.9 RegExp.prototype[@@search](string) + : function(string){ return rxfn.call(string, this); } + ); + } + }; + +/***/ }, +/* 201 */ +/***/ function(module, exports, __webpack_require__) { + + // @@replace logic + __webpack_require__(200)('replace', 2, function(defined, REPLACE, $replace){ + // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) + return [function replace(searchValue, replaceValue){ + 'use strict'; + var O = defined(this) + , fn = searchValue == undefined ? undefined : searchValue[REPLACE]; + return fn !== undefined + ? fn.call(searchValue, O, replaceValue) + : $replace.call(String(O), searchValue, replaceValue); + }, $replace]; + }); + +/***/ }, +/* 202 */ +/***/ function(module, exports, __webpack_require__) { + + // @@search logic + __webpack_require__(200)('search', 1, function(defined, SEARCH, $search){ + // 21.1.3.15 String.prototype.search(regexp) + return [function search(regexp){ + 'use strict'; + var O = defined(this) + , fn = regexp == undefined ? undefined : regexp[SEARCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); + }, $search]; + }); + +/***/ }, +/* 203 */ +/***/ function(module, exports, __webpack_require__) { + + // @@split logic + __webpack_require__(200)('split', 2, function(defined, SPLIT, $split){ + 'use strict'; + var isRegExp = __webpack_require__(134) + , _split = $split + , $push = [].push + , $SPLIT = 'split' + , LENGTH = 'length' + , LAST_INDEX = 'lastIndex'; + if( + 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || + 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || + 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || + '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || + '.'[$SPLIT](/()()/)[LENGTH] > 1 || + ''[$SPLIT](/.?/)[LENGTH] + ){ + var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group + // based on es5-shim implementation, need to rework it + $split = function(separator, limit){ + var string = String(this); + if(separator === undefined && limit === 0)return []; + // If `separator` is not a regex, use native split + if(!isRegExp(separator))return _split.call(string, separator, limit); + var output = []; + var flags = (separator.ignoreCase ? 'i' : '') + + (separator.multiline ? 'm' : '') + + (separator.unicode ? 'u' : '') + + (separator.sticky ? 'y' : ''); + var lastLastIndex = 0; + var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; + // Make `global` and avoid `lastIndex` issues by working with a copy + var separatorCopy = new RegExp(separator.source, flags + 'g'); + var separator2, match, lastIndex, lastLength, i; + // Doesn't need flags gy, but they don't hurt + if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); + while(match = separatorCopy.exec(string)){ + // `separatorCopy.lastIndex` is not reliable cross-browser + lastIndex = match.index + match[0][LENGTH]; + if(lastIndex > lastLastIndex){ + output.push(string.slice(lastLastIndex, match.index)); + // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG + if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){ + for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined; + }); + if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1)); + lastLength = match[0][LENGTH]; + lastLastIndex = lastIndex; + if(output[LENGTH] >= splitLimit)break; + } + if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop + } + if(lastLastIndex === string[LENGTH]){ + if(lastLength || !separatorCopy.test(''))output.push(''); + } else output.push(string.slice(lastLastIndex)); + return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; + }; + // Chakra, V8 + } else if('0'[$SPLIT](undefined, 0)[LENGTH]){ + $split = function(separator, limit){ + return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); + }; + } + // 21.1.3.17 String.prototype.split(separator, limit) + return [function split(separator, limit){ + var O = defined(this) + , fn = separator == undefined ? undefined : separator[SPLIT]; + return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); + }, $split]; + }); + +/***/ }, +/* 204 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(28) + , global = __webpack_require__(4) + , ctx = __webpack_require__(20) + , classof = __webpack_require__(75) + , $export = __webpack_require__(8) + , isObject = __webpack_require__(13) + , aFunction = __webpack_require__(21) + , anInstance = __webpack_require__(205) + , forOf = __webpack_require__(206) + , speciesConstructor = __webpack_require__(207) + , task = __webpack_require__(208).set + , microtask = __webpack_require__(209)() + , PROMISE = 'Promise' + , TypeError = global.TypeError + , process = global.process + , $Promise = global[PROMISE] + , process = global.process + , isNode = classof(process) == 'process' + , empty = function(){ /* empty */ } + , Internal, GenericPromiseCapability, Wrapper; + + var USE_NATIVE = !!function(){ + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1) + , FakePromise = (promise.constructor = {})[__webpack_require__(25)('species')] = function(exec){ exec(empty, empty); }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; + } catch(e){ /* empty */ } + }(); + + // helpers + var sameConstructor = function(a, b){ + // with library wrapper special case + return a === b || a === $Promise && b === Wrapper; + }; + var isThenable = function(it){ + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; + }; + var newPromiseCapability = function(C){ + return sameConstructor($Promise, C) + ? new PromiseCapability(C) + : new GenericPromiseCapability(C); + }; + var PromiseCapability = GenericPromiseCapability = function(C){ + var resolve, reject; + this.promise = new C(function($$resolve, $$reject){ + if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); + }; + var perform = function(exec){ + try { + exec(); + } catch(e){ + return {error: e}; + } + }; + var notify = function(promise, isReject){ + if(promise._n)return; + promise._n = true; + var chain = promise._c; + microtask(function(){ + var value = promise._v + , ok = promise._s == 1 + , i = 0; + var run = function(reaction){ + var handler = ok ? reaction.ok : reaction.fail + , resolve = reaction.resolve + , reject = reaction.reject + , domain = reaction.domain + , result, then; + try { + if(handler){ + if(!ok){ + if(promise._h == 2)onHandleUnhandled(promise); + promise._h = 1; + } + if(handler === true)result = value; + else { + if(domain)domain.enter(); + result = handler(value); + if(domain)domain.exit(); + } + if(result === reaction.promise){ + reject(TypeError('Promise-chain cycle')); + } else if(then = isThenable(result)){ + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch(e){ + reject(e); + } + }; + while(chain.length > i)run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if(isReject && !promise._h)onUnhandled(promise); + }); + }; + var onUnhandled = function(promise){ + task.call(global, function(){ + var value = promise._v + , abrupt, handler, console; + if(isUnhandled(promise)){ + abrupt = perform(function(){ + if(isNode){ + process.emit('unhandledRejection', value, promise); + } else if(handler = global.onunhandledrejection){ + handler({promise: promise, reason: value}); + } else if((console = global.console) && console.error){ + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if(abrupt)throw abrupt.error; + }); + }; + var isUnhandled = function(promise){ + if(promise._h == 1)return false; + var chain = promise._a || promise._c + , i = 0 + , reaction; + while(chain.length > i){ + reaction = chain[i++]; + if(reaction.fail || !isUnhandled(reaction.promise))return false; + } return true; + }; + var onHandleUnhandled = function(promise){ + task.call(global, function(){ + var handler; + if(isNode){ + process.emit('rejectionHandled', promise); + } else if(handler = global.onrejectionhandled){ + handler({promise: promise, reason: promise._v}); + } + }); + }; + var $reject = function(value){ + var promise = this; + if(promise._d)return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if(!promise._a)promise._a = promise._c.slice(); + notify(promise, true); + }; + var $resolve = function(value){ + var promise = this + , then; + if(promise._d)return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if(promise === value)throw TypeError("Promise can't be resolved itself"); + if(then = isThenable(value)){ + microtask(function(){ + var wrapper = {_w: promise, _d: false}; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch(e){ + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch(e){ + $reject.call({_w: promise, _d: false}, e); // wrap + } + }; + + // constructor polyfill + if(!USE_NATIVE){ + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor){ + anInstance(this, $Promise, PROMISE, '_h'); + aFunction(executor); + Internal.call(this); + try { + executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + } catch(err){ + $reject.call(this, err); + } + }; + Internal = function Promise(executor){ + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = __webpack_require__(210)($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected){ + var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode ? process.domain : undefined; + this._c.push(reaction); + if(this._a)this._a.push(reaction); + if(this._s)notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function(onRejected){ + return this.then(undefined, onRejected); + } + }); + PromiseCapability = function(){ + var promise = new Internal; + this.promise = promise; + this.resolve = ctx($resolve, promise, 1); + this.reject = ctx($reject, promise, 1); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); + __webpack_require__(24)($Promise, PROMISE); + __webpack_require__(192)(PROMISE); + Wrapper = __webpack_require__(9)[PROMISE]; + + // statics + $export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r){ + var capability = newPromiseCapability(this) + , $$reject = capability.reject; + $$reject(r); + return capability.promise; + } + }); + $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x){ + // instanceof instead of internal slot check because we should fix it without replacement native Promise core + if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; + var capability = newPromiseCapability(this) + , $$resolve = capability.resolve; + $$resolve(x); + return capability.promise; + } + }); + $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(165)(function(iter){ + $Promise.all(iter)['catch'](empty); + })), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable){ + var C = this + , capability = newPromiseCapability(C) + , resolve = capability.resolve + , reject = capability.reject; + var abrupt = perform(function(){ + var values = [] + , index = 0 + , remaining = 1; + forOf(iterable, false, function(promise){ + var $index = index++ + , alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function(value){ + if(alreadyCalled)return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if(abrupt)reject(abrupt.error); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable){ + var C = this + , capability = newPromiseCapability(C) + , reject = capability.reject; + var abrupt = perform(function(){ + forOf(iterable, false, function(promise){ + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if(abrupt)reject(abrupt.error); + return capability.promise; + } + }); + +/***/ }, +/* 205 */ +/***/ function(module, exports) { + + module.exports = function(it, Constructor, name, forbiddenField){ + if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ + throw TypeError(name + ': incorrect invocation!'); + } return it; + }; + +/***/ }, +/* 206 */ +/***/ function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20) + , call = __webpack_require__(161) + , isArrayIter = __webpack_require__(162) + , anObject = __webpack_require__(12) + , toLength = __webpack_require__(37) + , getIterFn = __webpack_require__(164) + , BREAK = {} + , RETURN = {}; + var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ + var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) + , f = ctx(fn, that, entries ? 2 : 1) + , index = 0 + , length, step, iterator, result; + if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ + result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if(result === BREAK || result === RETURN)return result; + } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ + result = call(iterator, f, step.value, entries); + if(result === BREAK || result === RETURN)return result; + } + }; + exports.BREAK = BREAK; + exports.RETURN = RETURN; + +/***/ }, +/* 207 */ +/***/ function(module, exports, __webpack_require__) { + + // 7.3.20 SpeciesConstructor(O, defaultConstructor) + var anObject = __webpack_require__(12) + , aFunction = __webpack_require__(21) + , SPECIES = __webpack_require__(25)('species'); + module.exports = function(O, D){ + var C = anObject(O).constructor, S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); + }; + +/***/ }, +/* 208 */ +/***/ function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20) + , invoke = __webpack_require__(78) + , html = __webpack_require__(48) + , cel = __webpack_require__(15) + , global = __webpack_require__(4) + , process = global.process + , setTask = global.setImmediate + , clearTask = global.clearImmediate + , MessageChannel = global.MessageChannel + , counter = 0 + , queue = {} + , ONREADYSTATECHANGE = 'onreadystatechange' + , defer, channel, port; + var run = function(){ + var id = +this; + if(queue.hasOwnProperty(id)){ + var fn = queue[id]; + delete queue[id]; + fn(); + } + }; + var listener = function(event){ + run.call(event.data); + }; + // Node.js 0.9+ & IE10+ has setImmediate, otherwise: + if(!setTask || !clearTask){ + setTask = function setImmediate(fn){ + var args = [], i = 1; + while(arguments.length > i)args.push(arguments[i++]); + queue[++counter] = function(){ + invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id){ + delete queue[id]; + }; + // Node.js 0.8- + if(__webpack_require__(34)(process) == 'process'){ + defer = function(id){ + process.nextTick(ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if(MessageChannel){ + channel = new MessageChannel; + port = channel.port2; + channel.port1.onmessage = listener; + defer = ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ + defer = function(id){ + global.postMessage(id + '', '*'); + }; + global.addEventListener('message', listener, false); + // IE8- + } else if(ONREADYSTATECHANGE in cel('script')){ + defer = function(id){ + html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ + html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function(id){ + setTimeout(ctx(run, id, 1), 0); + }; + } + } + module.exports = { + set: setTask, + clear: clearTask + }; + +/***/ }, +/* 209 */ +/***/ function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4) + , macrotask = __webpack_require__(208).set + , Observer = global.MutationObserver || global.WebKitMutationObserver + , process = global.process + , Promise = global.Promise + , isNode = __webpack_require__(34)(process) == 'process'; + + module.exports = function(){ + var head, last, notify; + + var flush = function(){ + var parent, fn; + if(isNode && (parent = process.domain))parent.exit(); + while(head){ + fn = head.fn; + head = head.next; + try { + fn(); + } catch(e){ + if(head)notify(); + else last = undefined; + throw e; + } + } last = undefined; + if(parent)parent.enter(); + }; + + // Node.js + if(isNode){ + notify = function(){ + process.nextTick(flush); + }; + // browsers with MutationObserver + } else if(Observer){ + var toggle = true + , node = document.createTextNode(''); + new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new + notify = function(){ + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if(Promise && Promise.resolve){ + var promise = Promise.resolve(); + notify = function(){ + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function(){ + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } + + return function(fn){ + var task = {fn: fn, next: undefined}; + if(last)last.next = task; + if(!head){ + head = task; + notify(); + } last = task; + }; + }; + +/***/ }, +/* 210 */ +/***/ function(module, exports, __webpack_require__) { + + var redefine = __webpack_require__(18); + module.exports = function(target, src, safe){ + for(var key in src)redefine(target, key, src[key], safe); + return target; + }; + +/***/ }, +/* 211 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(212); + + // 23.1 Map Objects + module.exports = __webpack_require__(213)('Map', function(get){ + return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key){ + var entry = strong.getEntry(this, key); + return entry && entry.v; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value){ + return strong.def(this, key === 0 ? 0 : key, value); + } + }, strong, true); + +/***/ }, +/* 212 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var dP = __webpack_require__(11).f + , create = __webpack_require__(46) + , redefineAll = __webpack_require__(210) + , ctx = __webpack_require__(20) + , anInstance = __webpack_require__(205) + , defined = __webpack_require__(35) + , forOf = __webpack_require__(206) + , $iterDefine = __webpack_require__(128) + , step = __webpack_require__(194) + , setSpecies = __webpack_require__(192) + , DESCRIPTORS = __webpack_require__(6) + , fastKey = __webpack_require__(22).fastKey + , SIZE = DESCRIPTORS ? '_s' : 'size'; + + var getEntry = function(that, key){ + // fast case + var index = fastKey(key), entry; + if(index !== 'F')return that._i[index]; + // frozen object case + for(entry = that._f; entry; entry = entry.n){ + if(entry.k == key)return entry; + } + }; + + module.exports = { + getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ + var C = wrapper(function(that, iterable){ + anInstance(that, C, NAME, '_i'); + that._i = create(null); // index + that._f = undefined; // first entry + that._l = undefined; // last entry + that[SIZE] = 0; // size + if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear(){ + for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ + entry.r = true; + if(entry.p)entry.p = entry.p.n = undefined; + delete data[entry.i]; + } + that._f = that._l = undefined; + that[SIZE] = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function(key){ + var that = this + , entry = getEntry(that, key); + if(entry){ + var next = entry.n + , prev = entry.p; + delete that._i[entry.i]; + entry.r = true; + if(prev)prev.n = next; + if(next)next.p = prev; + if(that._f == entry)that._f = next; + if(that._l == entry)that._l = prev; + that[SIZE]--; + } return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /*, that = undefined */){ + anInstance(this, C, 'forEach'); + var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) + , entry; + while(entry = entry ? entry.n : this._f){ + f(entry.v, entry.k, this); + // revert to the last existing entry + while(entry && entry.r)entry = entry.p; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key){ + return !!getEntry(this, key); + } + }); + if(DESCRIPTORS)dP(C.prototype, 'size', { + get: function(){ + return defined(this[SIZE]); + } + }); + return C; + }, + def: function(that, key, value){ + var entry = getEntry(that, key) + , prev, index; + // change existing entry + if(entry){ + entry.v = value; + // create new entry + } else { + that._l = entry = { + i: index = fastKey(key, true), // <- index + k: key, // <- key + v: value, // <- value + p: prev = that._l, // <- previous entry + n: undefined, // <- next entry + r: false // <- removed + }; + if(!that._f)that._f = entry; + if(prev)prev.n = entry; + that[SIZE]++; + // add to index + if(index !== 'F')that._i[index] = entry; + } return that; + }, + getEntry: getEntry, + setStrong: function(C, NAME, IS_MAP){ + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + $iterDefine(C, NAME, function(iterated, kind){ + this._t = iterated; // target + this._k = kind; // kind + this._l = undefined; // previous + }, function(){ + var that = this + , kind = that._k + , entry = that._l; + // revert to the last existing entry + while(entry && entry.r)entry = entry.p; + // get next entry + if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ + // or finish the iteration + that._t = undefined; + return step(1); + } + // return step by kind + if(kind == 'keys' )return step(0, entry.k); + if(kind == 'values')return step(0, entry.v); + return step(0, [entry.k, entry.v]); + }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); + + // add [@@species], 23.1.2.2, 23.2.2.2 + setSpecies(NAME); + } + }; + +/***/ }, +/* 213 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4) + , $export = __webpack_require__(8) + , redefine = __webpack_require__(18) + , redefineAll = __webpack_require__(210) + , meta = __webpack_require__(22) + , forOf = __webpack_require__(206) + , anInstance = __webpack_require__(205) + , isObject = __webpack_require__(13) + , fails = __webpack_require__(7) + , $iterDetect = __webpack_require__(165) + , setToStringTag = __webpack_require__(24) + , inheritIfRequired = __webpack_require__(88); + + module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ + var Base = global[NAME] + , C = Base + , ADDER = IS_MAP ? 'set' : 'add' + , proto = C && C.prototype + , O = {}; + var fixMethod = function(KEY){ + var fn = proto[KEY]; + redefine(proto, KEY, + KEY == 'delete' ? function(a){ + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'has' ? function has(a){ + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'get' ? function get(a){ + return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; } + : function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; } + ); + }; + if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ + new C().entries().next(); + }))){ + // create collection constructor + C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); + redefineAll(C.prototype, methods); + meta.NEED = true; + } else { + var instance = new C + // early implementations not supports chaining + , HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + , THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); }) + // most early implementations doesn't supports iterables, most modern - not close it correctly + , ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new + // for early implementations -0 and +0 not the same + , BUGGY_ZERO = !IS_WEAK && fails(function(){ + // V8 ~ Chromium 42- fails only with 5+ elements + var $instance = new C() + , index = 5; + while(index--)$instance[ADDER](index, index); + return !$instance.has(-0); + }); + if(!ACCEPT_ITERABLES){ + C = wrapper(function(target, iterable){ + anInstance(target, C, NAME); + var that = inheritIfRequired(new Base, target, C); + if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); + return that; + }); + C.prototype = proto; + proto.constructor = C; + } + if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){ + fixMethod('delete'); + fixMethod('has'); + IS_MAP && fixMethod('get'); + } + if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER); + // weak collections should not contains .clear method + if(IS_WEAK && proto.clear)delete proto.clear; + } + + setToStringTag(C, NAME); + + O[NAME] = C; + $export($export.G + $export.W + $export.F * (C != Base), O); + + if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); + + return C; + }; + +/***/ }, +/* 214 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(212); + + // 23.2 Set Objects + module.exports = __webpack_require__(213)('Set', function(get){ + return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.2.3.1 Set.prototype.add(value) + add: function add(value){ + return strong.def(this, value = value === 0 ? 0 : value, value); + } + }, strong); + +/***/ }, +/* 215 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var each = __webpack_require__(172)(0) + , redefine = __webpack_require__(18) + , meta = __webpack_require__(22) + , assign = __webpack_require__(69) + , weak = __webpack_require__(216) + , isObject = __webpack_require__(13) + , getWeak = meta.getWeak + , isExtensible = Object.isExtensible + , uncaughtFrozenStore = weak.ufstore + , tmp = {} + , InternalMap; + + var wrapper = function(get){ + return function WeakMap(){ + return get(this, arguments.length > 0 ? arguments[0] : undefined); + }; + }; + + var methods = { + // 23.3.3.3 WeakMap.prototype.get(key) + get: function get(key){ + if(isObject(key)){ + var data = getWeak(key); + if(data === true)return uncaughtFrozenStore(this).get(key); + return data ? data[this._i] : undefined; + } + }, + // 23.3.3.5 WeakMap.prototype.set(key, value) + set: function set(key, value){ + return weak.def(this, key, value); + } + }; + + // 23.3 WeakMap Objects + var $WeakMap = module.exports = __webpack_require__(213)('WeakMap', wrapper, methods, weak, true, true); + + // IE11 WeakMap frozen keys fix + if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ + InternalMap = weak.getConstructor(wrapper); + assign(InternalMap.prototype, methods); + meta.NEED = true; + each(['delete', 'has', 'get', 'set'], function(key){ + var proto = $WeakMap.prototype + , method = proto[key]; + redefine(proto, key, function(a, b){ + // store frozen objects on internal weakmap shim + if(isObject(a) && !isExtensible(a)){ + if(!this._f)this._f = new InternalMap; + var result = this._f[key](a, b); + return key == 'set' ? this : result; + // store all the rest on native weakmap + } return method.call(this, a, b); + }); + }); + } + +/***/ }, +/* 216 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var redefineAll = __webpack_require__(210) + , getWeak = __webpack_require__(22).getWeak + , anObject = __webpack_require__(12) + , isObject = __webpack_require__(13) + , anInstance = __webpack_require__(205) + , forOf = __webpack_require__(206) + , createArrayMethod = __webpack_require__(172) + , $has = __webpack_require__(5) + , arrayFind = createArrayMethod(5) + , arrayFindIndex = createArrayMethod(6) + , id = 0; + + // fallback for uncaught frozen keys + var uncaughtFrozenStore = function(that){ + return that._l || (that._l = new UncaughtFrozenStore); + }; + var UncaughtFrozenStore = function(){ + this.a = []; + }; + var findUncaughtFrozen = function(store, key){ + return arrayFind(store.a, function(it){ + return it[0] === key; + }); + }; + UncaughtFrozenStore.prototype = { + get: function(key){ + var entry = findUncaughtFrozen(this, key); + if(entry)return entry[1]; + }, + has: function(key){ + return !!findUncaughtFrozen(this, key); + }, + set: function(key, value){ + var entry = findUncaughtFrozen(this, key); + if(entry)entry[1] = value; + else this.a.push([key, value]); + }, + 'delete': function(key){ + var index = arrayFindIndex(this.a, function(it){ + return it[0] === key; + }); + if(~index)this.a.splice(index, 1); + return !!~index; + } + }; + + module.exports = { + getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ + var C = wrapper(function(that, iterable){ + anInstance(that, C, NAME, '_i'); + that._i = id++; // collection id + that._l = undefined; // leak store for uncaught frozen objects + if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.3.3.2 WeakMap.prototype.delete(key) + // 23.4.3.3 WeakSet.prototype.delete(value) + 'delete': function(key){ + if(!isObject(key))return false; + var data = getWeak(key); + if(data === true)return uncaughtFrozenStore(this)['delete'](key); + return data && $has(data, this._i) && delete data[this._i]; + }, + // 23.3.3.4 WeakMap.prototype.has(key) + // 23.4.3.4 WeakSet.prototype.has(value) + has: function has(key){ + if(!isObject(key))return false; + var data = getWeak(key); + if(data === true)return uncaughtFrozenStore(this).has(key); + return data && $has(data, this._i); + } + }); + return C; + }, + def: function(that, key, value){ + var data = getWeak(anObject(key), true); + if(data === true)uncaughtFrozenStore(that).set(key, value); + else data[that._i] = value; + return that; + }, + ufstore: uncaughtFrozenStore + }; + +/***/ }, +/* 217 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var weak = __webpack_require__(216); + + // 23.4 WeakSet Objects + __webpack_require__(213)('WeakSet', function(get){ + return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.4.3.1 WeakSet.prototype.add(value) + add: function add(value){ + return weak.def(this, value, true); + } + }, weak, false, true); + +/***/ }, +/* 218 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , $typed = __webpack_require__(219) + , buffer = __webpack_require__(220) + , anObject = __webpack_require__(12) + , toIndex = __webpack_require__(39) + , toLength = __webpack_require__(37) + , isObject = __webpack_require__(13) + , ArrayBuffer = __webpack_require__(4).ArrayBuffer + , speciesConstructor = __webpack_require__(207) + , $ArrayBuffer = buffer.ArrayBuffer + , $DataView = buffer.DataView + , $isView = $typed.ABV && ArrayBuffer.isView + , $slice = $ArrayBuffer.prototype.slice + , VIEW = $typed.VIEW + , ARRAY_BUFFER = 'ArrayBuffer'; + + $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer}); + + $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { + // 24.1.3.1 ArrayBuffer.isView(arg) + isView: function isView(it){ + return $isView && $isView(it) || isObject(it) && VIEW in it; + } + }); + + $export($export.P + $export.U + $export.F * __webpack_require__(7)(function(){ + return !new $ArrayBuffer(2).slice(1, undefined).byteLength; + }), ARRAY_BUFFER, { + // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) + slice: function slice(start, end){ + if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix + var len = anObject(this).byteLength + , first = toIndex(start, len) + , final = toIndex(end === undefined ? len : end, len) + , result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first)) + , viewS = new $DataView(this) + , viewT = new $DataView(result) + , index = 0; + while(first < final){ + viewT.setUint8(index++, viewS.getUint8(first++)); + } return result; + } + }); + + __webpack_require__(192)(ARRAY_BUFFER); + +/***/ }, +/* 219 */ +/***/ function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4) + , hide = __webpack_require__(10) + , uid = __webpack_require__(19) + , TYPED = uid('typed_array') + , VIEW = uid('view') + , ABV = !!(global.ArrayBuffer && global.DataView) + , CONSTR = ABV + , i = 0, l = 9, Typed; + + var TypedArrayConstructors = ( + 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' + ).split(','); + + while(i < l){ + if(Typed = global[TypedArrayConstructors[i++]]){ + hide(Typed.prototype, TYPED, true); + hide(Typed.prototype, VIEW, true); + } else CONSTR = false; + } + + module.exports = { + ABV: ABV, + CONSTR: CONSTR, + TYPED: TYPED, + VIEW: VIEW + }; + +/***/ }, +/* 220 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4) + , DESCRIPTORS = __webpack_require__(6) + , LIBRARY = __webpack_require__(28) + , $typed = __webpack_require__(219) + , hide = __webpack_require__(10) + , redefineAll = __webpack_require__(210) + , fails = __webpack_require__(7) + , anInstance = __webpack_require__(205) + , toInteger = __webpack_require__(38) + , toLength = __webpack_require__(37) + , gOPN = __webpack_require__(50).f + , dP = __webpack_require__(11).f + , arrayFill = __webpack_require__(188) + , setToStringTag = __webpack_require__(24) + , ARRAY_BUFFER = 'ArrayBuffer' + , DATA_VIEW = 'DataView' + , PROTOTYPE = 'prototype' + , WRONG_LENGTH = 'Wrong length!' + , WRONG_INDEX = 'Wrong index!' + , $ArrayBuffer = global[ARRAY_BUFFER] + , $DataView = global[DATA_VIEW] + , Math = global.Math + , RangeError = global.RangeError + , Infinity = global.Infinity + , BaseBuffer = $ArrayBuffer + , abs = Math.abs + , pow = Math.pow + , floor = Math.floor + , log = Math.log + , LN2 = Math.LN2 + , BUFFER = 'buffer' + , BYTE_LENGTH = 'byteLength' + , BYTE_OFFSET = 'byteOffset' + , $BUFFER = DESCRIPTORS ? '_b' : BUFFER + , $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH + , $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; + + // IEEE754 conversions based on https://github.com/feross/ieee754 + var packIEEE754 = function(value, mLen, nBytes){ + var buffer = Array(nBytes) + , eLen = nBytes * 8 - mLen - 1 + , eMax = (1 << eLen) - 1 + , eBias = eMax >> 1 + , rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0 + , i = 0 + , s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0 + , e, m, c; + value = abs(value) + if(value != value || value === Infinity){ + m = value != value ? 1 : 0; + e = eMax; + } else { + e = floor(log(value) / LN2); + if(value * (c = pow(2, -e)) < 1){ + e--; + c *= 2; + } + if(e + eBias >= 1){ + value += rt / c; + } else { + value += rt * pow(2, 1 - eBias); + } + if(value * c >= 2){ + e++; + c /= 2; + } + if(e + eBias >= eMax){ + m = 0; + e = eMax; + } else if(e + eBias >= 1){ + m = (value * c - 1) * pow(2, mLen); + e = e + eBias; + } else { + m = value * pow(2, eBias - 1) * pow(2, mLen); + e = 0; + } + } + for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); + e = e << mLen | m; + eLen += mLen; + for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); + buffer[--i] |= s * 128; + return buffer; + }; + var unpackIEEE754 = function(buffer, mLen, nBytes){ + var eLen = nBytes * 8 - mLen - 1 + , eMax = (1 << eLen) - 1 + , eBias = eMax >> 1 + , nBits = eLen - 7 + , i = nBytes - 1 + , s = buffer[i--] + , e = s & 127 + , m; + s >>= 7; + for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); + if(e === 0){ + e = 1 - eBias; + } else if(e === eMax){ + return m ? NaN : s ? -Infinity : Infinity; + } else { + m = m + pow(2, mLen); + e = e - eBias; + } return (s ? -1 : 1) * m * pow(2, e - mLen); + }; + + var unpackI32 = function(bytes){ + return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; + }; + var packI8 = function(it){ + return [it & 0xff]; + }; + var packI16 = function(it){ + return [it & 0xff, it >> 8 & 0xff]; + }; + var packI32 = function(it){ + return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; + }; + var packF64 = function(it){ + return packIEEE754(it, 52, 8); + }; + var packF32 = function(it){ + return packIEEE754(it, 23, 4); + }; + + var addGetter = function(C, key, internal){ + dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }}); + }; + + var get = function(view, bytes, index, isLittleEndian){ + var numIndex = +index + , intIndex = toInteger(numIndex); + if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b + , start = intIndex + view[$OFFSET] + , pack = store.slice(start, start + bytes); + return isLittleEndian ? pack : pack.reverse(); + }; + var set = function(view, bytes, index, conversion, value, isLittleEndian){ + var numIndex = +index + , intIndex = toInteger(numIndex); + if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b + , start = intIndex + view[$OFFSET] + , pack = conversion(+value); + for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; + }; + + var validateArrayBufferArguments = function(that, length){ + anInstance(that, $ArrayBuffer, ARRAY_BUFFER); + var numberLength = +length + , byteLength = toLength(numberLength); + if(numberLength != byteLength)throw RangeError(WRONG_LENGTH); + return byteLength; + }; + + if(!$typed.ABV){ + $ArrayBuffer = function ArrayBuffer(length){ + var byteLength = validateArrayBufferArguments(this, length); + this._b = arrayFill.call(Array(byteLength), 0); + this[$LENGTH] = byteLength; + }; + + $DataView = function DataView(buffer, byteOffset, byteLength){ + anInstance(this, $DataView, DATA_VIEW); + anInstance(buffer, $ArrayBuffer, DATA_VIEW); + var bufferLength = buffer[$LENGTH] + , offset = toInteger(byteOffset); + if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH); + this[$BUFFER] = buffer; + this[$OFFSET] = offset; + this[$LENGTH] = byteLength; + }; + + if(DESCRIPTORS){ + addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); + addGetter($DataView, BUFFER, '_b'); + addGetter($DataView, BYTE_LENGTH, '_l'); + addGetter($DataView, BYTE_OFFSET, '_o'); + } + + redefineAll($DataView[PROTOTYPE], { + getInt8: function getInt8(byteOffset){ + return get(this, 1, byteOffset)[0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset){ + return get(this, 1, byteOffset)[0]; + }, + getInt16: function getInt16(byteOffset /*, littleEndian */){ + var bytes = get(this, 2, byteOffset, arguments[1]); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /*, littleEndian */){ + var bytes = get(this, 2, byteOffset, arguments[1]); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /*, littleEndian */){ + return unpackI32(get(this, 4, byteOffset, arguments[1])); + }, + getUint32: function getUint32(byteOffset /*, littleEndian */){ + return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /*, littleEndian */){ + return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); + }, + getFloat64: function getFloat64(byteOffset /*, littleEndian */){ + return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); + }, + setInt8: function setInt8(byteOffset, value){ + set(this, 1, byteOffset, packI8, value); + }, + setUint8: function setUint8(byteOffset, value){ + set(this, 1, byteOffset, packI8, value); + }, + setInt16: function setInt16(byteOffset, value /*, littleEndian */){ + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setUint16: function setUint16(byteOffset, value /*, littleEndian */){ + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setInt32: function setInt32(byteOffset, value /*, littleEndian */){ + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setUint32: function setUint32(byteOffset, value /*, littleEndian */){ + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){ + set(this, 4, byteOffset, packF32, value, arguments[2]); + }, + setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){ + set(this, 8, byteOffset, packF64, value, arguments[2]); + } + }); + } else { + if(!fails(function(){ + new $ArrayBuffer; // eslint-disable-line no-new + }) || !fails(function(){ + new $ArrayBuffer(.5); // eslint-disable-line no-new + })){ + $ArrayBuffer = function ArrayBuffer(length){ + return new BaseBuffer(validateArrayBufferArguments(this, length)); + }; + var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; + for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){ + if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]); + }; + if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer; + } + // iOS Safari 7.x bug + var view = new $DataView(new $ArrayBuffer(2)) + , $setInt8 = $DataView[PROTOTYPE].setInt8; + view.setInt8(0, 2147483648); + view.setInt8(1, 2147483649); + if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], { + setInt8: function setInt8(byteOffset, value){ + $setInt8.call(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value){ + $setInt8.call(this, byteOffset, value << 24 >> 24); + } + }, true); + } + setToStringTag($ArrayBuffer, ARRAY_BUFFER); + setToStringTag($DataView, DATA_VIEW); + hide($DataView[PROTOTYPE], $typed.VIEW, true); + exports[ARRAY_BUFFER] = $ArrayBuffer; + exports[DATA_VIEW] = $DataView; + +/***/ }, +/* 221 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + $export($export.G + $export.W + $export.F * !__webpack_require__(219).ABV, { + DataView: __webpack_require__(220).DataView + }); + +/***/ }, +/* 222 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Int8', 1, function(init){ + return function Int8Array(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }); + +/***/ }, +/* 223 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + if(__webpack_require__(6)){ + var LIBRARY = __webpack_require__(28) + , global = __webpack_require__(4) + , fails = __webpack_require__(7) + , $export = __webpack_require__(8) + , $typed = __webpack_require__(219) + , $buffer = __webpack_require__(220) + , ctx = __webpack_require__(20) + , anInstance = __webpack_require__(205) + , propertyDesc = __webpack_require__(17) + , hide = __webpack_require__(10) + , redefineAll = __webpack_require__(210) + , toInteger = __webpack_require__(38) + , toLength = __webpack_require__(37) + , toIndex = __webpack_require__(39) + , toPrimitive = __webpack_require__(16) + , has = __webpack_require__(5) + , same = __webpack_require__(71) + , classof = __webpack_require__(75) + , isObject = __webpack_require__(13) + , toObject = __webpack_require__(58) + , isArrayIter = __webpack_require__(162) + , create = __webpack_require__(46) + , getPrototypeOf = __webpack_require__(59) + , gOPN = __webpack_require__(50).f + , getIterFn = __webpack_require__(164) + , uid = __webpack_require__(19) + , wks = __webpack_require__(25) + , createArrayMethod = __webpack_require__(172) + , createArrayIncludes = __webpack_require__(36) + , speciesConstructor = __webpack_require__(207) + , ArrayIterators = __webpack_require__(193) + , Iterators = __webpack_require__(129) + , $iterDetect = __webpack_require__(165) + , setSpecies = __webpack_require__(192) + , arrayFill = __webpack_require__(188) + , arrayCopyWithin = __webpack_require__(185) + , $DP = __webpack_require__(11) + , $GOPD = __webpack_require__(51) + , dP = $DP.f + , gOPD = $GOPD.f + , RangeError = global.RangeError + , TypeError = global.TypeError + , Uint8Array = global.Uint8Array + , ARRAY_BUFFER = 'ArrayBuffer' + , SHARED_BUFFER = 'Shared' + ARRAY_BUFFER + , BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT' + , PROTOTYPE = 'prototype' + , ArrayProto = Array[PROTOTYPE] + , $ArrayBuffer = $buffer.ArrayBuffer + , $DataView = $buffer.DataView + , arrayForEach = createArrayMethod(0) + , arrayFilter = createArrayMethod(2) + , arraySome = createArrayMethod(3) + , arrayEvery = createArrayMethod(4) + , arrayFind = createArrayMethod(5) + , arrayFindIndex = createArrayMethod(6) + , arrayIncludes = createArrayIncludes(true) + , arrayIndexOf = createArrayIncludes(false) + , arrayValues = ArrayIterators.values + , arrayKeys = ArrayIterators.keys + , arrayEntries = ArrayIterators.entries + , arrayLastIndexOf = ArrayProto.lastIndexOf + , arrayReduce = ArrayProto.reduce + , arrayReduceRight = ArrayProto.reduceRight + , arrayJoin = ArrayProto.join + , arraySort = ArrayProto.sort + , arraySlice = ArrayProto.slice + , arrayToString = ArrayProto.toString + , arrayToLocaleString = ArrayProto.toLocaleString + , ITERATOR = wks('iterator') + , TAG = wks('toStringTag') + , TYPED_CONSTRUCTOR = uid('typed_constructor') + , DEF_CONSTRUCTOR = uid('def_constructor') + , ALL_CONSTRUCTORS = $typed.CONSTR + , TYPED_ARRAY = $typed.TYPED + , VIEW = $typed.VIEW + , WRONG_LENGTH = 'Wrong length!'; + + var $map = createArrayMethod(1, function(O, length){ + return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); + }); + + var LITTLE_ENDIAN = fails(function(){ + return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + }); + + var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){ + new Uint8Array(1).set({}); + }); + + var strictToLength = function(it, SAME){ + if(it === undefined)throw TypeError(WRONG_LENGTH); + var number = +it + , length = toLength(it); + if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH); + return length; + }; + + var toOffset = function(it, BYTES){ + var offset = toInteger(it); + if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!'); + return offset; + }; + + var validate = function(it){ + if(isObject(it) && TYPED_ARRAY in it)return it; + throw TypeError(it + ' is not a typed array!'); + }; + + var allocate = function(C, length){ + if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){ + throw TypeError('It is not a typed array constructor!'); + } return new C(length); + }; + + var speciesFromList = function(O, list){ + return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); + }; + + var fromList = function(C, list){ + var index = 0 + , length = list.length + , result = allocate(C, length); + while(length > index)result[index] = list[index++]; + return result; + }; + + var addGetter = function(it, key, internal){ + dP(it, key, {get: function(){ return this._d[internal]; }}); + }; + + var $from = function from(source /*, mapfn, thisArg */){ + var O = toObject(source) + , aLen = arguments.length + , mapfn = aLen > 1 ? arguments[1] : undefined + , mapping = mapfn !== undefined + , iterFn = getIterFn(O) + , i, length, values, result, step, iterator; + if(iterFn != undefined && !isArrayIter(iterFn)){ + for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){ + values.push(step.value); + } O = values; + } + if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2); + for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){ + result[i] = mapping ? mapfn(O[i], i) : O[i]; + } + return result; + }; + + var $of = function of(/*...items*/){ + var index = 0 + , length = arguments.length + , result = allocate(this, length); + while(length > index)result[index] = arguments[index++]; + return result; + }; + + // iOS Safari 6.x fails here + var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); }); + + var $toLocaleString = function toLocaleString(){ + return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); + }; + + var proto = { + copyWithin: function copyWithin(target, start /*, end */){ + return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); + }, + every: function every(callbackfn /*, thisArg */){ + return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars + return arrayFill.apply(validate(this), arguments); + }, + filter: function filter(callbackfn /*, thisArg */){ + return speciesFromList(this, arrayFilter(validate(this), callbackfn, + arguments.length > 1 ? arguments[1] : undefined)); + }, + find: function find(predicate /*, thisArg */){ + return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + findIndex: function findIndex(predicate /*, thisArg */){ + return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + forEach: function forEach(callbackfn /*, thisArg */){ + arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + indexOf: function indexOf(searchElement /*, fromIndex */){ + return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + includes: function includes(searchElement /*, fromIndex */){ + return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + join: function join(separator){ // eslint-disable-line no-unused-vars + return arrayJoin.apply(validate(this), arguments); + }, + lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars + return arrayLastIndexOf.apply(validate(this), arguments); + }, + map: function map(mapfn /*, thisArg */){ + return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); + }, + reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars + return arrayReduce.apply(validate(this), arguments); + }, + reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars + return arrayReduceRight.apply(validate(this), arguments); + }, + reverse: function reverse(){ + var that = this + , length = validate(that).length + , middle = Math.floor(length / 2) + , index = 0 + , value; + while(index < middle){ + value = that[index]; + that[index++] = that[--length]; + that[length] = value; + } return that; + }, + some: function some(callbackfn /*, thisArg */){ + return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + sort: function sort(comparefn){ + return arraySort.call(validate(this), comparefn); + }, + subarray: function subarray(begin, end){ + var O = validate(this) + , length = O.length + , $begin = toIndex(begin, length); + return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( + O.buffer, + O.byteOffset + $begin * O.BYTES_PER_ELEMENT, + toLength((end === undefined ? length : toIndex(end, length)) - $begin) + ); + } + }; + + var $slice = function slice(start, end){ + return speciesFromList(this, arraySlice.call(validate(this), start, end)); + }; + + var $set = function set(arrayLike /*, offset */){ + validate(this); + var offset = toOffset(arguments[1], 1) + , length = this.length + , src = toObject(arrayLike) + , len = toLength(src.length) + , index = 0; + if(len + offset > length)throw RangeError(WRONG_LENGTH); + while(index < len)this[offset + index] = src[index++]; + }; + + var $iterators = { + entries: function entries(){ + return arrayEntries.call(validate(this)); + }, + keys: function keys(){ + return arrayKeys.call(validate(this)); + }, + values: function values(){ + return arrayValues.call(validate(this)); + } + }; + + var isTAIndex = function(target, key){ + return isObject(target) + && target[TYPED_ARRAY] + && typeof key != 'symbol' + && key in target + && String(+key) == String(key); + }; + var $getDesc = function getOwnPropertyDescriptor(target, key){ + return isTAIndex(target, key = toPrimitive(key, true)) + ? propertyDesc(2, target[key]) + : gOPD(target, key); + }; + var $setDesc = function defineProperty(target, key, desc){ + if(isTAIndex(target, key = toPrimitive(key, true)) + && isObject(desc) + && has(desc, 'value') + && !has(desc, 'get') + && !has(desc, 'set') + // TODO: add validation descriptor w/o calling accessors + && !desc.configurable + && (!has(desc, 'writable') || desc.writable) + && (!has(desc, 'enumerable') || desc.enumerable) + ){ + target[key] = desc.value; + return target; + } else return dP(target, key, desc); + }; + + if(!ALL_CONSTRUCTORS){ + $GOPD.f = $getDesc; + $DP.f = $setDesc; + } + + $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { + getOwnPropertyDescriptor: $getDesc, + defineProperty: $setDesc + }); + + if(fails(function(){ arrayToString.call({}); })){ + arrayToString = arrayToLocaleString = function toString(){ + return arrayJoin.call(this); + } + } + + var $TypedArrayPrototype$ = redefineAll({}, proto); + redefineAll($TypedArrayPrototype$, $iterators); + hide($TypedArrayPrototype$, ITERATOR, $iterators.values); + redefineAll($TypedArrayPrototype$, { + slice: $slice, + set: $set, + constructor: function(){ /* noop */ }, + toString: arrayToString, + toLocaleString: $toLocaleString + }); + addGetter($TypedArrayPrototype$, 'buffer', 'b'); + addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); + addGetter($TypedArrayPrototype$, 'byteLength', 'l'); + addGetter($TypedArrayPrototype$, 'length', 'e'); + dP($TypedArrayPrototype$, TAG, { + get: function(){ return this[TYPED_ARRAY]; } + }); + + module.exports = function(KEY, BYTES, wrapper, CLAMPED){ + CLAMPED = !!CLAMPED; + var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array' + , ISNT_UINT8 = NAME != 'Uint8Array' + , GETTER = 'get' + KEY + , SETTER = 'set' + KEY + , TypedArray = global[NAME] + , Base = TypedArray || {} + , TAC = TypedArray && getPrototypeOf(TypedArray) + , FORCED = !TypedArray || !$typed.ABV + , O = {} + , TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; + var getter = function(that, index){ + var data = that._d; + return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); + }; + var setter = function(that, index, value){ + var data = that._d; + if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; + data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); + }; + var addElement = function(that, index){ + dP(that, index, { + get: function(){ + return getter(this, index); + }, + set: function(value){ + return setter(this, index, value); + }, + enumerable: true + }); + }; + if(FORCED){ + TypedArray = wrapper(function(that, data, $offset, $length){ + anInstance(that, TypedArray, NAME, '_d'); + var index = 0 + , offset = 0 + , buffer, byteLength, length, klass; + if(!isObject(data)){ + length = strictToLength(data, true) + byteLength = length * BYTES; + buffer = new $ArrayBuffer(byteLength); + } else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ + buffer = data; + offset = toOffset($offset, BYTES); + var $len = data.byteLength; + if($length === undefined){ + if($len % BYTES)throw RangeError(WRONG_LENGTH); + byteLength = $len - offset; + if(byteLength < 0)throw RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if(TYPED_ARRAY in data){ + return fromList(TypedArray, data); + } else { + return $from.call(TypedArray, data); + } + hide(that, '_d', { + b: buffer, + o: offset, + l: byteLength, + e: length, + v: new $DataView(buffer) + }); + while(index < length)addElement(that, index++); + }); + TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); + hide(TypedArrayPrototype, 'constructor', TypedArray); + } else if(!$iterDetect(function(iter){ + // V8 works with iterators, but fails in many other cases + // https://code.google.com/p/v8/issues/detail?id=4552 + new TypedArray(null); // eslint-disable-line no-new + new TypedArray(iter); // eslint-disable-line no-new + }, true)){ + TypedArray = wrapper(function(that, data, $offset, $length){ + anInstance(that, TypedArray, NAME); + var klass; + // `ws` module bug, temporarily remove validation length for Uint8Array + // https://github.com/websockets/ws/pull/645 + if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8)); + if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ + return $length !== undefined + ? new Base(data, toOffset($offset, BYTES), $length) + : $offset !== undefined + ? new Base(data, toOffset($offset, BYTES)) + : new Base(data); + } + if(TYPED_ARRAY in data)return fromList(TypedArray, data); + return $from.call(TypedArray, data); + }); + arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){ + if(!(key in TypedArray))hide(TypedArray, key, Base[key]); + }); + TypedArray[PROTOTYPE] = TypedArrayPrototype; + if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray; + } + var $nativeIterator = TypedArrayPrototype[ITERATOR] + , CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined) + , $iterator = $iterators.values; + hide(TypedArray, TYPED_CONSTRUCTOR, true); + hide(TypedArrayPrototype, TYPED_ARRAY, NAME); + hide(TypedArrayPrototype, VIEW, true); + hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); + + if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){ + dP(TypedArrayPrototype, TAG, { + get: function(){ return NAME; } + }); + } + + O[NAME] = TypedArray; + + $export($export.G + $export.W + $export.F * (TypedArray != Base), O); + + $export($export.S, NAME, { + BYTES_PER_ELEMENT: BYTES, + from: $from, + of: $of + }); + + if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); + + $export($export.P, NAME, proto); + + setSpecies(NAME); + + $export($export.P + $export.F * FORCED_SET, NAME, {set: $set}); + + $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); + + $export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString}); + + $export($export.P + $export.F * fails(function(){ + new TypedArray(1).slice(); + }), NAME, {slice: $slice}); + + $export($export.P + $export.F * (fails(function(){ + return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString() + }) || !fails(function(){ + TypedArrayPrototype.toLocaleString.call([1, 2]); + })), NAME, {toLocaleString: $toLocaleString}); + + Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; + if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator); + }; + } else module.exports = function(){ /* empty */ }; + +/***/ }, +/* 224 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Uint8', 1, function(init){ + return function Uint8Array(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }); + +/***/ }, +/* 225 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Uint8', 1, function(init){ + return function Uint8ClampedArray(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }, true); + +/***/ }, +/* 226 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Int16', 2, function(init){ + return function Int16Array(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }); + +/***/ }, +/* 227 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Uint16', 2, function(init){ + return function Uint16Array(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }); + +/***/ }, +/* 228 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Int32', 4, function(init){ + return function Int32Array(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }); + +/***/ }, +/* 229 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Uint32', 4, function(init){ + return function Uint32Array(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }); + +/***/ }, +/* 230 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Float32', 4, function(init){ + return function Float32Array(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }); + +/***/ }, +/* 231 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(223)('Float64', 8, function(init){ + return function Float64Array(data, byteOffset, length){ + return init(this, data, byteOffset, length); + }; + }); + +/***/ }, +/* 232 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) + var $export = __webpack_require__(8) + , aFunction = __webpack_require__(21) + , anObject = __webpack_require__(12) + , rApply = (__webpack_require__(4).Reflect || {}).apply + , fApply = Function.apply; + // MS Edge argumentsList argument is optional + $export($export.S + $export.F * !__webpack_require__(7)(function(){ + rApply(function(){}); + }), 'Reflect', { + apply: function apply(target, thisArgument, argumentsList){ + var T = aFunction(target) + , L = anObject(argumentsList); + return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); + } + }); + +/***/ }, +/* 233 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) + var $export = __webpack_require__(8) + , create = __webpack_require__(46) + , aFunction = __webpack_require__(21) + , anObject = __webpack_require__(12) + , isObject = __webpack_require__(13) + , fails = __webpack_require__(7) + , bind = __webpack_require__(77) + , rConstruct = (__webpack_require__(4).Reflect || {}).construct; + + // MS Edge supports only 2 arguments and argumentsList argument is optional + // FF Nightly sets third argument as `new.target`, but does not create `this` from it + var NEW_TARGET_BUG = fails(function(){ + function F(){} + return !(rConstruct(function(){}, [], F) instanceof F); + }); + var ARGS_BUG = !fails(function(){ + rConstruct(function(){}); + }); + + $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { + construct: function construct(Target, args /*, newTarget*/){ + aFunction(Target); + anObject(args); + var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); + if(ARGS_BUG && !NEW_TARGET_BUG)return rConstruct(Target, args, newTarget); + if(Target == newTarget){ + // w/o altered newTarget, optimization for 0-4 arguments + switch(args.length){ + case 0: return new Target; + case 1: return new Target(args[0]); + case 2: return new Target(args[0], args[1]); + case 3: return new Target(args[0], args[1], args[2]); + case 4: return new Target(args[0], args[1], args[2], args[3]); + } + // w/o altered newTarget, lot of arguments case + var $args = [null]; + $args.push.apply($args, args); + return new (bind.apply(Target, $args)); + } + // with altered newTarget, not support built-in constructors + var proto = newTarget.prototype + , instance = create(isObject(proto) ? proto : Object.prototype) + , result = Function.apply.call(Target, instance, args); + return isObject(result) ? result : instance; + } + }); + +/***/ }, +/* 234 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) + var dP = __webpack_require__(11) + , $export = __webpack_require__(8) + , anObject = __webpack_require__(12) + , toPrimitive = __webpack_require__(16); + + // MS Edge has broken Reflect.defineProperty - throwing instead of returning false + $export($export.S + $export.F * __webpack_require__(7)(function(){ + Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2}); + }), 'Reflect', { + defineProperty: function defineProperty(target, propertyKey, attributes){ + anObject(target); + propertyKey = toPrimitive(propertyKey, true); + anObject(attributes); + try { + dP.f(target, propertyKey, attributes); + return true; + } catch(e){ + return false; + } + } + }); + +/***/ }, +/* 235 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.4 Reflect.deleteProperty(target, propertyKey) + var $export = __webpack_require__(8) + , gOPD = __webpack_require__(51).f + , anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + deleteProperty: function deleteProperty(target, propertyKey){ + var desc = gOPD(anObject(target), propertyKey); + return desc && !desc.configurable ? false : delete target[propertyKey]; + } + }); + +/***/ }, +/* 236 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // 26.1.5 Reflect.enumerate(target) + var $export = __webpack_require__(8) + , anObject = __webpack_require__(12); + var Enumerate = function(iterated){ + this._t = anObject(iterated); // target + this._i = 0; // next index + var keys = this._k = [] // keys + , key; + for(key in iterated)keys.push(key); + }; + __webpack_require__(130)(Enumerate, 'Object', function(){ + var that = this + , keys = that._k + , key; + do { + if(that._i >= keys.length)return {value: undefined, done: true}; + } while(!((key = keys[that._i++]) in that._t)); + return {value: key, done: false}; + }); + + $export($export.S, 'Reflect', { + enumerate: function enumerate(target){ + return new Enumerate(target); + } + }); + +/***/ }, +/* 237 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.6 Reflect.get(target, propertyKey [, receiver]) + var gOPD = __webpack_require__(51) + , getPrototypeOf = __webpack_require__(59) + , has = __webpack_require__(5) + , $export = __webpack_require__(8) + , isObject = __webpack_require__(13) + , anObject = __webpack_require__(12); + + function get(target, propertyKey/*, receiver*/){ + var receiver = arguments.length < 3 ? target : arguments[2] + , desc, proto; + if(anObject(target) === receiver)return target[propertyKey]; + if(desc = gOPD.f(target, propertyKey))return has(desc, 'value') + ? desc.value + : desc.get !== undefined + ? desc.get.call(receiver) + : undefined; + if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver); + } + + $export($export.S, 'Reflect', {get: get}); + +/***/ }, +/* 238 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) + var gOPD = __webpack_require__(51) + , $export = __webpack_require__(8) + , anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ + return gOPD.f(anObject(target), propertyKey); + } + }); + +/***/ }, +/* 239 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.8 Reflect.getPrototypeOf(target) + var $export = __webpack_require__(8) + , getProto = __webpack_require__(59) + , anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getPrototypeOf: function getPrototypeOf(target){ + return getProto(anObject(target)); + } + }); + +/***/ }, +/* 240 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.9 Reflect.has(target, propertyKey) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { + has: function has(target, propertyKey){ + return propertyKey in target; + } + }); + +/***/ }, +/* 241 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.10 Reflect.isExtensible(target) + var $export = __webpack_require__(8) + , anObject = __webpack_require__(12) + , $isExtensible = Object.isExtensible; + + $export($export.S, 'Reflect', { + isExtensible: function isExtensible(target){ + anObject(target); + return $isExtensible ? $isExtensible(target) : true; + } + }); + +/***/ }, +/* 242 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.11 Reflect.ownKeys(target) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', {ownKeys: __webpack_require__(243)}); + +/***/ }, +/* 243 */ +/***/ function(module, exports, __webpack_require__) { + + // all object keys, includes non-enumerable and symbols + var gOPN = __webpack_require__(50) + , gOPS = __webpack_require__(43) + , anObject = __webpack_require__(12) + , Reflect = __webpack_require__(4).Reflect; + module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){ + var keys = gOPN.f(anObject(it)) + , getSymbols = gOPS.f; + return getSymbols ? keys.concat(getSymbols(it)) : keys; + }; + +/***/ }, +/* 244 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.12 Reflect.preventExtensions(target) + var $export = __webpack_require__(8) + , anObject = __webpack_require__(12) + , $preventExtensions = Object.preventExtensions; + + $export($export.S, 'Reflect', { + preventExtensions: function preventExtensions(target){ + anObject(target); + try { + if($preventExtensions)$preventExtensions(target); + return true; + } catch(e){ + return false; + } + } + }); + +/***/ }, +/* 245 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) + var dP = __webpack_require__(11) + , gOPD = __webpack_require__(51) + , getPrototypeOf = __webpack_require__(59) + , has = __webpack_require__(5) + , $export = __webpack_require__(8) + , createDesc = __webpack_require__(17) + , anObject = __webpack_require__(12) + , isObject = __webpack_require__(13); + + function set(target, propertyKey, V/*, receiver*/){ + var receiver = arguments.length < 4 ? target : arguments[3] + , ownDesc = gOPD.f(anObject(target), propertyKey) + , existingDescriptor, proto; + if(!ownDesc){ + if(isObject(proto = getPrototypeOf(target))){ + return set(proto, propertyKey, V, receiver); + } + ownDesc = createDesc(0); + } + if(has(ownDesc, 'value')){ + if(ownDesc.writable === false || !isObject(receiver))return false; + existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0); + existingDescriptor.value = V; + dP.f(receiver, propertyKey, existingDescriptor); + return true; + } + return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); + } + + $export($export.S, 'Reflect', {set: set}); + +/***/ }, +/* 246 */ +/***/ function(module, exports, __webpack_require__) { + + // 26.1.14 Reflect.setPrototypeOf(target, proto) + var $export = __webpack_require__(8) + , setProto = __webpack_require__(73); + + if(setProto)$export($export.S, 'Reflect', { + setPrototypeOf: function setPrototypeOf(target, proto){ + setProto.check(target, proto); + try { + setProto.set(target, proto); + return true; + } catch(e){ + return false; + } + } + }); + +/***/ }, +/* 247 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/Array.prototype.includes + var $export = __webpack_require__(8) + , $includes = __webpack_require__(36)(true); + + $export($export.P, 'Array', { + includes: function includes(el /*, fromIndex = 0 */){ + return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + __webpack_require__(186)('includes'); + +/***/ }, +/* 248 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/mathiasbynens/String.prototype.at + var $export = __webpack_require__(8) + , $at = __webpack_require__(127)(true); + + $export($export.P, 'String', { + at: function at(pos){ + return $at(this, pos); + } + }); + +/***/ }, +/* 249 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8) + , $pad = __webpack_require__(250); + + $export($export.P, 'String', { + padStart: function padStart(maxLength /*, fillString = ' ' */){ + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); + } + }); + +/***/ }, +/* 250 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-string-pad-start-end + var toLength = __webpack_require__(37) + , repeat = __webpack_require__(91) + , defined = __webpack_require__(35); + + module.exports = function(that, maxLength, fillString, left){ + var S = String(defined(that)) + , stringLength = S.length + , fillStr = fillString === undefined ? ' ' : String(fillString) + , intMaxLength = toLength(maxLength); + if(intMaxLength <= stringLength || fillStr == '')return S; + var fillLen = intMaxLength - stringLength + , stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); + if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen); + return left ? stringFiller + S : S + stringFiller; + }; + + +/***/ }, +/* 251 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8) + , $pad = __webpack_require__(250); + + $export($export.P, 'String', { + padEnd: function padEnd(maxLength /*, fillString = ' ' */){ + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); + } + }); + +/***/ }, +/* 252 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(83)('trimLeft', function($trim){ + return function trimLeft(){ + return $trim(this, 1); + }; + }, 'trimStart'); + +/***/ }, +/* 253 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(83)('trimRight', function($trim){ + return function trimRight(){ + return $trim(this, 2); + }; + }, 'trimEnd'); + +/***/ }, +/* 254 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/String.prototype.matchAll/ + var $export = __webpack_require__(8) + , defined = __webpack_require__(35) + , toLength = __webpack_require__(37) + , isRegExp = __webpack_require__(134) + , getFlags = __webpack_require__(196) + , RegExpProto = RegExp.prototype; + + var $RegExpStringIterator = function(regexp, string){ + this._r = regexp; + this._s = string; + }; + + __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next(){ + var match = this._r.exec(this._s); + return {value: match, done: match === null}; + }); + + $export($export.P, 'String', { + matchAll: function matchAll(regexp){ + defined(this); + if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!'); + var S = String(this) + , flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp) + , rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); + rx.lastIndex = toLength(regexp.lastIndex); + return new $RegExpStringIterator(rx, S); + } + }); + +/***/ }, +/* 255 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(27)('asyncIterator'); + +/***/ }, +/* 256 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(27)('observable'); + +/***/ }, +/* 257 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-getownpropertydescriptors + var $export = __webpack_require__(8) + , ownKeys = __webpack_require__(243) + , toIObject = __webpack_require__(32) + , gOPD = __webpack_require__(51) + , createProperty = __webpack_require__(163); + + $export($export.S, 'Object', { + getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ + var O = toIObject(object) + , getDesc = gOPD.f + , keys = ownKeys(O) + , result = {} + , i = 0 + , key; + while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key)); + return result; + } + }); + +/***/ }, +/* 258 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8) + , $values = __webpack_require__(259)(false); + + $export($export.S, 'Object', { + values: function values(it){ + return $values(it); + } + }); + +/***/ }, +/* 259 */ +/***/ function(module, exports, __webpack_require__) { + + var getKeys = __webpack_require__(30) + , toIObject = __webpack_require__(32) + , isEnum = __webpack_require__(44).f; + module.exports = function(isEntries){ + return function(it){ + var O = toIObject(it) + , keys = getKeys(O) + , length = keys.length + , i = 0 + , result = [] + , key; + while(length > i)if(isEnum.call(O, key = keys[i++])){ + result.push(isEntries ? [key, O[key]] : O[key]); + } return result; + }; + }; + +/***/ }, +/* 260 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8) + , $entries = __webpack_require__(259)(true); + + $export($export.S, 'Object', { + entries: function entries(it){ + return $entries(it); + } + }); + +/***/ }, +/* 261 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , toObject = __webpack_require__(58) + , aFunction = __webpack_require__(21) + , $defineProperty = __webpack_require__(11); + + // B.2.2.2 Object.prototype.__defineGetter__(P, getter) + __webpack_require__(6) && $export($export.P + __webpack_require__(262), 'Object', { + __defineGetter__: function __defineGetter__(P, getter){ + $defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true}); + } + }); + +/***/ }, +/* 262 */ +/***/ function(module, exports, __webpack_require__) { + + // Forced replacement prototype accessors methods + module.exports = __webpack_require__(28)|| !__webpack_require__(7)(function(){ + var K = Math.random(); + // In FF throws only define methods + __defineSetter__.call(null, K, function(){ /* empty */}); + delete __webpack_require__(4)[K]; + }); + +/***/ }, +/* 263 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , toObject = __webpack_require__(58) + , aFunction = __webpack_require__(21) + , $defineProperty = __webpack_require__(11); + + // B.2.2.3 Object.prototype.__defineSetter__(P, setter) + __webpack_require__(6) && $export($export.P + __webpack_require__(262), 'Object', { + __defineSetter__: function __defineSetter__(P, setter){ + $defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true}); + } + }); + +/***/ }, +/* 264 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , toObject = __webpack_require__(58) + , toPrimitive = __webpack_require__(16) + , getPrototypeOf = __webpack_require__(59) + , getOwnPropertyDescriptor = __webpack_require__(51).f; + + // B.2.2.4 Object.prototype.__lookupGetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(262), 'Object', { + __lookupGetter__: function __lookupGetter__(P){ + var O = toObject(this) + , K = toPrimitive(P, true) + , D; + do { + if(D = getOwnPropertyDescriptor(O, K))return D.get; + } while(O = getPrototypeOf(O)); + } + }); + +/***/ }, +/* 265 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8) + , toObject = __webpack_require__(58) + , toPrimitive = __webpack_require__(16) + , getPrototypeOf = __webpack_require__(59) + , getOwnPropertyDescriptor = __webpack_require__(51).f; + + // B.2.2.5 Object.prototype.__lookupSetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(262), 'Object', { + __lookupSetter__: function __lookupSetter__(P){ + var O = toObject(this) + , K = toPrimitive(P, true) + , D; + do { + if(D = getOwnPropertyDescriptor(O, K))return D.set; + } while(O = getPrototypeOf(O)); + } + }); + +/***/ }, +/* 266 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Map', {toJSON: __webpack_require__(267)('Map')}); + +/***/ }, +/* 267 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var classof = __webpack_require__(75) + , from = __webpack_require__(268); + module.exports = function(NAME){ + return function toJSON(){ + if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); + return from(this); + }; + }; + +/***/ }, +/* 268 */ +/***/ function(module, exports, __webpack_require__) { + + var forOf = __webpack_require__(206); + + module.exports = function(iter, ITERATOR){ + var result = []; + forOf(iter, false, result.push, result, ITERATOR); + return result; + }; + + +/***/ }, +/* 269 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Set', {toJSON: __webpack_require__(267)('Set')}); + +/***/ }, +/* 270 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/ljharb/proposal-global + var $export = __webpack_require__(8); + + $export($export.S, 'System', {global: __webpack_require__(4)}); + +/***/ }, +/* 271 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/ljharb/proposal-is-error + var $export = __webpack_require__(8) + , cof = __webpack_require__(34); + + $export($export.S, 'Error', { + isError: function isError(it){ + return cof(it) === 'Error'; + } + }); + +/***/ }, +/* 272 */ +/***/ function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + iaddh: function iaddh(x0, x1, y0, y1){ + var $x0 = x0 >>> 0 + , $x1 = x1 >>> 0 + , $y0 = y0 >>> 0; + return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; + } + }); + +/***/ }, +/* 273 */ +/***/ function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + isubh: function isubh(x0, x1, y0, y1){ + var $x0 = x0 >>> 0 + , $x1 = x1 >>> 0 + , $y0 = y0 >>> 0; + return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; + } + }); + +/***/ }, +/* 274 */ +/***/ function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + imulh: function imulh(u, v){ + var UINT16 = 0xffff + , $u = +u + , $v = +v + , u0 = $u & UINT16 + , v0 = $v & UINT16 + , u1 = $u >> 16 + , v1 = $v >> 16 + , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); + } + }); + +/***/ }, +/* 275 */ +/***/ function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + umulh: function umulh(u, v){ + var UINT16 = 0xffff + , $u = +u + , $v = +v + , u0 = $u & UINT16 + , v0 = $v & UINT16 + , u1 = $u >>> 16 + , v1 = $v >>> 16 + , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); + } + }); + +/***/ }, +/* 276 */ +/***/ function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , toMetaKey = metadata.key + , ordinaryDefineOwnMetadata = metadata.set; + + metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){ + ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); + }}); + +/***/ }, +/* 277 */ +/***/ function(module, exports, __webpack_require__) { + + var Map = __webpack_require__(211) + , $export = __webpack_require__(8) + , shared = __webpack_require__(23)('metadata') + , store = shared.store || (shared.store = new (__webpack_require__(215))); + + var getOrCreateMetadataMap = function(target, targetKey, create){ + var targetMetadata = store.get(target); + if(!targetMetadata){ + if(!create)return undefined; + store.set(target, targetMetadata = new Map); + } + var keyMetadata = targetMetadata.get(targetKey); + if(!keyMetadata){ + if(!create)return undefined; + targetMetadata.set(targetKey, keyMetadata = new Map); + } return keyMetadata; + }; + var ordinaryHasOwnMetadata = function(MetadataKey, O, P){ + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? false : metadataMap.has(MetadataKey); + }; + var ordinaryGetOwnMetadata = function(MetadataKey, O, P){ + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); + }; + var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){ + getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); + }; + var ordinaryOwnMetadataKeys = function(target, targetKey){ + var metadataMap = getOrCreateMetadataMap(target, targetKey, false) + , keys = []; + if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); }); + return keys; + }; + var toMetaKey = function(it){ + return it === undefined || typeof it == 'symbol' ? it : String(it); + }; + var exp = function(O){ + $export($export.S, 'Reflect', O); + }; + + module.exports = { + store: store, + map: getOrCreateMetadataMap, + has: ordinaryHasOwnMetadata, + get: ordinaryGetOwnMetadata, + set: ordinaryDefineOwnMetadata, + keys: ordinaryOwnMetadataKeys, + key: toMetaKey, + exp: exp + }; + +/***/ }, +/* 278 */ +/***/ function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , toMetaKey = metadata.key + , getOrCreateMetadataMap = metadata.map + , store = metadata.store; + + metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){ + var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]) + , metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); + if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false; + if(metadataMap.size)return true; + var targetMetadata = store.get(target); + targetMetadata['delete'](targetKey); + return !!targetMetadata.size || store['delete'](target); + }}); + +/***/ }, +/* 279 */ +/***/ function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , getPrototypeOf = __webpack_require__(59) + , ordinaryHasOwnMetadata = metadata.has + , ordinaryGetOwnMetadata = metadata.get + , toMetaKey = metadata.key; + + var ordinaryGetMetadata = function(MetadataKey, O, P){ + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P); + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; + }; + + metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){ + return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + }}); + +/***/ }, +/* 280 */ +/***/ function(module, exports, __webpack_require__) { + + var Set = __webpack_require__(214) + , from = __webpack_require__(268) + , metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , getPrototypeOf = __webpack_require__(59) + , ordinaryOwnMetadataKeys = metadata.keys + , toMetaKey = metadata.key; + + var ordinaryMetadataKeys = function(O, P){ + var oKeys = ordinaryOwnMetadataKeys(O, P) + , parent = getPrototypeOf(O); + if(parent === null)return oKeys; + var pKeys = ordinaryMetadataKeys(parent, P); + return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; + }; + + metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){ + return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + }}); + +/***/ }, +/* 281 */ +/***/ function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , ordinaryGetOwnMetadata = metadata.get + , toMetaKey = metadata.key; + + metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){ + return ordinaryGetOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + }}); + +/***/ }, +/* 282 */ +/***/ function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , ordinaryOwnMetadataKeys = metadata.keys + , toMetaKey = metadata.key; + + metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){ + return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + }}); + +/***/ }, +/* 283 */ +/***/ function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , getPrototypeOf = __webpack_require__(59) + , ordinaryHasOwnMetadata = metadata.has + , toMetaKey = metadata.key; + + var ordinaryHasMetadata = function(MetadataKey, O, P){ + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if(hasOwn)return true; + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; + }; + + metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){ + return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + }}); + +/***/ }, +/* 284 */ +/***/ function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , ordinaryHasOwnMetadata = metadata.has + , toMetaKey = metadata.key; + + metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){ + return ordinaryHasOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + }}); + +/***/ }, +/* 285 */ +/***/ function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(277) + , anObject = __webpack_require__(12) + , aFunction = __webpack_require__(21) + , toMetaKey = metadata.key + , ordinaryDefineOwnMetadata = metadata.set; + + metadata.exp({metadata: function metadata(metadataKey, metadataValue){ + return function decorator(target, targetKey){ + ordinaryDefineOwnMetadata( + metadataKey, metadataValue, + (targetKey !== undefined ? anObject : aFunction)(target), + toMetaKey(targetKey) + ); + }; + }}); + +/***/ }, +/* 286 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask + var $export = __webpack_require__(8) + , microtask = __webpack_require__(209)() + , process = __webpack_require__(4).process + , isNode = __webpack_require__(34)(process) == 'process'; + + $export($export.G, { + asap: function asap(fn){ + var domain = isNode && process.domain; + microtask(domain ? domain.bind(fn) : fn); + } + }); + +/***/ }, +/* 287 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/zenparsing/es-observable + var $export = __webpack_require__(8) + , global = __webpack_require__(4) + , core = __webpack_require__(9) + , microtask = __webpack_require__(209)() + , OBSERVABLE = __webpack_require__(25)('observable') + , aFunction = __webpack_require__(21) + , anObject = __webpack_require__(12) + , anInstance = __webpack_require__(205) + , redefineAll = __webpack_require__(210) + , hide = __webpack_require__(10) + , forOf = __webpack_require__(206) + , RETURN = forOf.RETURN; + + var getMethod = function(fn){ + return fn == null ? undefined : aFunction(fn); + }; + + var cleanupSubscription = function(subscription){ + var cleanup = subscription._c; + if(cleanup){ + subscription._c = undefined; + cleanup(); + } + }; + + var subscriptionClosed = function(subscription){ + return subscription._o === undefined; + }; + + var closeSubscription = function(subscription){ + if(!subscriptionClosed(subscription)){ + subscription._o = undefined; + cleanupSubscription(subscription); + } + }; + + var Subscription = function(observer, subscriber){ + anObject(observer); + this._c = undefined; + this._o = observer; + observer = new SubscriptionObserver(this); + try { + var cleanup = subscriber(observer) + , subscription = cleanup; + if(cleanup != null){ + if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); }; + else aFunction(cleanup); + this._c = cleanup; + } + } catch(e){ + observer.error(e); + return; + } if(subscriptionClosed(this))cleanupSubscription(this); + }; + + Subscription.prototype = redefineAll({}, { + unsubscribe: function unsubscribe(){ closeSubscription(this); } + }); + + var SubscriptionObserver = function(subscription){ + this._s = subscription; + }; + + SubscriptionObserver.prototype = redefineAll({}, { + next: function next(value){ + var subscription = this._s; + if(!subscriptionClosed(subscription)){ + var observer = subscription._o; + try { + var m = getMethod(observer.next); + if(m)return m.call(observer, value); + } catch(e){ + try { + closeSubscription(subscription); + } finally { + throw e; + } + } + } + }, + error: function error(value){ + var subscription = this._s; + if(subscriptionClosed(subscription))throw value; + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.error); + if(!m)throw value; + value = m.call(observer, value); + } catch(e){ + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + }, + complete: function complete(value){ + var subscription = this._s; + if(!subscriptionClosed(subscription)){ + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.complete); + value = m ? m.call(observer, value) : undefined; + } catch(e){ + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + } + } + }); + + var $Observable = function Observable(subscriber){ + anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); + }; + + redefineAll($Observable.prototype, { + subscribe: function subscribe(observer){ + return new Subscription(observer, this._f); + }, + forEach: function forEach(fn){ + var that = this; + return new (core.Promise || global.Promise)(function(resolve, reject){ + aFunction(fn); + var subscription = that.subscribe({ + next : function(value){ + try { + return fn(value); + } catch(e){ + reject(e); + subscription.unsubscribe(); + } + }, + error: reject, + complete: resolve + }); + }); + } + }); + + redefineAll($Observable, { + from: function from(x){ + var C = typeof this === 'function' ? this : $Observable; + var method = getMethod(anObject(x)[OBSERVABLE]); + if(method){ + var observable = anObject(method.call(x)); + return observable.constructor === C ? observable : new C(function(observer){ + return observable.subscribe(observer); + }); + } + return new C(function(observer){ + var done = false; + microtask(function(){ + if(!done){ + try { + if(forOf(x, false, function(it){ + observer.next(it); + if(done)return RETURN; + }) === RETURN)return; + } catch(e){ + if(done)throw e; + observer.error(e); + return; + } observer.complete(); + } + }); + return function(){ done = true; }; + }); + }, + of: function of(){ + for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++]; + return new (typeof this === 'function' ? this : $Observable)(function(observer){ + var done = false; + microtask(function(){ + if(!done){ + for(var i = 0; i < items.length; ++i){ + observer.next(items[i]); + if(done)return; + } observer.complete(); + } + }); + return function(){ done = true; }; + }); + } + }); + + hide($Observable.prototype, OBSERVABLE, function(){ return this; }); + + $export($export.G, {Observable: $Observable}); + + __webpack_require__(192)('Observable'); + +/***/ }, +/* 288 */ +/***/ function(module, exports, __webpack_require__) { + + // ie9- setTimeout & setInterval additional parameters fix + var global = __webpack_require__(4) + , $export = __webpack_require__(8) + , invoke = __webpack_require__(78) + , partial = __webpack_require__(289) + , navigator = global.navigator + , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check + var wrap = function(set){ + return MSIE ? function(fn, time /*, ...args */){ + return set(invoke( + partial, + [].slice.call(arguments, 2), + typeof fn == 'function' ? fn : Function(fn) + ), time); + } : set; + }; + $export($export.G + $export.B + $export.F * MSIE, { + setTimeout: wrap(global.setTimeout), + setInterval: wrap(global.setInterval) + }); + +/***/ }, +/* 289 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + var path = __webpack_require__(290) + , invoke = __webpack_require__(78) + , aFunction = __webpack_require__(21); + module.exports = function(/* ...pargs */){ + var fn = aFunction(this) + , length = arguments.length + , pargs = Array(length) + , i = 0 + , _ = path._ + , holder = false; + while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; + return function(/* ...args */){ + var that = this + , aLen = arguments.length + , j = 0, k = 0, args; + if(!holder && !aLen)return invoke(fn, pargs, that); + args = pargs.slice(); + if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; + while(aLen > k)args.push(arguments[k++]); + return invoke(fn, args, that); + }; + }; + +/***/ }, +/* 290 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = __webpack_require__(4); + +/***/ }, +/* 291 */ +/***/ function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8) + , $task = __webpack_require__(208); + $export($export.G + $export.B, { + setImmediate: $task.set, + clearImmediate: $task.clear + }); + +/***/ }, +/* 292 */ +/***/ function(module, exports, __webpack_require__) { + + var $iterators = __webpack_require__(193) + , redefine = __webpack_require__(18) + , global = __webpack_require__(4) + , hide = __webpack_require__(10) + , Iterators = __webpack_require__(129) + , wks = __webpack_require__(25) + , ITERATOR = wks('iterator') + , TO_STRING_TAG = wks('toStringTag') + , ArrayValues = Iterators.Array; + + for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ + var NAME = collections[i] + , Collection = global[NAME] + , proto = Collection && Collection.prototype + , key; + if(proto){ + if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues); + if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = ArrayValues; + for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true); + } + } + +/***/ }, +/* 293 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global, process) {/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ + + !(function(global) { + "use strict"; + + var hasOwn = Object.prototype.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + var inModule = typeof module === "object"; + var runtime = global.regeneratorRuntime; + if (runtime) { + if (inModule) { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; + } + // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + return; + } + + // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + runtime.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + prototype[method] = function(arg) { + return this._invoke(method, arg); + }; + }); + } + + runtime.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + runtime.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `value instanceof AwaitArgument` to determine if the yielded value is + // meant to be awaited. Some may consider the name of this method too + // cutesy, but they are curmudgeons. + runtime.awrap = function(arg) { + return new AwaitArgument(arg); + }; + + function AwaitArgument(arg) { + this.arg = arg; + } + + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value instanceof AwaitArgument) { + return Promise.resolve(value.arg).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return Promise.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } + + if (typeof process === "object" && process.domain) { + invoke = process.domain.bind(invoke); + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + runtime.async = function(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList) + ); + + return runtime.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + while (true) { + var delegate = context.delegate; + if (delegate) { + if (method === "return" || + (method === "throw" && delegate.iterator[method] === undefined)) { + // A return or throw (when the delegate iterator has no throw + // method) always terminates the yield* loop. + context.delegate = null; + + // If the delegate iterator has a return method, give it a + // chance to clean up. + var returnMethod = delegate.iterator["return"]; + if (returnMethod) { + var record = tryCatch(returnMethod, delegate.iterator, arg); + if (record.type === "throw") { + // If the return method threw an exception, let that + // exception prevail over the original return or throw. + method = "throw"; + arg = record.arg; + continue; + } + } + + if (method === "return") { + // Continue with the outer return, now that the delegate + // iterator has been terminated. + continue; + } + } + + var record = tryCatch( + delegate.iterator[method], + delegate.iterator, + arg + ); + + if (record.type === "throw") { + context.delegate = null; + + // Like returning generator.throw(uncaught), but without the + // overhead of an extra function call. + method = "throw"; + arg = record.arg; + continue; + } + + // Delegate generator ran and handled its own exceptions so + // regardless of what the method was, we continue as if it is + // "next" with an undefined arg. + method = "next"; + arg = undefined; + + var info = record.arg; + if (info.done) { + context[delegate.resultName] = info.value; + context.next = delegate.nextLoc; + } else { + state = GenStateSuspendedYield; + return info; + } + + context.delegate = null; + } + + if (method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = arg; + + } else if (method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw arg; + } + + if (context.dispatchException(arg)) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + method = "next"; + arg = undefined; + } + + } else if (method === "return") { + context.abrupt("return", arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + var info = { + value: record.arg, + done: context.done + }; + + if (record.arg === ContinueSentinel) { + if (context.delegate && method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + arg = undefined; + } + } else { + return info; + } + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(arg) call above. + method = "throw"; + arg = record.arg; + } + } + }; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp[toStringTagSymbol] = "Generator"; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + runtime.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + runtime.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + return !!caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.next = finallyEntry.finallyLoc; + } else { + this.complete(record); + } + + return ContinueSentinel; + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = record.arg; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + return ContinueSentinel; + } + }; + })( + // Among the various tricks for obtaining a reference to the global + // object, this seems to be the most reliable technique that does not + // use indirect eval (which violates Content Security Policy). + typeof global === "object" ? global : + typeof window === "object" ? window : + typeof self === "object" ? self : this + ); + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(294))) + +/***/ }, +/* 294 */ +/***/ function(module, exports) { + + // shim for using process in browser + var process = module.exports = {}; + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + +/***/ }, +/* 295 */ +/***/ function(module, exports, __webpack_require__) { + + __webpack_require__(296); + module.exports = __webpack_require__(9).RegExp.escape; + +/***/ }, +/* 296 */ +/***/ function(module, exports, __webpack_require__) { + + // https://github.com/benjamingr/RexExp.escape + var $export = __webpack_require__(8) + , $re = __webpack_require__(297)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + + $export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }}); + + +/***/ }, +/* 297 */ +/***/ function(module, exports) { + + module.exports = function(regExp, replace){ + var replacer = replace === Object(replace) ? function(part){ + return replace[part]; + } : replace; + return function(it){ + return String(it).replace(regExp, replacer); + }; + }; + +/***/ }, +/* 298 */ +/***/ function(module, exports, __webpack_require__) { + + var BSON = __webpack_require__(299), + Binary = __webpack_require__(318), + Code = __webpack_require__(313), + DBRef = __webpack_require__(317), + Decimal128 = __webpack_require__(314), + Double = __webpack_require__(307), + Int32 = __webpack_require__(312), + Long = __webpack_require__(306), + Map = __webpack_require__(305), + MaxKey = __webpack_require__(316), + MinKey = __webpack_require__(315), + ObjectId = __webpack_require__(309), + BSONRegExp = __webpack_require__(310), + Symbol = __webpack_require__(311), + Timestamp = __webpack_require__(308); + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7FFFFFFF; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Add BSON types to function creation + BSON.Binary = Binary; + BSON.Code = Code; + BSON.DBRef = DBRef; + BSON.Decimal128 = Decimal128; + BSON.Double = Double; + BSON.Int32 = Int32; + BSON.Long = Long; + BSON.Map = Map; + BSON.MaxKey = MaxKey; + BSON.MinKey = MinKey; + BSON.ObjectId = ObjectId; + BSON.ObjectID = ObjectId; + BSON.BSONRegExp = BSONRegExp; + BSON.Symbol = Symbol; + BSON.Timestamp = Timestamp; + + // Return the BSON + module.exports = BSON; + +/***/ }, +/* 299 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; + + var writeIEEE754 = __webpack_require__(304).writeIEEE754, + readIEEE754 = __webpack_require__(304).readIEEE754, + Map = __webpack_require__(305), + Long = __webpack_require__(306), + Double = __webpack_require__(307), + Timestamp = __webpack_require__(308), + ObjectID = __webpack_require__(309), + BSONRegExp = __webpack_require__(310), + Symbol = __webpack_require__(311), + Int32 = __webpack_require__(312), + Code = __webpack_require__(313), + Decimal128 = __webpack_require__(314), + MinKey = __webpack_require__(315), + MaxKey = __webpack_require__(316), + DBRef = __webpack_require__(317), + Binary = __webpack_require__(318); + + // Parts of the parser + var deserialize = __webpack_require__(319), + serializer = __webpack_require__(323), + calculateObjectSize = __webpack_require__(324); + + /** + * @ignore + * @api private + */ + // Max Size + var MAXSIZE = 1024 * 1024 * 17; + // Max Document Buffer size + var buffer = new Buffer(MAXSIZE); + + var BSON = function () {}; + + /** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ + BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : true; + + // console.log("===================================== serialize") + // console.log("checkKeys = " + checkKeys) + // console.log("serializeFunctions = " + serializeFunctions) + // console.log("ignoreUndefined = " + ignoreUndefined) + + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; + }; + + /** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ + BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index == 'number' ? options.index : 0; + + // console.log("===================================== serializeWithBufferAndIndex") + // console.log("checkKeys = " + checkKeys) + // console.log("serializeFunctions = " + serializeFunctions) + // console.log("ignoreUndefined = " + ignoreUndefined) + // console.log("startIndex = " + startIndex) + + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + + // Return the index + return serializationIndex - 1; + }; + + /** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ + BSON.prototype.deserialize = function (data, options) { + return deserialize(data, options); + }; + + /** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ + BSON.prototype.calculateObjectSize = function (object, options) { + options = options || {}; + + var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); + }; + + /** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ + BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; + }; + + /** + * @ignore + * @api private + */ + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7FFFFFFF; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // Return BSON + module.exports = BSON; + module.exports.Code = Code; + module.exports.Map = Map; + module.exports.Symbol = Symbol; + module.exports.BSON = BSON; + module.exports.DBRef = DBRef; + module.exports.Binary = Binary; + module.exports.ObjectID = ObjectID; + module.exports.Long = Long; + module.exports.Timestamp = Timestamp; + module.exports.Double = Double; + module.exports.Int32 = Int32; + module.exports.MinKey = MinKey; + module.exports.MaxKey = MaxKey; + module.exports.BSONRegExp = BSONRegExp; + module.exports.Decimal128 = Decimal128; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) + +/***/ }, +/* 300 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> + * @license MIT + */ + /* eslint-disable no-proto */ + + 'use strict' + + var base64 = __webpack_require__(301) + var ieee754 = __webpack_require__(302) + var isArray = __webpack_require__(303) + + exports.Buffer = Buffer + exports.SlowBuffer = SlowBuffer + exports.INSPECT_MAX_BYTES = 50 + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + + /* + * Export kMaxLength after typed array support is determined. + */ + exports.kMaxLength = kMaxLength() + + function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } + } + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192 // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr + } + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + } + + function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + } + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + } + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that + } + + function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + } + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer + } + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + Buffer.byteLength = byteLength + + function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true + + function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this + } + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this + } + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this + } + + Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + } + + Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + } + + Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '<Buffer ' + str + '>' + } + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + } + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + } + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + } + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + } + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000 + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf + } + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val + } + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val + } + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] + } + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) + } + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] + } + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + } + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + } + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + } + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + } + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + } + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) + } + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) + } + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) + } + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) + } + + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 + } + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + } + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + } + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len + } + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this + } + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray + } + + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer, (function() { return this; }()))) + +/***/ }, +/* 301 */ +/***/ function(module, exports) { + + 'use strict' + + exports.byteLength = byteLength + exports.toByteArray = toByteArray + exports.fromByteArray = fromByteArray + + var lookup = [] + var revLookup = [] + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 + + function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + } + + function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) + } + + function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') + } + + +/***/ }, +/* 302 */ +/***/ function(module, exports) { + + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 + } + + +/***/ }, +/* 303 */ +/***/ function(module, exports) { + + var toString = {}.toString; + + module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + +/***/ }, +/* 304 */ +/***/ function(module, exports) { + + // Copyright (c) 2008, Fair Oaks Labs, Inc. + // All rights reserved. + // + // Redistribution and use in source and binary forms, with or without + // modification, are permitted provided that the following conditions are met: + // + // * Redistributions of source code must retain the above copyright notice, + // this list of conditions and the following disclaimer. + // + // * Redistributions in binary form must reproduce the above copyright notice, + // this list of conditions and the following disclaimer in the documentation + // and/or other materials provided with the distribution. + // + // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors + // may be used to endorse or promote products derived from this software + // without specific prior written permission. + // + // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + // POSSIBILITY OF SUCH DAMAGE. + // + // + // Modifications to writeIEEE754 to support negative zeroes made by Brian White + + var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { + var e, + m, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : nBytes - 1, + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + + var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { + var e, + m, + c, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + i = bBE ? nBytes - 1 : 0, + d = bBE ? -1 : 1, + s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; + }; + + exports.readIEEE754 = readIEEE754; + exports.writeIEEE754 = writeIEEE754; + +/***/ }, +/* 305 */ +/***/ function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {"use strict"; + + // We have an ES6 Map available, return the native instance + + if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; + } else { + // We will return a polyfill + var Map = function (array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function (callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function (key) { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function (key, value) { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function () { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; + } + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 306 */ +/***/ function(module, exports) { + + // 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. + // + // Copyright 2009 Google Inc. All Rights Reserved + + /** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ + function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + }; + + /** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ + Long.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Long.prototype.toNumber = function () { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Long.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + Long.prototype.toString = function (opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } + }; + + /** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Long.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Long.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; + }; + + /** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } + }; + + /** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ + Long.prototype.isZero = function () { + return this.high_ == 0 && this.low_ == 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Long.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Long.prototype.isOdd = function () { + return (this.low_ & 1) == 1; + }; + + /** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ + Long.prototype.equals = function (other) { + return this.high_ == other.high_ && this.low_ == other.low_; + }; + + /** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ + Long.prototype.notEquals = function (other) { + return this.high_ != other.high_ || this.low_ != other.low_; + }; + + /** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ + Long.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ + Long.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ + Long.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ + Long.prototype.compare = function (other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } + }; + + /** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ + Long.prototype.negate = function () { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } + }; + + /** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ + Long.prototype.add = function (other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ + Long.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ + Long.prototype.multiply = function (other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ + Long.prototype.div = function (other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; + }; + + /** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ + Long.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ + Long.prototype.not = function () { + return Long.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ + Long.prototype.and = function (other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); + }; + + /** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ + Long.prototype.or = function (other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); + }; + + /** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ + Long.prototype.xor = function (other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); + }; + + /** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ + Long.prototype.shiftLeft = function (numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); + } else { + return Long.fromBits(0, low << numBits - 32); + } + } + }; + + /** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ + Long.prototype.shiftRight = function (numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); + } else { + return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); + } + } + }; + + /** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> numBits - 32, 0); + } + } + }; + + /** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ + Long.fromInt = function (value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; + }; + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ + Long.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); + } + }; + + /** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ + Long.fromBits = function (lowBits, highBits) { + return new Long(lowBits, highBits); + }; + + /** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ + Long.fromString = function (str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; + }; + + // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the + // from* methods on which they depend. + + + /** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ + Long.INT_CACHE_ = {}; + + // NOTE: the compiler should inline these constant values below and then remove + // these variables, so there should be no runtime penalty for these. + + /** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ + Long.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + + /** @type {Long} */ + Long.ZERO = Long.fromInt(0); + + /** @type {Long} */ + Long.ONE = Long.fromInt(1); + + /** @type {Long} */ + Long.NEG_ONE = Long.fromInt(-1); + + /** @type {Long} */ + Long.MAX_VALUE = Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + + /** @type {Long} */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + + /** + * @type {Long} + * @ignore + */ + Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Long; + module.exports.Long = Long; + +/***/ }, +/* 307 */ +/***/ function(module, exports) { + + /** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ + function Double(value) { + if (!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; + } + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Double.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Double; + module.exports.Double = Double; + +/***/ }, +/* 308 */ +/***/ function(module, exports) { + + // 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. + // + // Copyright 2009 Google Inc. All Rights Reserved + + /** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ + function Timestamp(low, high) { + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + }; + + /** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ + Timestamp.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Timestamp.prototype.toNumber = function () { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Timestamp.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + Timestamp.prototype.toString = function (opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } + }; + + /** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Timestamp.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Timestamp.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + Timestamp.prototype.getLowBitsUnsigned = function () { + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; + }; + + /** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ + Timestamp.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } + }; + + /** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ + Timestamp.prototype.isZero = function () { + return this.high_ == 0 && this.low_ == 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Timestamp.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Timestamp.prototype.isOdd = function () { + return (this.low_ & 1) == 1; + }; + + /** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ + Timestamp.prototype.equals = function (other) { + return this.high_ == other.high_ && this.low_ == other.low_; + }; + + /** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ + Timestamp.prototype.notEquals = function (other) { + return this.high_ != other.high_ || this.low_ != other.low_; + }; + + /** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ + Timestamp.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ + Timestamp.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ + Timestamp.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ + Timestamp.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ + Timestamp.prototype.compare = function (other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } + }; + + /** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ + Timestamp.prototype.negate = function () { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } + }; + + /** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ + Timestamp.prototype.add = function (other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ + Timestamp.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ + Timestamp.prototype.multiply = function (other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ + Timestamp.prototype.div = function (other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; + }; + + /** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ + Timestamp.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ + Timestamp.prototype.not = function () { + return Timestamp.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ + Timestamp.prototype.and = function (other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); + }; + + /** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ + Timestamp.prototype.or = function (other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); + }; + + /** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ + Timestamp.prototype.xor = function (other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); + }; + + /** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ + Timestamp.prototype.shiftLeft = function (numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); + } else { + return Timestamp.fromBits(0, low << numBits - 32); + } + } + }; + + /** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ + Timestamp.prototype.shiftRight = function (numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); + } else { + return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); + } + } + }; + + /** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ + Timestamp.prototype.shiftRightUnsigned = function (numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> numBits - 32, 0); + } + } + }; + + /** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromInt = function (value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; + }; + + /** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); + } + }; + + /** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + + /** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromString = function (str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; + }; + + // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the + // from* methods on which they depend. + + + /** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ + Timestamp.INT_CACHE_ = {}; + + // NOTE: the compiler should inline these constant values below and then remove + // these variables, so there should be no runtime penalty for these. + + /** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + + /** @type {Timestamp} */ + Timestamp.ZERO = Timestamp.fromInt(0); + + /** @type {Timestamp} */ + Timestamp.ONE = Timestamp.fromInt(1); + + /** @type {Timestamp} */ + Timestamp.NEG_ONE = Timestamp.fromInt(-1); + + /** @type {Timestamp} */ + Timestamp.MAX_VALUE = Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + + /** @type {Timestamp} */ + Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + + /** + * @type {Timestamp} + * @ignore + */ + Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Timestamp; + module.exports.Timestamp = Timestamp; + +/***/ }, +/* 309 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(process, Buffer) {/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ + var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + + // Regular expression that checks for hex value + var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); + + /** + * Create a new ObjectID instance + * + * @class + * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. + * @property {number} generationTime The generation time of this ObjectId instance + * @return {ObjectID} instance of ObjectID. + */ + var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + var __id = null; + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } else if (valid && typeof id == 'string' && id.length == 24) { + return ObjectID.createFromHexString(id); + } else if (id == null || typeof id == 'number') { + // convert to 12 byte binary string + this.id = this.generate(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } + + if (ObjectID.cacheHexString) this.__id = this.toHexString(); + }; + + // Allow usage of ObjectId as well as ObjectID + var ObjectId = ObjectID; + + // Precomputed hex table enables speedy hex string conversion + var hexTable = []; + for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); + } + + /** + * Return the ObjectID id as a 24 byte hex string representation + * + * @method + * @return {string} return the 24 byte hex string representation. + */ + ObjectID.prototype.toHexString = function () { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.get_inc = function () { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.getInc = function () { + return this.get_inc(); + }; + + /** + * Generate a 12 byte id buffer used in ObjectID's + * + * @method + * @param {number} [time] optional parameter allowing to pass in a second based timestamp. + * @return {Buffer} return the 12 byte id buffer string. + */ + ObjectID.prototype.generate = function (time) { + if ('number' != typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF; + var inc = this.get_inc(); + // Buffer used + var buffer = new Buffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = MACHINE_ID >> 8 & 0xff; + buffer[4] = MACHINE_ID >> 16 & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = pid >> 8 & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = inc >> 8 & 0xff; + buffer[9] = inc >> 16 & 0xff; + // Return the buffer + return buffer; + }; + + /** + * Converts the id into a 24 byte hex string for printing + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toString = function () { + return this.toHexString(); + }; + + /** + * Converts to a string representation of this Id. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.inspect = ObjectID.prototype.toString; + + /** + * Converts to its JSON representation. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toJSON = function () { + return this.toHexString(); + }; + + /** + * Compares the equality of this ObjectID with `otherID`. + * + * @method + * @param {object} otherID ObjectID instance to compare against. + * @return {boolean} the result of comparing two ObjectID's + */ + ObjectID.prototype.equals = function equals(otherId) { + var id; + + if (otherId instanceof ObjectID) { + return this.toString() == otherId.toString(); + } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } + }; + + /** + * Returns the generation date (accurate up to the second) that this ID was generated. + * + * @method + * @return {date} the generation date + */ + ObjectID.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + + /** + * @ignore + */ + ObjectID.index = ~~(Math.random() * 0xFFFFFF); + + /** + * @ignore + */ + ObjectID.createPk = function createPk() { + return new ObjectID(); + }; + + /** + * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. + * + * @method + * @param {number} time an integer number representing a number of seconds. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromTime = function createFromTime(time) { + var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Return the new objectId + return new ObjectID(buffer); + }; + + // Lookup tables + var encodeLookup = '0123456789abcdef'.split(''); + var decodeLookup = []; + var i = 0; + while (i < 10) decodeLookup[0x30 + i] = i++; + while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + + var _Buffer = Buffer; + var convertToHex = function (bytes) { + return bytes.toString('hex'); + }; + + /** + * Creates an ObjectID from a hex string representation of an ObjectID. + * + * @method + * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || string != null && string.length != 24) throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + var length = string.length; + + if (length > 12 * 2) { + throw new Error('Id cannot be longer than 12 bytes'); + } + + // Calculate lengths + var sizeof = length >> 1; + var array = new _Buffer(sizeof); + var n = 0; + var i = 0; + + while (i < length) { + array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); + }; + + /** + * Checks if a value is a valid bson ObjectId + * + * @method + * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. + */ + ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id == 'number') { + return true; + } + + if (typeof id == 'string') { + return id.length == 12 || id.length == 24 && checkForHexRegExp.test(id); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length == 12 || id.id.length == 24 && checkForHexRegExp.test(id.id); + } + + return false; + }; + + /** + * @ignore + */ + Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true, + get: function () { + return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + }, + set: function (value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = value >> 8 & 0xff; + this.id[1] = value >> 16 & 0xff; + this.id[0] = value >> 24 & 0xff; + } + }); + + /** + * Expose. + */ + module.exports = ObjectID; + module.exports.ObjectID = ObjectID; + module.exports.ObjectId = ObjectID; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(294), __webpack_require__(300).Buffer)) + +/***/ }, +/* 310 */ +/***/ function(module, exports) { + + /** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] == 'i' || this.options[i] == 'm' || this.options[i] == 'x' || this.options[i] == 'l' || this.options[i] == 's' || this.options[i] == 'u')) { + throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); + } + } + } + + module.exports = BSONRegExp; + module.exports.BSONRegExp = BSONRegExp; + +/***/ }, +/* 311 */ +/***/ function(module, exports) { + + /** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ + function Symbol(value) { + if (!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; + } + + /** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ + Symbol.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toString = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.inspect = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Symbol; + module.exports.Symbol = Symbol; + +/***/ }, +/* 312 */ +/***/ function(module, exports) { + + var Int32 = function (value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; + }; + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Int32.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Int32; + module.exports.Int32 = Int32; + +/***/ }, +/* 313 */ +/***/ function(module, exports) { + + /** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ + var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; + }; + + /** + * @ignore + */ + Code.prototype.toJSON = function () { + return { scope: this.scope, code: this.code }; + }; + + module.exports = Code; + module.exports.Code = Code; + +/***/ }, +/* 314 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; + + var Long = __webpack_require__(306); + + var PARSE_STRING_REGEXP = /^(\+|\-)?(\d+|(\d*\.\d*))?(E|e)?([\-\+])?(\d+)?$/; + var PARSE_INF_REGEXP = /^(\+|\-)?(Infinity|inf)$/i; + var PARSE_NAN_REGEXP = /^(\+|\-)?NaN$/i; + + var EXPONENT_MAX = 6111; + var EXPONENT_MIN = -6176; + var EXPONENT_BIAS = 6176; + var MAX_DIGITS = 34; + + // Nan value bits as 32 bit values (due to lack of longs) + var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + // Infinity value bits 32 bit values (due to lack of longs) + var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + + var EXPONENT_REGEX = /^([\-\+])?(\d+)?$/; + + // Detect if the value is a digit + var isDigit = function (value) { + return !isNaN(parseInt(value, 10)); + }; + + // Divide two uint128 values + var divideu128 = function (value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (var i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; + }; + + // Multiply two Long values and return the 128 bit value + var multiply64x2 = function (left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; + }; + + var lessThan = function (left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft == uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; + }; + + var longtoHex = function (value) { + var buffer = new Buffer(8); + var index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = value.low_ & 0xff; + buffer[index++] = value.low_ >> 8 & 0xff; + buffer[index++] = value.low_ >> 16 & 0xff; + buffer[index++] = value.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = value.high_ & 0xff; + buffer[index++] = value.high_ >> 8 & 0xff; + buffer[index++] = value.high_ >> 16 & 0xff; + buffer[index++] = value.high_ >> 24 & 0xff; + return buffer.reverse().toString('hex'); + }; + + var int32toHex = function (value) { + var buffer = new Buffer(4); + var index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + return buffer.reverse().toString('hex'); + }; + + var Decimal128 = function (bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; + }; + + Decimal128.fromString = function (string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if (!stringMatch && !infMatch && !nanMatch || string.length == 0) { + throw new Error("" + string + " not a valid Decimal128 string"); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error("" + string + " not a valid Decimal128 string"); + } + + // Get the negative or positive sign + if (string[index] == '+' || string[index] == '-') { + isNegative = string[index++] == '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] != '.') { + if (string[index] == 'i' || string[index] == 'I') { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] == 'N') { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] == '.') { + if (string[index] == '.') { + if (sawRadix) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] != '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error("" + string + " not a valid Decimal128 string"); + } + + // Read exponent if exists + if (string[index] == 'e' || string[index] == 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent != 0 && significantDigits != 1) { + while (string[firstNonZero + significantDigits - 1] == '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit == 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] != '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent == EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit == 5) { + roundBit = digits[lastDigit] % 2 == 1; + + for (var i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx == 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits == 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + var dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString("100000000000000000")); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + var biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = new Buffer(16); + var index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = dec.low.low_ >> 8 & 0xff; + buffer[index++] = dec.low.low_ >> 16 & 0xff; + buffer[index++] = dec.low.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = dec.low.high_ >> 8 & 0xff; + buffer[index++] = dec.low.high_ >> 16 & 0xff; + buffer[index++] = dec.low.high_ >> 24 & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = dec.high.low_ >> 8 & 0xff; + buffer[index++] = dec.high.low_ >> 16 & 0xff; + buffer[index++] = dec.high.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = dec.high.high_ >> 8 & 0xff; + buffer[index++] = dec.high.high_ >> 16 & 0xff; + buffer[index++] = dec.high.high_ >> 24 & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); + }; + + // Extract least significant 5 bits + var COMBINATION_MASK = 0x1f; + // Extract least significant 14 bits + var EXPONENT_MASK = 0x3fff; + // Value of combination field for Inf + var COMBINATION_INFINITY = 30; + // Value of combination field for NaN + var COMBINATION_NAN = 31; + // Value of combination field for NaN + var COMBINATION_SNAN = 32; + // decimal128 exponent bias + var EXPONENT_BIAS = 6176; + + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + var i; + var j, k; + + // Output string + var string = []; + + // Unpack index + var index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack the high 64bits into a long + midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack index + var index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = high >> 26 & COMBINATION_MASK; + + if (combination >> 3 == 3) { + // Check for 'special' values + if (combination == COMBINATION_INFINITY) { + return string.join('') + "Infinity"; + } else if (combination == COMBINATION_NAN) { + return "NaN"; + } else { + biased_exponent = high >> 15 & EXPONENT_MASK; + significand_msb = 0x08 + (high >> 14 & 0x01); + } + } else { + significand_msb = high >> 14 & 0x07; + biased_exponent = high >> 17 & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if (significand128.parts[0] == 0 && significand128.parts[1] == 0 && significand128.parts[2] == 0 && significand128.parts[3] == 0) { + is_zero = true; + } else { + for (var k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (var j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + var i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (var i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (var i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (var i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); + }; + + Decimal128.prototype.toJSON = function () { + return { "$numberDecimal": this.toString() }; + }; + + module.exports = Decimal128; + module.exports.Decimal128 = Decimal128; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) + +/***/ }, +/* 315 */ +/***/ function(module, exports) { + + /** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ + function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; + } + + module.exports = MinKey; + module.exports.MinKey = MinKey; + +/***/ }, +/* 316 */ +/***/ function(module, exports) { + + /** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ + function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; + } + + module.exports = MaxKey; + module.exports.MaxKey = MaxKey; + +/***/ }, +/* 317 */ +/***/ function(module, exports) { + + /** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ + function DBRef(namespace, oid, db) { + if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; + }; + + /** + * @ignore + * @api private + */ + DBRef.prototype.toJSON = function () { + return { + '$ref': this.namespace, + '$id': this.oid, + '$db': this.db == null ? '' : this.db + }; + }; + + module.exports = DBRef; + module.exports.DBRef = DBRef; + +/***/ }, +/* 318 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Module dependencies. + * @ignore + */ + + // Test if we're in Node via presence of "global" not absence of "window" + // to support hybrid environments like Electron + if (typeof global !== 'undefined') { + var Buffer = __webpack_require__(300).Buffer; // TODO just use global Buffer + } + + /** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if (buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if (buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if (typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if (typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if (typeof Uint8Array != 'undefined' || Object.prototype.toString.call(buffer) == '[object Array]') { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if (typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if (typeof Uint8Array != 'undefined') { + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } + }; + + /** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ + Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if (byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if (typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if (typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if (byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if (typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if (Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for (var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } + }; + + /** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ + Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if (typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if (Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); + // Copy the content + for (var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if (typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length + } else if (typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, offset, 'binary'); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length; + } else if (Object.prototype.toString.call(string) == '[object Uint8Array]' || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for (var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if (typeof string == 'string') { + for (var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } + }; + + /** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ + Binary.prototype.read = function read(position, length) { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + if (this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for (var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; + }; + + /** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ + Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) return this.buffer; + + // If it's a node.js buffer object + if (typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if (asRaw) { + // we support the slice command use it + if (this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for (var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } + }; + + /** + * Length. + * + * @method + * @return {number} the length of the binary. + */ + Binary.prototype.length = function length() { + return this.position; + }; + + /** + * @ignore + */ + Binary.prototype.toJSON = function () { + return this.buffer != null ? this.buffer.toString('base64') : ''; + }; + + /** + * @ignore + */ + Binary.prototype.toString = function (format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; + }; + + /** + * Binary default subtype + * @ignore + */ + var BSON_BINARY_SUBTYPE_DEFAULT = 0; + + /** + * @ignore + */ + var writeStringToArray = function (data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for (var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; + }; + + /** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ + var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { + var result = ""; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; + }; + + Binary.BUFFER_SIZE = 256; + + /** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_DEFAULT = 0; + /** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_FUNCTION = 1; + /** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_UUID_OLD = 3; + /** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_UUID = 4; + /** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_MD5 = 5; + /** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_USER_DEFINED = 128; + + /** + * Expose. + */ + module.exports = Binary; + module.exports.Binary = Binary; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 319 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; + + var readIEEE754 = __webpack_require__(304).readIEEE754, + f = __webpack_require__(320).format, + Long = __webpack_require__(306).Long, + Double = __webpack_require__(307).Double, + Timestamp = __webpack_require__(308).Timestamp, + ObjectID = __webpack_require__(309).ObjectID, + Symbol = __webpack_require__(311).Symbol, + Code = __webpack_require__(313).Code, + MinKey = __webpack_require__(315).MinKey, + MaxKey = __webpack_require__(316).MaxKey, + Decimal128 = __webpack_require__(314), + Int32 = __webpack_require__(312), + DBRef = __webpack_require__(317).DBRef, + BSONRegExp = __webpack_require__(310).BSONRegExp, + Binary = __webpack_require__(318).Binary; + + var deserialize = function (buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error("corrupt bson message"); + } + + // Illegal end value + if (buffer[index + size - 1] != 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); + }; + + var deserializeObject = function (buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + // While we have more left data left keep parsing + while (true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType == 0) { + break; + } + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType == BSON.BSON_DATA_STRING) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType == BSON.BSON_DATA_OID) { + var oid = new Buffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType == BSON.BSON_DATA_INT && promoteValues == false) { + object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); + } else if (elementType == BSON.BSON_DATA_INT) { + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if (elementType == BSON.BSON_DATA_NUMBER && promoteValues == false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType == BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType == BSON.BSON_DATA_DATE) { + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType == BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] != 0 && buffer[index] != 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] == 1; + } else if (elementType == BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error("bad embedded document length in bson"); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType == BSON.BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] != 0) throw new Error('invalid array terminator byte'); + if (index != stopIndex) throw new Error('corrupted array bson'); + } else if (elementType == BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType == BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType == BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues == true) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + } else if (elementType == BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = new Buffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType == BSON.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (var i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType == BSON.BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType == BSON.BSON_DATA_TIMESTAMP) { + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType == BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType == BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType == BSON.BSON_DATA_CODE) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType == BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error("code_w_scope total size shorter minimum expected length"); + } + + // Get the code string size + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + + // Javascript function + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _index = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType == BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = new Buffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + var oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error("Detected unknown BSON type " + elementType.toString(16) + " for fieldname \"" + name + "\", are you using the latest BSON parser"); + } + } + + // Check if the deserialization was against a valid array/object + if (size != index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEvalWithHash = function (functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEval = function (functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + var functionCache = BSON.functionCache = {}; + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ + BSON.BSON_DATA_DBPOINTER = 12; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7FFFFFFF; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = deserialize; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) + +/***/ }, +/* 320 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; + + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + }; + + + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; + + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = __webpack_require__(321); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = __webpack_require__(322); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(294))) + +/***/ }, +/* 321 */ +/***/ function(module, exports) { + + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } + +/***/ }, +/* 322 */ +/***/ function(module, exports) { + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + +/***/ }, +/* 323 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; + + var writeIEEE754 = __webpack_require__(304).writeIEEE754, + readIEEE754 = __webpack_require__(304).readIEEE754, + Long = __webpack_require__(306).Long, + Map = __webpack_require__(305), + Double = __webpack_require__(307).Double, + Timestamp = __webpack_require__(308).Timestamp, + ObjectID = __webpack_require__(309).ObjectID, + Symbol = __webpack_require__(311).Symbol, + Code = __webpack_require__(313).Code, + BSONRegExp = __webpack_require__(310).BSONRegExp, + Int32 = __webpack_require__(312).Int32, + MinKey = __webpack_require__(315).MinKey, + MaxKey = __webpack_require__(316).MaxKey, + Decimal128 = __webpack_require__(314), + DBRef = __webpack_require__(317).DBRef, + Binary = __webpack_require__(318).Binary; + + try { + var _Buffer = Uint8Array; + } catch (e) { + var _Buffer = Buffer; + } + + var regexp = /\x00/; + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; + }; + + var serializeString = function (buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = size + 1 >> 24 & 0xff; + buffer[index + 2] = size + 1 >> 16 & 0xff; + buffer[index + 1] = size + 1 >> 8 & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeNumber = function (buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + }; + + var serializeUndefined = function (buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_UNDEFINED; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeNull = function (buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeBoolean = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + }; + + var serializeDate = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error("value " + value.source + " must not contain null bytes"); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeBSONRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("pattern " + value.pattern + " must not contain null bytes"); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeMinMax = function (buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeObjectId = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id == 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + "] is not a valid ObjectId"); + } + + // Ajust index + return index + 12; + }; + + var serializeBuffer = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + }; + + var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + // Write size + var size = endIndex - index; + return endIndex; + }; + + var serializeDecimal128 = function (buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; + }; + + var serializeLong = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeInt32 = function (buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + return index; + }; + + var serializeDouble = function (buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + }; + + var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (value.scope && typeof value.scope == 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = codeSize >> 8 & 0xff; + buffer[index + 2] = codeSize >> 16 & 0xff; + buffer[index + 3] = codeSize >> 24 & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = totalSize >> 8 & 0xff; + buffer[startIndex++] = totalSize >> 16 & 0xff; + buffer[startIndex++] = totalSize >> 24 & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; + }; + + var serializeBinary = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; + }; + + var serializeSymbol = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + }; + + var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto(buffer, { + '$ref': value.namespace, + '$id': value.oid, + '$db': value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + '$ref': value.namespace, + '$id': value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = size >> 8 & 0xff; + buffer[startIndex++] = size >> 16 & 0xff; + buffer[startIndex++] = size >> 24 & 0xff; + // Set index + return endIndex; + }; + + var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = "" + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + var type = typeof value; + if (type == 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type == 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type == 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } else if (type == 'object' && value['_bsontype'] == 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); + } else if (value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } else if (value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] == 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + + if (checkKeys) { + if ('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + if (type == 'string') { + index = serializeString(buffer, key, value, index); + } else if (type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined && ignoreUndefined == true) {} else if (value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type == 'object' && value['_bsontype'] == 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] == 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); + object = object.toBSON(); + if (object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); + } + + // Iterate over all the keys + for (var key in object) { + var value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + + if (checkKeys) { + if ('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + if (type == 'string') { + index = serializeString(buffer, key, value, index); + } else if (type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined && ignoreUndefined == true) {} else if (value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type == 'object' && value['_bsontype'] == 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] == 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = size >> 8 & 0xff; + buffer[startingIndex++] = size >> 16 & 0xff; + buffer[startingIndex++] = size >> 24 & 0xff; + return index; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + var functionCache = BSON.functionCache = {}; + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7FFFFFFF; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = serializeInto; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) + +/***/ }, +/* 324 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; + + var writeIEEE754 = __webpack_require__(304).writeIEEE754, + readIEEE754 = __webpack_require__(304).readIEEE754, + Long = __webpack_require__(306).Long, + Double = __webpack_require__(307).Double, + Timestamp = __webpack_require__(308).Timestamp, + ObjectID = __webpack_require__(309).ObjectID, + Symbol = __webpack_require__(311).Symbol, + BSONRegExp = __webpack_require__(310).BSONRegExp, + Code = __webpack_require__(313).Code, + Decimal128 = __webpack_require__(314), + MinKey = __webpack_require__(315).MinKey, + MaxKey = __webpack_require__(316).MaxKey, + DBRef = __webpack_require__(317).DBRef, + Binary = __webpack_require__(318).Binary; + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; + }; + + /** + * @ignore + * @api private + */ + function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; + } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] == 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; + } + } else if (value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if (value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); + } + } else if (value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; + } else if (value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace, + '$id': value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else if (value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if (serializeFunctions) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; + } + } + } + + return 0; + } + + var BSON = {}; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7FFFFFFF; + BSON.BSON_INT32_MIN = -0x80000000; + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = calculateObjectSize; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) + +/***/ } +/******/ ]) +}); +;
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json new file mode 100644 index 00000000..980db7f9 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "name" : "bson" +, "description" : "A bson parser for node.js and the browser" +, "main": "../" +, "directories" : { "lib" : "../lib/bson" } +, "engines" : { "node" : ">=0.6.0" } +, "licenses" : [ { "type" : "Apache License, Version 2.0" + , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/index.js new file mode 100644 index 00000000..caed12b7 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/index.js @@ -0,0 +1,46 @@ +var BSON = require('./lib/bson/bson'), + Binary = require('./lib/bson/binary'), + Code = require('./lib/bson/code'), + DBRef = require('./lib/bson/db_ref'), + Decimal128 = require('./lib/bson/decimal128'), + Double = require('./lib/bson/double'), + Int32 = require('./lib/bson/int_32'), + Long = require('./lib/bson/long'), + Map = require('./lib/bson/map'), + MaxKey = require('./lib/bson/max_key'), + MinKey = require('./lib/bson/min_key'), + ObjectId = require('./lib/bson/objectid'), + BSONRegExp = require('./lib/bson/regexp'), + Symbol = require('./lib/bson/symbol'), + Timestamp = require('./lib/bson/timestamp'); + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Add BSON types to function creation +BSON.Binary = Binary; +BSON.Code = Code; +BSON.DBRef = DBRef; +BSON.Decimal128 = Decimal128; +BSON.Double = Double; +BSON.Int32 = Int32; +BSON.Long = Long; +BSON.Map = Map; +BSON.MaxKey = MaxKey; +BSON.MinKey = MinKey; +BSON.ObjectId = ObjectId; +BSON.ObjectID = ObjectId; +BSON.BSONRegExp = BSONRegExp; +BSON.Symbol = Symbol; +BSON.Timestamp = Timestamp; + +// Return the BSON +module.exports = BSON; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js new file mode 100644 index 00000000..793b56f9 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,347 @@ +/** + * Module dependencies. + * @ignore + */ + +// Test if we're in Node via presence of "global" not absence of "window" +// to support hybrid environments like Electron +if(typeof global !== 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if(!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if(buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if(buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if(typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if(typeof Uint8Array != 'undefined'){ + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +}; + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if(typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if(byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if(this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for(var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if(this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) + // Copy the content + for(var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length + } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, offset, 'binary'); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length; + } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' + || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if(typeof string == 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 + ? length + : this.position; + + // Let's return the data based on the type we have + if(this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for(var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) + return this.buffer; + + // If it's a node.js buffer object + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if(asRaw) { + // we support the slice command use it + if(this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for(var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for(var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +} + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js new file mode 100644 index 00000000..b98887ea --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,358 @@ +"use strict" + +var writeIEEE754 = require('./float_parser').writeIEEE754, + readIEEE754 = require('./float_parser').readIEEE754, + Map = require('./map'), + Long = require('./long'), + Double = require('./double'), + Timestamp = require('./timestamp'), + ObjectID = require('./objectid'), + BSONRegExp = require('./regexp'), + Symbol = require('./symbol'), + Int32 = require('./int_32'), + Code = require('./code'), + Decimal128 = require('./decimal128'), + MinKey = require('./min_key'), + MaxKey = require('./max_key'), + DBRef = require('./db_ref'), + Binary = require('./binary'); + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'); + +/** + * @ignore + * @api private + */ +// Max Size +var MAXSIZE = (1024*1024*17); +// Max Document Buffer size +var buffer = new Buffer(MAXSIZE); + +var BSON = function() { +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys == 'boolean' + ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : true; + + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys == 'boolean' + ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : true; + var startIndex = typeof options.index == 'number' + ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + + // Return the index + return serializationIndex - 1; +} + +/** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(buffer, options) { + return deserialize(buffer, options); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, options) { + options = options || {}; + + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +} + +/** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// Return BSON +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.Int32 = Int32; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; +module.exports.Decimal128 = Decimal128; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js new file mode 100644 index 00000000..bc80ce5f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if(!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +module.exports = Code; +module.exports.Code = Code; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 00000000..06789a6c --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +}; + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + '$ref':this.namespace, + '$id':this.oid, + '$db':this.db == null ? '' : this.db + }; +} + +module.exports = DBRef; +module.exports.DBRef = DBRef;
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/decimal128.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/decimal128.js new file mode 100644 index 00000000..23ae082e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/decimal128.js @@ -0,0 +1,728 @@ +"use strict" + +var Long = require('./long'); + +var PARSE_STRING_REGEXP = /^(\+|\-)?(\d+|(\d*\.\d*))?(E|e)?([\-\+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|\-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|\-)?NaN$/i; + +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); +var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + +var EXPONENT_REGEX = /^([\-\+])?(\d+)?$/; + + +// Detect if the value is a digit +var isDigit = function(value) { + return !isNaN(parseInt(value, 10)); +} + +// Divide two uint128 values +var divideu128 = function(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if(!value.parts[0] && !value.parts[1] && + !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for(var i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +} + +// Multiply two Long values and return the 128 bit value +var multiply64x2 = function(left, right) { + if(!left && !right) { + return {high: Long.fromNumber(0), low: Long.fromNumber(0)}; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return {high: productHigh, low: productLow}; +} + +var lessThan = function(left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if(uhleft < uhright) { + return true + } else if(uhleft == uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if(ulleft < ulright) return true; + } + + return false; +} + +var longtoHex = function(value) { + var buffer = new Buffer(8); + var index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = value.low_ & 0xff; + buffer[index++] = (value.low_ >> 8) & 0xff; + buffer[index++] = (value.low_ >> 16) & 0xff; + buffer[index++] = (value.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = value.high_ & 0xff; + buffer[index++] = (value.high_ >> 8) & 0xff; + buffer[index++] = (value.high_ >> 16) & 0xff; + buffer[index++] = (value.high_ >> 24) & 0xff; + return buffer.reverse().toString('hex'); +} + +var int32toHex = function(value) { + var buffer = new Buffer(4); + var index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return buffer.reverse().toString('hex'); +} + +var Decimal128 = function(bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; +} + +Decimal128.fromString = function(string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if(!stringMatch + && ! infMatch + && ! nanMatch || string.length == 0) { + throw new Error("" + string + " not a valid Decimal128 string"); + } + + // Check if we have an illegal exponent format + if(stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error("" + string + " not a valid Decimal128 string"); + } + + // Get the negative or positive sign + if(string[index] == '+' || string[index] == '-') { + isNegative = string[index++] == '-'; + } + + // Check if user passed Infinity or NaN + if(!isDigit(string[index]) && string[index] != '.') { + if(string[index] == 'i' || string[index] == 'I') { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if(string[index] == 'N') { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + } + + // Read all the digits + while(isDigit(string[index]) || string[index] == '.') { + if(string[index] == '.') { + if(sawRadix) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if(nDigitsStored < 34) { + if(string[index] != '0' || foundNonZero) { + if(!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if(foundNonZero) { + nDigits = nDigits + 1; + } + + if(sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if(sawRadix && !nDigitsRead) { + throw new Error("" + string + " not a valid Decimal128 string"); + } + + // Read exponent if exists + if(string[index] == 'e' || string[index] == 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if(!match || !match[2]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if(string[index]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if(!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if(exponent != 0 && significantDigits != 1) { + while(string[firstNonZero + significantDigits - 1] == '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if(exponent <= radixPosition && radixPosition - exponent > (1 << 14)) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while(exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if(lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if(digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while(exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if(lastDigit == 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if(nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if(exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if(digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)) + } + } + } + + + // Round + // We've normalized the exponent, but might still need to round. + if((lastDigit - firstDigit + 1 < significantDigits) && string[significantDigits] != '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if(sawRadix && exponent == EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if(roundDigit >= 5) { + roundBit = 1; + + if(roundDigit == 5) { + roundBit = digits[lastDigit] % 2 == 1; + + for(var i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if(parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if(roundBit) { + var dIdx = lastDigit; + + for(; dIdx >= 0; dIdx--) { + if(++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if(dIdx == 0) { + if(exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)) + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if(significantDigits == 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if(lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for(; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + var dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for(; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for(; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString("100000000000000000")); + + significand.low = significand.low.add(significandLow); + + if(lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + var biasedExponent = (exponent + EXPONENT_BIAS); + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if(significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if(isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = new Buffer(16); + var index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = (dec.low.low_ >> 8) & 0xff; + buffer[index++] = (dec.low.low_ >> 16) & 0xff; + buffer[index++] = (dec.low.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = (dec.low.high_ >> 8) & 0xff; + buffer[index++] = (dec.low.high_ >> 16) & 0xff; + buffer[index++] = (dec.low.high_ >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = (dec.high.low_ >> 8) & 0xff; + buffer[index++] = (dec.high.low_ >> 16) & 0xff; + buffer[index++] = (dec.high.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = (dec.high.high_ >> 8) & 0xff; + buffer[index++] = (dec.high.high_ >> 16) & 0xff; + buffer[index++] = (dec.high.high_ >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); +} + +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Value of combination field for NaN +var COMBINATION_SNAN = 32; +// decimal128 exponent bias +var EXPONENT_BIAS = 6176; + +Decimal128.prototype.toString = function() { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for(var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = {parts: new Array(4)}; + // indexing variables + var i; + var j, k; + + // Output string + var string = []; + + // Unpack index + var index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack the high 64bits into a long + midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack index + var index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) }; + + if(dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = (high >> 26) & COMBINATION_MASK; + + if((combination >> 3) == 3) { + // Check for 'special' values + if(combination == COMBINATION_INFINITY) { + return string.join('') + "Infinity"; + } else if(combination == COMBINATION_NAN) { + return "NaN"; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if(significand128.parts[0] == 0 && significand128.parts[1] == 0 + && significand128.parts[2] == 0 && significand128.parts[3] == 0) { + is_zero = true; + } else { + for(var k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if(!least_digits) continue; + + for(var j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if(is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + var i = 0; + + while(!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if(scientific_exponent >= 34 || scientific_exponent <= -7 || + exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if(significand_digits) { + string.push('.'); + } + + for(var i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if(scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if(exponent >= 0) { + for(var i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if(radix_position > 0) { + for(var i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while(radix_position++ < 0) { + string.push('0'); + } + + for(var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); +} + +Decimal128.prototype.toJSON = function() { + return { "$numberDecimal": this.toString() }; +} + +module.exports = Decimal128; +module.exports.Decimal128 = Decimal128; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js new file mode 100644 index 00000000..82c5bd60 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if(!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +} + +module.exports = Double; +module.exports.Double = Double; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 00000000..6fca3924 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,121 @@ +// Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, m, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : (nBytes - 1), + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, m, c, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = bBE ? (nBytes-1) : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e+eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754;
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/int_32.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/int_32.js new file mode 100644 index 00000000..6c729f6b --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/int_32.js @@ -0,0 +1,26 @@ +var Int32 = function(value) { + if(!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ +Int32.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Int32.prototype.toJSON = function() { + return this.value; +} + +module.exports = Int32; +module.exports.Int32 = Int32; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js new file mode 100644 index 00000000..6f188850 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js @@ -0,0 +1,856 @@ +// 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && + other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || + other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Long.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long( + (value % Long.TWO_PWR_32_DBL_) | 0, + (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = + Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long;
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js new file mode 100644 index 00000000..f53c8c16 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js @@ -0,0 +1,126 @@ +"use strict" + +// We have an ES6 Map available, return the native instance +if(typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for(var i = 0; i < array.length; i++) { + if(array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + } + } + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + } + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if(value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + } + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for(var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + } + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + } + + Map.prototype.has = function(key) { + return this._values[key] != null; + } + + Map.prototype.keys = function(key) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.set = function(key, value) { + if(this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + return this; + } + + Map.prototype.values = function(key, value) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable:true, + get: function() { return this._keys.length; } + }); + + module.exports = Map; + module.exports.Map = Map; +}
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 00000000..03ee9cdd --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey;
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 00000000..5e120fbe --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey;
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 00000000..71bb1c91 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,362 @@ +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); +var hasBufferType = false; + +// Check if buffer exists +try { + if(Buffer && Buffer.from) hasBufferType = true; +} catch(err) {}; + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if(id instanceof ObjectID) return id; + if(!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if(id == null || typeof id == 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if(ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if(!valid && id != null){ + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } else if(valid && typeof id == 'string' && id.length == 24 && hasBufferType) { + return new ObjectID(Buffer.from(id, 'hex')); + } else if(valid && typeof id == 'string' && id.length == 24) { + return ObjectID.createFromHexString(id); + } else if(id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if(id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } + + if(ObjectID.cacheHexString) this.__id = this.toString('hex'); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if(!this.id || !this.id.length) { + throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); + } + + if(this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id buffer used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {Buffer} return the 12 byte id buffer string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' != typeof time) { + time = ~~(Date.now()/1000); + } + + // Use pid + var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF; + var inc = this.get_inc(); + // Buffer used + var buffer = new Buffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = (MACHINE_ID >> 8) & 0xff; + buffer[4] = (MACHINE_ID >> 16) & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = (pid >> 8) & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + // Return the buffer + return buffer; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @param {String} format The Buffer toString format parameter. +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function(format) { + // Is the id a buffer then use the buffer toString method to return the format + if(this.id && this.id.copy) { + return this.id.toString(format || 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals (otherId) { + var id; + + if(otherId instanceof ObjectID) { + return this.toString() == otherId.toString(); + } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) { + return otherId === this.id.toString('binary'); + } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) { + return otherId === this.id; + } else if(otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; +} + +/** +* @ignore +*/ +ObjectID.index = ~~(Math.random() * 0xFFFFFF); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk () { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime (time) { + var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Return the new objectId + return new ObjectID(buffer); +}; + +// Lookup tables +var encodeLookup = '0123456789abcdef'.split('') +var decodeLookup = [] +var i = 0 +while (i < 10) decodeLookup[0x30 + i] = i++ +while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++ + +var _Buffer = Buffer; +var convertToHex = function(bytes) { + return bytes.toString('hex'); +} + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString (string) { + // Throw an error if it's not a valid setup + if(typeof string === 'undefined' || string != null && string.length != 24) { + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } + + // Use Buffer.from method if available + if(hasBufferType) return new ObjectID(Buffer.from(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)] + } + + return new ObjectID(array); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if(id == null) return false; + + if(typeof id == 'number') { + return true; + } + + if(typeof id == 'string') { + return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id)); + } + + if(id instanceof ObjectID) { + return true; + } + + if(id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if(id.toHexString) { + return id.id.length == 12 || (id.id.length == 24 && checkForHexRegExp.test(id.id)); + } + + return false; +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true + , get: function () { + return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + } + , set: function (value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = (value >> 8) & 0xff; + this.id[1] = (value >> 16) & 0xff; + this.id[0] = (value >> 24) & 0xff; + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 00000000..53d338f5 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,152 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754 + , readIEEE754 = require('../float_parser').readIEEE754 + , Long = require('../long').Long + , Double = require('../double').Double + , Timestamp = require('../timestamp').Timestamp + , ObjectID = require('../objectid').ObjectID + , Symbol = require('../symbol').Symbol + , BSONRegExp = require('../regexp').BSONRegExp + , Code = require('../code').Code + , Decimal128 = require('../decimal128') + , MinKey = require('../min_key').MinKey + , MaxKey = require('../max_key').MaxKey + , DBRef = require('../db_ref').DBRef + , Binary = require('../binary').Binary; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + case 'undefined': + if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + return 0; + case 'boolean': + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } else if(value instanceof Decimal128 || value['_bsontype'] == 'Decimal128') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (16 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + + Buffer.byteLength(value.options, 'utf8') + 1 + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if(serializeFunctions) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; + } + } + } + + return 0; +} + +var BSON = {}; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = calculateObjectSize; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 00000000..35818a3c --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,653 @@ +"use strict" + +var readIEEE754 = require('../float_parser').readIEEE754, + f = require('util').format, + Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + Decimal128 = require('../decimal128'), + Int32 = require('../int_32'), + DBRef = require('../db_ref').DBRef, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var deserialize = function(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | buffer[index+1] << 8 | buffer[index+2] << 16 | buffer[index+3] << 24; + + // Ensure buffer is valid size + if(size < 5 || buffer.length < size || (size + index) > buffer.length) { + throw new Error("corrupt bson message"); + } + + // Illegal end value + if(buffer[index + size - 1] != 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +} + +var deserializeObject = function(buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) { + break; + } + + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if(elementType == BSON.BSON_DATA_STRING) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_OID) { + var oid = new Buffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if(elementType == BSON.BSON_DATA_INT && promoteValues == false) { + object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); + } else if(elementType == BSON.BSON_DATA_INT) { + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if(elementType == BSON.BSON_DATA_NUMBER && promoteValues == false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if(elementType == BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if(elementType == BSON.BSON_DATA_DATE) { + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if(elementType == BSON.BSON_DATA_BOOLEAN) { + if(buffer[index] != 0 && buffer[index] != 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] == 1; + } else if(elementType == BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + if(objectSize <= 0 || objectSize > (buffer.length - index)) throw new Error("bad embedded document length in bson"); + + // We have a raw value + if(raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if(fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for(var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if(buffer[index - 1] != 0) throw new Error('invalid array terminator byte'); + if(index != stopIndex) throw new Error('corrupted array bson'); + } else if(elementType == BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if(elementType == BSON.BSON_DATA_NULL) { + object[name] = null; + } else if(elementType == BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs && promoteValues == true) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + } else if(elementType == BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = new Buffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if(elementType == BSON.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if(binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if(binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if(binarySize > (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if(binarySize < (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if(promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if(binarySize > (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if(binarySize < (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if(promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if(elementType == BSON.BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_TIMESTAMP) { + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Timestamp(lowBits, highBits); + } else if(elementType == BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if(elementType == BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if(elementType == BSON.BSON_DATA_CODE) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if(totalSize < (4 + 4 + 4 + 1)) { + throw new Error("code_w_scope total size shorter minimum expected length"); + } + + // Get the code string size + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + + // Javascript function + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _index = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if(totalSize < (4 + 4 + objectSize + stringSize)) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if(totalSize > (4 + 4 + objectSize + stringSize)) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if(elementType == BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = new Buffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + var oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error("Detected unknown BSON type " + elementType.toString(16) + " for fieldname \"" + name + "\", are you using the latest BSON parser"); + } + } + + // Check if the deserialization was against a valid array/object + if(size != (index - startIndex)) { + if(isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ +BSON.BSON_DATA_DBPOINTER = 12; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = deserialize diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 00000000..4fdb0cfb --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,1001 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + Long = require('../long').Long, + Map = require('../map'), + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + BSONRegExp = require('../regexp').BSONRegExp, + Int32 = require('../int_32').Int32, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + Decimal128 = require('../decimal128'), + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +try { + var _Buffer = Uint8Array; +} catch(e) { + var _Buffer = Buffer; +} + +var regexp = /\x00/ + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} + +var serializeString = function(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = (size + 1 >> 24) & 0xff; + buffer[index + 2] = (size + 1 >> 16) & 0xff; + buffer[index + 1] = (size + 1 >> 8) & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeNumber = function(buffer, key, value, index, isArray) { + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +} + +var serializeNull = function(buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +var serializeBoolean = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +var serializeDate = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +var serializeRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error("value " + value.source + " must not contain null bytes"); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeBSONRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("pattern " + value.pattern + " must not contain null bytes"); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeMinMax = function(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +var serializeObjectId = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if(typeof value.id == 'string') { + buffer.write(value.id, index, 'binary') + } else if(value.id && value.id.copy){ + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + "] is not a valid ObjectId"); + } + + // Ajust index + return index + 12; +} + +var serializeBuffer = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +} + +var serializeObject = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + for(var i = 0; i < path.length; i++) { + if(path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + // Write size + var size = endIndex - index; + return endIndex; +} + +var serializeDecimal128 = function(buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; +} + +var serializeLong = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +var serializeInt32 = function(buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +} + +var serializeDouble = function(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +} + +var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if(value.scope && typeof value.scope == 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined) + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +var serializeBinary = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +} + +var serializeSymbol = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if(null != value.db) { + endIndex = serializeInto(buffer, { + '$ref': value.namespace + , '$id' : value.oid + , '$db' : value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + '$ref': value.namespace + , '$id' : value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} + +var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + var self = this; + + // Special case isArray + if(Array.isArray(object)) { + // Get object keys + for(var i = 0; i < object.length; i++) { + var key = "" + i; + var value = object[i]; + + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + var type = typeof value; + if(type == 'string') { + index = serializeString(buffer, key, value, index, true); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if(value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if(value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } else if(type == 'object' && value['_bsontype'] == 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if(value['_bsontype'] == 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if(object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while(!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if(done) continue; + + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + + if (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeNull(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if(type == 'object' && value['_bsontype'] == 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if(object.toBSON) { + if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); + object = object.toBSON(); + if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); + } + + // Iterate over all the keys + for(var key in object) { + var value = object[key]; + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + + if (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeNull(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if(type == 'object' && value['_bsontype'] == 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = serializeInto; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 00000000..9dd00662 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,30 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if(!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for(var i = 0; i < this.options.length; i++) { + if(!(this.options[i] == 'i' + || this.options[i] == 'm' + || this.options[i] == 'x' + || this.options[i] == 'l' + || this.options[i] == 's' + || this.options[i] == 'u' + )) { + throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 00000000..7681a4de --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,47 @@ +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if(!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +module.exports = Symbol; +module.exports.Symbol = Symbol;
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 00000000..7718cafc --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,856 @@ +// 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if(!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && + other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || + other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Timestamp.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = + Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp;
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json new file mode 100644 index 00000000..3b4945f3 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json @@ -0,0 +1,87 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "files": [ + "lib", + "index.js", + "browser_build", + "bower.json" + ], + "version": "1.0.2", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "contributors": [], + "repository": { + "type": "git", + "url": "git+https://github.com/mongodb/js-bson.git" + }, + "bugs": { + "url": "https://github.com/mongodb/js-bson/issues" + }, + "devDependencies": { + "benchmark": "1.0.0", + "colors": "1.1.0", + "nodeunit": "0.9.0", + "babel-core": "^6.14.0", + "babel-loader": "^6.2.5", + "babel-polyfill": "^6.13.0", + "babel-preset-es2015": "^6.14.0", + "babel-preset-stage-0": "^6.5.0", + "babel-register": "^6.14.0", + "webpack": "^1.13.2", + "webpack-polyfills-plugin": "0.0.9" + }, + "config": { + "native": false + }, + "main": "./index", + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "scripts": { + "test": "nodeunit ./test/node", + "build": "webpack --config ./webpack.dist.config.js" + }, + "browser": "lib/bson/bson.js", + "license": "Apache-2.0", + "gitHead": "e2fb5d9adfd1525b80814c203759a9598df99c94", + "homepage": "https://github.com/mongodb/js-bson#readme", + "_id": "bson@1.0.2", + "_shasum": "7e8a8066379f4faa2e4795dbe7ee2d595b3c4ae1", + "_from": "bson@>=1.0.1 <1.1.0", + "_npmVersion": "3.10.8", + "_nodeVersion": "6.9.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "dist": { + "shasum": "7e8a8066379f4faa2e4795dbe7ee2d595b3c4ae1", + "tarball": "https://registry.npmjs.org/bson/-/bson-1.0.2.tgz" + }, + "maintainers": [ + { + "name": "octave", + "email": "chinsay@gmail.com" + }, + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/bson-1.0.2.tgz_1483371724203_0.9188052278477699" + }, + "_resolved": "https://registry.npmjs.org/bson/-/bson-1.0.2.tgz" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore new file mode 100644 index 00000000..e920c167 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore @@ -0,0 +1,33 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml new file mode 100644 index 00000000..38de5c60 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4.2.1" +sudo: false diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE new file mode 100644 index 00000000..8dada3ed --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE @@ -0,0 +1,201 @@ + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md new file mode 100644 index 00000000..c0323f06 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md @@ -0,0 +1,2 @@ +# require_optional +Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js new file mode 100644 index 00000000..9754581a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js @@ -0,0 +1,109 @@ +var path = require('path'), + fs = require('fs'), + f = require('util').format, + resolveFrom = require('resolve-from'), + semver = require('semver'); + +var exists = fs.existsSync || path.existsSync; + +var find_package_json = function(location) { + var found = false; + + while(!found) { + if (exists(location + '/package.json')) { + found = location; + } else if (location !== '/') { + location = path.dirname(location); + } else { + return false; + } + } + + return location; +} + +var require_optional = function(name, options) { + options = options || {}; + options.strict = typeof options.strict == 'boolean' ? options.strict : true; + + // Current location + var location = __dirname; + // Check if we have a parent + if(module.parent) { + location = module.parent.filename; + } + + // Locate this module's package.json file + var location = find_package_json(location); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the package.json file + var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Is the name defined by interal file references + var parts = name.split(/\//); + + // Optional dependencies exist + if(!object.peerOptionalDependencies) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in package.json', parts[0])); + } else if(object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]]) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in package.json', parts[0])); + } + + // Unpack the expected version + var expectedVersions = object.peerOptionalDependencies[parts[0]]; + // The resolved package + var moduleEntry = undefined; + // Module file + var moduleEntryFile = name; + + try { + // Validate if it's possible to read the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + // Attempt to resolve in top level package + try { + // Get the module entry file + moduleEntryFile = resolveFrom(process.cwd(), name); + if(moduleEntryFile == null) return undefined; + // Attempt to resolve the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + if(err.code === 'MODULE_NOT_FOUND') return undefined; + } + } + + // Resolve the location of the module's package.json file + var location = find_package_json(require.resolve(moduleEntryFile)); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the module file + var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Get the version + var version = dependentOnModule.version; + // Validate if the found module satisfies the version id + if(semver.satisfies(version, expectedVersions) == false + && options.strict) { + var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); + error.code = 'OPTIONAL_MODULE_NOT_FOUND'; + throw error; + } + + // Satifies the module requirement + return moduleEntry; +} + +require_optional.exists = function(name) { + try { + var m = require_optional(name); + if(m === undefined) return false; + return true; + } catch(err) { + return false; + } +} + +module.exports = require_optional; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver new file mode 100644 index 00000000..d592e693 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../semver/bin/semver" "$@" + ret=$? +else + node "$basedir/../semver/bin/semver" "$@" + ret=$? +fi +exit $ret diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver.cmd b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver.cmd new file mode 100644 index 00000000..eabc7376 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" (
+ "%~dp0\node.exe" "%~dp0\..\semver\bin\semver" %*
+) ELSE (
+ @SETLOCAL
+ @SET PATHEXT=%PATHEXT:;.JS;=;%
+ node "%~dp0\..\semver\bin\semver" %*
+)
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js new file mode 100644 index 00000000..434159f1 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js @@ -0,0 +1,23 @@ +'use strict'; +var path = require('path'); +var Module = require('module'); + +module.exports = function (fromDir, moduleId) { + if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { + throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); + } + + fromDir = path.resolve(fromDir); + + var fromFile = path.join(fromDir, 'noop.js'); + + try { + return Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDir) + }); + } catch (err) { + return null; + } +}; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license new file mode 100644 index 00000000..654d0bfe --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +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. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json new file mode 100644 index 00000000..080176e4 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json @@ -0,0 +1,64 @@ +{ + "name": "resolve-from", + "version": "2.0.0", + "description": "Resolve the path of a module like require.resolve() but from a given path", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/resolve-from.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "path" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "gitHead": "583e0f8df06e1bc4d1c96d8d4f2484c745f522c3", + "bugs": { + "url": "https://github.com/sindresorhus/resolve-from/issues" + }, + "homepage": "https://github.com/sindresorhus/resolve-from", + "_id": "resolve-from@2.0.0", + "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "_from": "resolve-from@>=2.0.0 <3.0.0", + "_npmVersion": "2.14.7", + "_nodeVersion": "4.2.1", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "dist": { + "shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "tarball": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md new file mode 100644 index 00000000..bb4ca91e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md @@ -0,0 +1,58 @@ +# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) + +> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path + +Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. + + +## Install + +``` +$ npm install --save resolve-from +``` + + +## Usage + +```js +const resolveFrom = require('resolve-from'); + +// there's a file at `./foo/bar.js` + +resolveFrom('foo', './bar'); +//=> '/Users/sindresorhus/dev/test/foo/bar.js' +``` + + +## API + +### resolveFrom(fromDir, moduleId) + +#### fromDir + +Type: `string` + +Directory to resolve from. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Tip + +Create a partial using a bound function if you want to require from the same `fromDir` multiple times: + +```js +const resolveFromFoo = resolveFrom.bind(null, 'foo'); + +resolveFromFoo('./bar'); +resolveFromFoo('./baz'); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md new file mode 100644 index 00000000..cbd95654 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md @@ -0,0 +1,350 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Usage + + $ npm install semver + $ node + var semver = require('semver') + + semver.valid('1.2.3') // '1.2.3' + semver.valid('a.b.c') // null + semver.clean(' =v1.2.3 ') // '1.2.3' + semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true + semver.gt('1.2.3', '9.8.7') // false + semver.lt('1.2.3', '9.8.7') // true + +As a command-line utility: + + $ semver -h + + SemVer 5.1.0 + + A JavaScript implementation of the http://semver.org/ specification + Copyright Isaac Z. Schlueter + + Usage: semver [options] <version> [<version> [...]] + Prints valid versions sorted by SemVer precedence + + Options: + -r --range <range> + Print versions that match the specified range. + + -i --increment [<level>] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + + --preid <identifier> + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + + -l --loose + Interpret versions and ranges loosely + + Program exits successfully if any valid version satisfies + all supplied ranges, and prints all satisfying versions. + + If no satisfying versions are found, then exits failure. + + Versions are printed in ascending order, so supplying + multiple versions to the utility will just sort them. + +## Versions + +A "version" is described by the `v2.0.0` specification found at +<http://semver.org/>. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +> semver.inc('1.2.3', 'prerelease', 'beta') +'1.2.4-beta.0' +``` + +command-line example: + +```shell +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```shell +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `loose` boolean argument that, if +true, will be more forgiving about not-quite-valid semver strings. +The resulting output will always be 100% strict, of course. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver new file mode 100644 index 00000000..c5f2e857 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver @@ -0,0 +1,133 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + , versions = [] + , range = [] + , gt = [] + , lt = [] + , eq = [] + , inc = null + , version = require("../package.json").version + , loose = false + , identifier = undefined + , semver = require("../semver") + , reverse = false + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var i = a.indexOf('=') + if (i !== -1) { + a = a.slice(0, i) + argv.unshift(a.slice(i + 1)) + } + switch (a) { + case "-rv": case "-rev": case "--rev": case "--reverse": + reverse = true + break + case "-l": case "--loose": + loose = true + break + case "-v": case "--version": + versions.push(argv.shift()) + break + case "-i": case "--inc": case "--increment": + switch (argv[0]) { + case "major": case "minor": case "patch": case "prerelease": + case "premajor": case "preminor": case "prepatch": + inc = argv.shift() + break + default: + inc = "patch" + break + } + break + case "--preid": + identifier = argv.shift() + break + case "-r": case "--range": + range.push(argv.shift()) + break + case "-h": case "--help": case "-?": + return help() + default: + versions.push(a) + break + } + } + + versions = versions.filter(function (v) { + return semver.valid(v, loose) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) + return failInc() + + for (var i = 0, l = range.length; i < l ; i ++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], loose) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error("--inc can only be used on a single version with no range") + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? "rcompare" : "compare" + versions.sort(function (a, b) { + return semver[compare](a, b, loose) + }).map(function (v) { + return semver.clean(v, loose) + }).map(function (v) { + return inc ? semver.inc(v, inc, loose, identifier) : v + }).forEach(function (v,i,_) { console.log(v) }) +} + +function help () { + console.log(["SemVer " + version + ,"" + ,"A JavaScript implementation of the http://semver.org/ specification" + ,"Copyright Isaac Z. Schlueter" + ,"" + ,"Usage: semver [options] <version> [<version> [...]]" + ,"Prints valid versions sorted by SemVer precedence" + ,"" + ,"Options:" + ,"-r --range <range>" + ," Print versions that match the specified range." + ,"" + ,"-i --increment [<level>]" + ," Increment a version by the specified level. Level can" + ," be one of: major, minor, patch, premajor, preminor," + ," prepatch, or prerelease. Default level is 'patch'." + ," Only one version may be specified." + ,"" + ,"--preid <identifier>" + ," Identifier to be used to prefix premajor, preminor," + ," prepatch or prerelease version increments." + ,"" + ,"-l --loose" + ," Interpret versions and ranges loosely" + ,"" + ,"Program exits successfully if any valid version satisfies" + ,"all supplied ranges, and prints all satisfying versions." + ,"" + ,"If no satisfying versions are found, then exits failure." + ,"" + ,"Versions are printed in ascending order, so supplying" + ,"multiple versions to the utility will just sort them." + ].join("\n")) +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json new file mode 100644 index 00000000..d99bbf63 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json @@ -0,0 +1,60 @@ +{ + "name": "semver", + "version": "5.3.0", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "scripts": { + "test": "tap test/*.js" + }, + "devDependencies": { + "tap": "^2.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "./bin/semver" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "gitHead": "d21444a0658224b152ce54965d02dbe0856afb84", + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "homepage": "https://github.com/npm/node-semver#readme", + "_id": "semver@5.3.0", + "_shasum": "9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f", + "_from": "semver@>=5.1.0 <6.0.0", + "_npmVersion": "3.10.6", + "_nodeVersion": "4.4.4", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "dist": { + "shasum": "9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f", + "tarball": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + { + "name": "othiym23", + "email": "ogd@aoaioxxysz.net" + } + ], + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/semver-5.3.0.tgz_1468515166602_0.9155273644719273" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf new file mode 100644 index 00000000..25ebd5c8 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js new file mode 100644 index 00000000..5f1a3c5c --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js @@ -0,0 +1,1203 @@ +exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num; + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(b); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + + +exports.Range = Range; +function Range(range, loose) { + if ((range instanceof Range) && range.loose === loose) + return range; + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) + M = +M + 1; + else + m = +m + 1; + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + return versions.filter(function(version) { + return satisfies(version, range, loose); + }).sort(function(a, b) { + return rcompare(a, b, loose); + })[0] || null; +} + +exports.minSatisfying = minSatisfying; +function minSatisfying(versions, range, loose) { + return versions.filter(function(version) { + return satisfies(version, range, loose); + }).sort(function(a, b) { + return compare(a, b, loose); + })[0] || null; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} + +exports.prerelease = prerelease; +function prerelease(version, loose) { + var parsed = parse(version, loose); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json new file mode 100644 index 00000000..3718c617 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json @@ -0,0 +1,69 @@ +{ + "name": "require_optional", + "version": "1.0.0", + "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", + "main": "index.js", + "scripts": { + "test": "mocha" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/christkv/require_optional.git" + }, + "keywords": [ + "optional", + "require", + "optionalPeerDependencies" + ], + "author": { + "name": "Christian Kvalheim Amor" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/christkv/require_optional/issues" + }, + "homepage": "https://github.com/christkv/require_optional", + "dependencies": { + "semver": "^5.1.0", + "resolve-from": "^2.0.0" + }, + "devDependencies": { + "bson": "0.4.21", + "co": "4.6.0", + "es6-promise": "^3.0.2", + "mocha": "^2.4.5" + }, + "peerOptionalDependencies": { + "co": ">=5.6.0", + "es6-promise": "^3.0.2", + "es6-promise2": "^4.0.2", + "bson": "0.4.21" + }, + "gitHead": "8eac964c8e31166a8fb483d0d56025b185cee03f", + "_id": "require_optional@1.0.0", + "_shasum": "52a86137a849728eb60a55533617f8f914f59abf", + "_from": "require_optional@>=1.0.0 <1.1.0", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "52a86137a849728eb60a55533617f8f914f59abf", + "tarball": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.0.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-5-east.internal.npmjs.com", + "tmp": "tmp/require_optional-1.0.0.tgz_1454503936164_0.7571216486394405" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js new file mode 100644 index 00000000..181d834f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js @@ -0,0 +1,42 @@ +var assert = require('assert'), + require_optional = require('../'); + +describe('Require Optional', function() { + describe('top level require', function() { + it('should correctly require co library', function() { + var promise = require_optional('es6-promise'); + assert.ok(promise); + }); + + it('should fail to require es6-promise library', function() { + try { + require_optional('co'); + } catch(e) { + assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); + return; + } + + assert.ok(false); + }); + + it('should ignore optional library not defined', function() { + assert.equal(undefined, require_optional('es6-promise2')); + }); + }); + + describe('internal module file require', function() { + it('should correctly require co library', function() { + var Long = require_optional('bson/lib/bson/long.js'); + assert.ok(Long); + }); + }); + + describe('top level resolve', function() { + it('should correctly use exists method', function() { + assert.equal(false, require_optional.exists('co')); + assert.equal(true, require_optional.exists('es6-promise')); + assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); + assert.equal(false, require_optional.exists('es6-promise2')); + }); + }); +}); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/package.json new file mode 100644 index 00000000..2e97054a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/package.json @@ -0,0 +1,77 @@ +{ + "name": "mongodb-core", + "version": "2.1.2", + "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", + "main": "index.js", + "scripts": { + "test": "node test/runner.js -t functional", + "coverage": "nyc node test/runner.js -t functional -l && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls", + "lint": "eslint lib" + }, + "repository": { + "type": "git", + "url": "git://github.com/christkv/mongodb-core.git" + }, + "keywords": [ + "mongodb", + "core" + ], + "dependencies": { + "bson": "~1.0.1", + "require_optional": "~1.0.0" + }, + "devDependencies": { + "co": "^4.5.4", + "coveralls": "^2.11.6", + "es6-promise": "^3.0.2", + "gleak": "0.5.0", + "integra": "0.1.8", + "jsdoc": "3.3.0-alpha8", + "mkdirp": "0.5.0", + "mongodb-topology-manager": "1.0.6", + "mongodb-version-manager": "github:christkv/mongodb-version-manager#master", + "nyc": "^5.5.0", + "optimist": "latest", + "rimraf": "2.2.6", + "semver": "4.1.0" + }, + "peerOptionalDependencies": { + "kerberos": "~0.0", + "bson-ext": "1.0.1" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/christkv/mongodb-core/issues" + }, + "homepage": "https://github.com/christkv/mongodb-core", + "gitHead": "6783e5ac19a0374dfe0e8becf77ac95ed0ab3b97", + "_id": "mongodb-core@2.1.2", + "_shasum": "a11db773d34819cbeb97751241827137ab535aab", + "_from": "mongodb-core@2.1.2", + "_npmVersion": "3.10.8", + "_nodeVersion": "6.9.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "dist": { + "shasum": "a11db773d34819cbeb97751241827137ab535aab", + "tarball": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-2.1.2.tgz" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/mongodb-core-2.1.2.tgz_1481385289831_0.8470144462771714" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-2.1.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat new file mode 100644 index 00000000..25ccf0b6 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat @@ -0,0 +1,11000 @@ +1 2 +2 1 +3 0 +4 0 +5 1 +6 0 +7 0 +8 0 +9 0 +10 1 +11 0 +12 0 +13 0 +14 1 +15 0 +16 0 +17 0 +18 1 +19 0 +20 0 +21 0 +22 1 +23 0 +24 0 +25 0 +26 0 +27 1 +28 0 +29 0 +30 0 +31 1 +32 0 +33 0 +34 0 +35 0 +36 0 +37 1 +38 0 +39 0 +40 0 +41 0 +42 0 +43 1 +44 0 +45 0 +46 0 +47 0 +48 0 +49 0 +50 0 +51 0 +52 0 +53 0 +54 0 +55 0 +56 0 +57 0 +58 0 +59 1 +60 0 +61 2 +62 0 +63 0 +64 1 +65 0 +66 0 +67 0 +68 1 +69 0 +70 0 +71 0 +72 0 +73 1 +74 0 +75 0 +76 0 +77 0 +78 0 +79 1 +80 0 +81 0 +82 0 +83 0 +84 0 +85 0 +86 1 +87 0 +88 0 +89 0 +90 0 +91 0 +92 0 +93 1 +94 0 +95 0 +96 0 +97 0 +98 0 +99 0 +100 0 +101 1 +102 0 +103 0 +104 0 +105 0 +106 0 +107 0 +108 1 +109 0 +110 0 +111 0 +112 0 +113 0 +114 0 +115 1 +116 0 +117 0 +118 0 +119 1 +120 0 +121 0 +122 0 +123 0 +124 0 +125 0 +126 1 +127 0 +128 1 +129 0 +130 0 +131 0 +132 1 +133 1 +134 0 +135 0 +136 0 +137 1 +138 0 +139 0 +140 0 +141 0 +142 0 +143 0 +144 1 +145 0 +146 0 +147 0 +148 0 +149 0 +150 0 +151 0 +152 0 +153 1 +154 0 +155 0 +156 0 +157 0 +158 0 +159 0 +160 0 +161 0 +162 0 +163 0 +164 0 +165 0 +166 0 +167 0 +168 0 +169 0 +170 1 +171 0 +172 0 +173 0 +174 0 +175 0 +176 0 +177 0 +178 1 +179 0 +180 0 +181 0 +182 0 +183 0 +184 0 +185 0 +186 1 +187 0 +188 0 +189 0 +190 0 +191 0 +192 1 +193 0 +194 0 +195 0 +196 1 +197 0 +198 0 +199 0 +200 1 +201 0 +202 0 +203 0 +204 0 +205 0 +206 0 +207 1 +208 0 +209 0 +210 0 +211 0 +212 0 +213 0 +214 0 +215 1 +216 0 +217 0 +218 0 +219 0 +220 0 +221 0 +222 0 +223 1 +224 0 +225 0 +226 0 +227 0 +228 0 +229 0 +230 1 +231 0 +232 0 +233 0 +234 0 +235 0 +236 0 +237 1 +238 0 +239 0 +240 0 +241 0 +242 0 +243 0 +244 0 +245 1 +246 0 +247 0 +248 0 +249 0 +250 0 +251 0 +252 0 +253 0 +254 1 +255 0 +256 0 +257 0 +258 0 +259 1 +260 0 +261 0 +262 0 +263 0 +264 0 +265 1 +266 0 +267 0 +268 0 +269 0 +270 0 +271 0 +272 1 +273 0 +274 0 +275 0 +276 0 +277 0 +278 0 +279 0 +280 0 +281 1 +282 0 +283 1 +284 0 +285 0 +286 1 +287 0 +288 0 +289 0 +290 0 +291 1 +292 0 +293 0 +294 0 +295 0 +296 1 +297 0 +298 0 +299 0 +300 0 +301 0 +302 0 +303 1 +304 0 +305 0 +306 0 +307 0 +308 0 +309 1 +310 0 +311 0 +312 0 +313 0 +314 0 +315 0 +316 1 +317 0 +318 0 +319 0 +320 0 +321 0 +322 0 +323 0 +324 0 +325 1 +326 0 +327 0 +328 0 +329 0 +330 0 +331 0 +332 0 +333 0 +334 1 +335 0 +336 0 +337 0 +338 0 +339 0 +340 0 +341 0 +342 0 +343 1 +344 0 +345 0 +346 0 +347 0 +348 0 +349 0 +350 0 +351 0 +352 1 +353 0 +354 0 +355 0 +356 0 +357 0 +358 0 +359 0 +360 0 +361 1 +362 0 +363 0 +364 0 +365 0 +366 0 +367 0 +368 0 +369 1 +370 0 +371 0 +372 0 +373 0 +374 0 +375 0 +376 0 +377 1 +378 0 +379 0 +380 0 +381 0 +382 0 +383 0 +384 0 +385 1 +386 0 +387 0 +388 0 +389 0 +390 1 +391 0 +392 0 +393 0 +394 0 +395 0 +396 0 +397 0 +398 0 +399 0 +400 0 +401 0 +402 1 +403 0 +404 0 +405 0 +406 0 +407 0 +408 0 +409 0 +410 1 +411 0 +412 0 +413 0 +414 0 +415 0 +416 0 +417 0 +418 0 +419 1 +420 0 +421 0 +422 0 +423 0 +424 0 +425 0 +426 0 +427 1 +428 0 +429 0 +430 0 +431 0 +432 0 +433 0 +434 0 +435 1 +436 0 +437 0 +438 0 +439 0 +440 0 +441 0 +442 0 +443 1 +444 0 +445 0 +446 0 +447 0 +448 0 +449 0 +450 1 +451 0 +452 0 +453 0 +454 0 +455 0 +456 1 +457 0 +458 0 +459 0 +460 0 +461 0 +462 0 +463 0 +464 1 +465 0 +466 0 +467 0 +468 0 +469 0 +470 0 +471 0 +472 0 +473 1 +474 0 +475 0 +476 0 +477 0 +478 0 +479 0 +480 0 +481 1 +482 0 +483 0 +484 0 +485 0 +486 0 +487 0 +488 0 +489 0 +490 1 +491 0 +492 0 +493 0 +494 0 +495 0 +496 0 +497 0 +498 0 +499 0 +500 0 +501 0 +502 0 +503 0 +504 1 +505 0 +506 0 +507 0 +508 0 +509 0 +510 0 +511 0 +512 1 +513 0 +514 0 +515 0 +516 0 +517 0 +518 0 +519 4 +520 0 +521 1 +522 0 +523 0 +524 0 +525 1 +526 0 +527 0 +528 0 +529 0 +530 1 +531 0 +532 0 +533 0 +534 1 +535 0 +536 0 +537 0 +538 0 +539 1 +540 0 +541 0 +542 0 +543 0 +544 0 +545 1 +546 0 +547 0 +548 0 +549 0 +550 0 +551 1 +552 0 +553 0 +554 0 +555 0 +556 0 +557 0 +558 0 +559 1 +560 0 +561 0 +562 0 +563 0 +564 0 +565 0 +566 0 +567 1 +568 0 +569 0 +570 0 +571 0 +572 0 +573 0 +574 0 +575 0 +576 1 +577 0 +578 0 +579 0 +580 0 +581 0 +582 0 +583 0 +584 0 +585 0 +586 0 +587 0 +588 0 +589 0 +590 0 +591 0 +592 0 +593 1 +594 0 +595 0 +596 0 +597 0 +598 0 +599 0 +600 0 +601 0 +602 1 +603 0 +604 0 +605 0 +606 0 +607 0 +608 0 +609 0 +610 0 +611 1 +612 0 +613 0 +614 0 +615 0 +616 0 +617 0 +618 0 +619 0 +620 1 +621 0 +622 0 +623 0 +624 0 +625 0 +626 0 +627 0 +628 0 +629 1 +630 0 +631 0 +632 0 +633 0 +634 0 +635 0 +636 0 +637 0 +638 0 +639 1 +640 0 +641 0 +642 0 +643 0 +644 0 +645 0 +646 1 +647 0 +648 0 +649 0 +650 0 +651 0 +652 1 +653 1 +654 0 +655 0 +656 1 +657 0 +658 1 +659 0 +660 0 +661 0 +662 0 +663 0 +664 1 +665 0 +666 0 +667 0 +668 0 +669 0 +670 0 +671 0 +672 0 +673 0 +674 0 +675 0 +676 0 +677 1 +678 0 +679 0 +680 0 +681 0 +682 0 +683 0 +684 0 +685 0 +686 1 +687 0 +688 0 +689 0 +690 0 +691 0 +692 0 +693 0 +694 0 +695 1 +696 0 +697 0 +698 0 +699 0 +700 0 +701 0 +702 0 +703 1 +704 0 +705 0 +706 0 +707 0 +708 0 +709 0 +710 0 +711 0 +712 1 +713 0 +714 0 +715 0 +716 0 +717 0 +718 0 +719 0 +720 1 +721 0 +722 0 +723 0 +724 0 +725 0 +726 0 +727 0 +728 1 +729 0 +730 0 +731 0 +732 0 +733 0 +734 0 +735 0 +736 0 +737 1 +738 0 +739 0 +740 0 +741 0 +742 0 +743 0 +744 0 +745 1 +746 0 +747 0 +748 0 +749 0 +750 0 +751 0 +752 0 +753 1 +754 0 +755 0 +756 0 +757 0 +758 0 +759 0 +760 0 +761 1 +762 0 +763 0 +764 0 +765 0 +766 0 +767 0 +768 1 +769 0 +770 0 +771 0 +772 0 +773 0 +774 0 +775 0 +776 0 +777 1 +778 0 +779 0 +780 0 +781 0 +782 0 +783 0 +784 0 +785 0 +786 1 +787 0 +788 0 +789 0 +790 0 +791 0 +792 1 +793 0 +794 0 +795 0 +796 0 +797 0 +798 0 +799 0 +800 0 +801 1 +802 0 +803 0 +804 0 +805 0 +806 0 +807 0 +808 0 +809 0 +810 0 +811 0 +812 0 +813 0 +814 0 +815 0 +816 0 +817 0 +818 0 +819 0 +820 1 +821 0 +822 0 +823 0 +824 0 +825 0 +826 0 +827 0 +828 0 +829 1 +830 0 +831 0 +832 0 +833 0 +834 0 +835 0 +836 0 +837 1 +838 0 +839 0 +840 0 +841 0 +842 0 +843 0 +844 0 +845 0 +846 1 +847 0 +848 0 +849 0 +850 0 +851 0 +852 0 +853 0 +854 0 +855 2 +856 0 +857 0 +858 0 +859 0 +860 0 +861 0 +862 1 +863 0 +864 0 +865 0 +866 0 +867 0 +868 0 +869 0 +870 0 +871 1 +872 0 +873 0 +874 0 +875 0 +876 0 +877 0 +878 1 +879 0 +880 0 +881 0 +882 0 +883 0 +884 0 +885 0 +886 0 +887 0 +888 0 +889 0 +890 0 +891 0 +892 0 +893 0 +894 0 +895 0 +896 1 +897 0 +898 0 +899 0 +900 0 +901 0 +902 0 +903 0 +904 0 +905 0 +906 1 +907 0 +908 0 +909 0 +910 0 +911 0 +912 0 +913 0 +914 0 +915 1 +916 0 +917 0 +918 0 +919 0 +920 0 +921 0 +922 1 +923 0 +924 0 +925 0 +926 0 +927 0 +928 0 +929 0 +930 1 +931 0 +932 0 +933 0 +934 0 +935 0 +936 0 +937 0 +938 0 +939 1 +940 0 +941 0 +942 0 +943 0 +944 0 +945 0 +946 0 +947 0 +948 0 +949 1 +950 0 +951 0 +952 0 +953 0 +954 0 +955 0 +956 0 +957 0 +958 1 +959 0 +960 0 +961 0 +962 0 +963 0 +964 0 +965 0 +966 0 +967 0 +968 1 +969 0 +970 0 +971 0 +972 0 +973 0 +974 0 +975 0 +976 0 +977 0 +978 1 +979 0 +980 0 +981 0 +982 0 +983 0 +984 0 +985 0 +986 0 +987 0 +988 1 +989 0 +990 0 +991 0 +992 0 +993 0 +994 0 +995 0 +996 0 +997 1 +998 0 +999 0 +1000 0 +1001 0 +1002 0 +1003 0 +1004 0 +1005 1 +1006 0 +1007 0 +1008 0 +1009 0 +1010 0 +1011 0 +1012 1 +1013 0 +1014 0 +1015 0 +1016 0 +1017 0 +1018 0 +1019 0 +1020 0 +1021 0 +1022 0 +1023 0 +1024 0 +1025 0 +1026 0 +1027 0 +1028 0 +1029 0 +1030 0 +1031 1 +1032 0 +1033 0 +1034 0 +1035 0 +1036 0 +1037 0 +1038 0 +1039 0 +1040 0 +1041 0 +1042 1 +1043 0 +1044 0 +1045 0 +1046 0 +1047 0 +1048 0 +1049 0 +1050 1 +1051 0 +1052 0 +1053 0 +1054 0 +1055 0 +1056 0 +1057 1 +1058 0 +1059 0 +1060 0 +1061 0 +1062 0 +1063 0 +1064 0 +1065 0 +1066 0 +1067 1 +1068 0 +1069 0 +1070 0 +1071 0 +1072 0 +1073 0 +1074 0 +1075 0 +1076 0 +1077 1 +1078 0 +1079 0 +1080 0 +1081 0 +1082 0 +1083 0 +1084 0 +1085 0 +1086 0 +1087 1 +1088 0 +1089 0 +1090 0 +1091 0 +1092 0 +1093 0 +1094 1 +1095 0 +1096 0 +1097 0 +1098 0 +1099 0 +1100 0 +1101 0 +1102 1 +1103 0 +1104 0 +1105 0 +1106 0 +1107 0 +1108 0 +1109 0 +1110 0 +1111 1 +1112 0 +1113 0 +1114 0 +1115 0 +1116 0 +1117 0 +1118 0 +1119 0 +1120 1 +1121 0 +1122 0 +1123 0 +1124 0 +1125 0 +1126 0 +1127 0 +1128 0 +1129 0 +1130 1 +1131 0 +1132 0 +1133 0 +1134 0 +1135 0 +1136 0 +1137 0 +1138 0 +1139 0 +1140 1 +1141 0 +1142 0 +1143 0 +1144 0 +1145 0 +1146 0 +1147 0 +1148 0 +1149 0 +1150 0 +1151 1 +1152 0 +1153 0 +1154 0 +1155 0 +1156 0 +1157 0 +1158 0 +1159 0 +1160 1 +1161 0 +1162 0 +1163 0 +1164 0 +1165 0 +1166 0 +1167 1 +1168 0 +1169 0 +1170 0 +1171 0 +1172 0 +1173 0 +1174 0 +1175 0 +1176 1 +1177 0 +1178 0 +1179 0 +1180 0 +1181 0 +1182 1 +1183 0 +1184 0 +1185 0 +1186 0 +1187 0 +1188 0 +1189 0 +1190 1 +1191 0 +1192 0 +1193 0 +1194 0 +1195 0 +1196 0 +1197 0 +1198 1 +1199 0 +1200 0 +1201 0 +1202 0 +1203 0 +1204 0 +1205 0 +1206 1 +1207 0 +1208 0 +1209 0 +1210 0 +1211 0 +1212 0 +1213 0 +1214 0 +1215 0 +1216 1 +1217 0 +1218 0 +1219 0 +1220 0 +1221 0 +1222 0 +1223 0 +1224 0 +1225 0 +1226 1 +1227 0 +1228 0 +1229 0 +1230 0 +1231 0 +1232 0 +1233 0 +1234 0 +1235 0 +1236 0 +1237 0 +1238 0 +1239 1 +1240 0 +1241 0 +1242 0 +1243 0 +1244 0 +1245 0 +1246 0 +1247 0 +1248 1 +1249 0 +1250 0 +1251 0 +1252 0 +1253 0 +1254 0 +1255 0 +1256 0 +1257 1 +1258 0 +1259 0 +1260 0 +1261 0 +1262 0 +1263 0 +1264 0 +1265 0 +1266 1 +1267 0 +1268 0 +1269 0 +1270 0 +1271 0 +1272 0 +1273 0 +1274 0 +1275 1 +1276 0 +1277 0 +1278 0 +1279 0 +1280 0 +1281 0 +1282 0 +1283 0 +1284 0 +1285 0 +1286 0 +1287 0 +1288 0 +1289 0 +1290 0 +1291 0 +1292 0 +1293 1 +1294 0 +1295 0 +1296 0 +1297 0 +1298 0 +1299 0 +1300 0 +1301 0 +1302 0 +1303 0 +1304 0 +1305 0 +1306 0 +1307 0 +1308 0 +1309 0 +1310 1 +1311 0 +1312 0 +1313 0 +1314 0 +1315 0 +1316 0 +1317 0 +1318 1 +1319 0 +1320 0 +1321 0 +1322 0 +1323 0 +1324 0 +1325 0 +1326 0 +1327 1 +1328 0 +1329 0 +1330 0 +1331 0 +1332 0 +1333 0 +1334 0 +1335 0 +1336 1 +1337 0 +1338 0 +1339 0 +1340 0 +1341 0 +1342 0 +1343 0 +1344 0 +1345 0 +1346 1 +1347 0 +1348 0 +1349 0 +1350 0 +1351 0 +1352 0 +1353 0 +1354 0 +1355 0 +1356 1 +1357 0 +1358 0 +1359 0 +1360 0 +1361 0 +1362 0 +1363 0 +1364 0 +1365 1 +1366 0 +1367 0 +1368 0 +1369 0 +1370 0 +1371 0 +1372 0 +1373 1 +1374 0 +1375 0 +1376 0 +1377 0 +1378 0 +1379 0 +1380 0 +1381 0 +1382 0 +1383 1 +1384 0 +1385 0 +1386 0 +1387 0 +1388 0 +1389 0 +1390 0 +1391 0 +1392 1 +1393 0 +1394 0 +1395 0 +1396 0 +1397 0 +1398 0 +1399 0 +1400 1 +1401 0 +1402 0 +1403 0 +1404 0 +1405 0 +1406 0 +1407 0 +1408 0 +1409 0 +1410 1 +1411 0 +1412 0 +1413 0 +1414 0 +1415 0 +1416 0 +1417 0 +1418 0 +1419 0 +1420 1 +1421 0 +1422 0 +1423 0 +1424 0 +1425 0 +1426 0 +1427 0 +1428 0 +1429 0 +1430 0 +1431 1 +1432 0 +1433 0 +1434 0 +1435 0 +1436 0 +1437 0 +1438 0 +1439 0 +1440 0 +1441 1 +1442 0 +1443 0 +1444 0 +1445 0 +1446 0 +1447 2 +1448 0 +1449 0 +1450 0 +1451 0 +1452 0 +1453 0 +1454 0 +1455 1 +1456 0 +1457 0 +1458 0 +1459 0 +1460 0 +1461 0 +1462 0 +1463 0 +1464 0 +1465 1 +1466 0 +1467 0 +1468 0 +1469 0 +1470 0 +1471 0 +1472 0 +1473 0 +1474 0 +1475 1 +1476 0 +1477 0 +1478 0 +1479 0 +1480 0 +1481 0 +1482 0 +1483 0 +1484 0 +1485 1 +1486 0 +1487 0 +1488 0 +1489 0 +1490 0 +1491 0 +1492 0 +1493 0 +1494 1 +1495 0 +1496 0 +1497 0 +1498 0 +1499 0 +1500 0 +1501 0 +1502 0 +1503 1 +1504 0 +1505 0 +1506 0 +1507 0 +1508 0 +1509 0 +1510 0 +1511 0 +1512 0 +1513 0 +1514 0 +1515 0 +1516 0 +1517 0 +1518 0 +1519 0 +1520 1 +1521 0 +1522 0 +1523 0 +1524 0 +1525 0 +1526 0 +1527 0 +1528 0 +1529 1 +1530 0 +1531 0 +1532 0 +1533 0 +1534 0 +1535 0 +1536 0 +1537 0 +1538 0 +1539 1 +1540 0 +1541 0 +1542 0 +1543 0 +1544 0 +1545 0 +1546 0 +1547 0 +1548 1 +1549 0 +1550 0 +1551 0 +1552 0 +1553 0 +1554 0 +1555 0 +1556 0 +1557 1 +1558 0 +1559 0 +1560 0 +1561 0 +1562 0 +1563 0 +1564 0 +1565 0 +1566 0 +1567 1 +1568 0 +1569 0 +1570 0 +1571 0 +1572 0 +1573 0 +1574 0 +1575 1 +1576 0 +1577 0 +1578 0 +1579 0 +1580 0 +1581 0 +1582 0 +1583 0 +1584 1 +1585 0 +1586 0 +1587 0 +1588 0 +1589 0 +1590 0 +1591 0 +1592 0 +1593 1 +1594 0 +1595 0 +1596 0 +1597 0 +1598 0 +1599 0 +1600 0 +1601 0 +1602 1 +1603 0 +1604 0 +1605 0 +1606 0 +1607 0 +1608 0 +1609 0 +1610 0 +1611 1 +1612 0 +1613 0 +1614 0 +1615 0 +1616 0 +1617 0 +1618 0 +1619 0 +1620 0 +1621 1 +1622 0 +1623 0 +1624 0 +1625 0 +1626 0 +1627 0 +1628 0 +1629 0 +1630 0 +1631 1 +1632 0 +1633 0 +1634 0 +1635 0 +1636 0 +1637 0 +1638 0 +1639 0 +1640 1 +1641 0 +1642 0 +1643 0 +1644 0 +1645 0 +1646 0 +1647 0 +1648 0 +1649 0 +1650 1 +1651 0 +1652 0 +1653 0 +1654 0 +1655 0 +1656 0 +1657 0 +1658 0 +1659 0 +1660 1 +1661 0 +1662 0 +1663 0 +1664 0 +1665 0 +1666 0 +1667 0 +1668 0 +1669 0 +1670 1 +1671 0 +1672 0 +1673 0 +1674 0 +1675 0 +1676 0 +1677 0 +1678 0 +1679 0 +1680 1 +1681 0 +1682 0 +1683 0 +1684 0 +1685 0 +1686 0 +1687 0 +1688 0 +1689 0 +1690 1 +1691 0 +1692 0 +1693 0 +1694 0 +1695 0 +1696 0 +1697 0 +1698 0 +1699 0 +1700 0 +1701 1 +1702 0 +1703 0 +1704 0 +1705 0 +1706 0 +1707 0 +1708 1 +1709 0 +1710 0 +1711 0 +1712 0 +1713 0 +1714 0 +1715 0 +1716 1 +1717 0 +1718 0 +1719 0 +1720 0 +1721 0 +1722 0 +1723 0 +1724 0 +1725 0 +1726 0 +1727 0 +1728 0 +1729 0 +1730 0 +1731 0 +1732 0 +1733 0 +1734 1 +1735 0 +1736 0 +1737 0 +1738 0 +1739 0 +1740 0 +1741 0 +1742 0 +1743 1 +1744 0 +1745 0 +1746 0 +1747 0 +1748 0 +1749 0 +1750 0 +1751 0 +1752 0 +1753 1 +1754 0 +1755 0 +1756 0 +1757 0 +1758 0 +1759 0 +1760 0 +1761 0 +1762 0 +1763 1 +1764 0 +1765 0 +1766 0 +1767 0 +1768 0 +1769 0 +1770 0 +1771 0 +1772 0 +1773 1 +1774 0 +1775 0 +1776 0 +1777 0 +1778 0 +1779 0 +1780 0 +1781 0 +1782 0 +1783 1 +1784 0 +1785 0 +1786 0 +1787 0 +1788 0 +1789 0 +1790 0 +1791 0 +1792 0 +1793 1 +1794 0 +1795 0 +1796 0 +1797 0 +1798 0 +1799 0 +1800 0 +1801 0 +1802 0 +1803 1 +1804 0 +1805 0 +1806 0 +1807 0 +1808 0 +1809 0 +1810 0 +1811 0 +1812 0 +1813 1 +1814 0 +1815 0 +1816 0 +1817 0 +1818 0 +1819 0 +1820 0 +1821 0 +1822 1 +1823 0 +1824 0 +1825 0 +1826 0 +1827 0 +1828 0 +1829 1 +1830 0 +1831 0 +1832 0 +1833 0 +1834 0 +1835 0 +1836 0 +1837 0 +1838 0 +1839 1 +1840 0 +1841 0 +1842 0 +1843 0 +1844 0 +1845 0 +1846 0 +1847 0 +1848 0 +1849 1 +1850 0 +1851 0 +1852 0 +1853 0 +1854 0 +1855 0 +1856 0 +1857 0 +1858 0 +1859 1 +1860 0 +1861 0 +1862 0 +1863 0 +1864 0 +1865 0 +1866 0 +1867 0 +1868 0 +1869 1 +1870 0 +1871 0 +1872 0 +1873 0 +1874 0 +1875 0 +1876 0 +1877 0 +1878 0 +1879 1 +1880 0 +1881 0 +1882 0 +1883 0 +1884 0 +1885 0 +1886 0 +1887 0 +1888 0 +1889 1 +1890 0 +1891 0 +1892 0 +1893 0 +1894 0 +1895 0 +1896 0 +1897 0 +1898 0 +1899 0 +1900 0 +1901 0 +1902 0 +1903 0 +1904 0 +1905 0 +1906 0 +1907 0 +1908 0 +1909 0 +1910 1 +1911 0 +1912 0 +1913 0 +1914 0 +1915 0 +1916 0 +1917 0 +1918 0 +1919 0 +1920 0 +1921 0 +1922 0 +1923 0 +1924 0 +1925 0 +1926 0 +1927 0 +1928 0 +1929 0 +1930 1 +1931 0 +1932 0 +1933 0 +1934 0 +1935 0 +1936 0 +1937 0 +1938 0 +1939 1 +1940 0 +1941 0 +1942 0 +1943 0 +1944 0 +1945 0 +1946 0 +1947 0 +1948 0 +1949 1 +1950 0 +1951 0 +1952 0 +1953 0 +1954 0 +1955 0 +1956 0 +1957 0 +1958 1 +1959 0 +1960 0 +1961 0 +1962 0 +1963 0 +1964 0 +1965 0 +1966 0 +1967 0 +1968 1 +1969 0 +1970 0 +1971 0 +1972 0 +1973 0 +1974 0 +1975 0 +1976 0 +1977 0 +1978 1 +1979 0 +1980 0 +1981 0 +1982 0 +1983 0 +1984 0 +1985 0 +1986 0 +1987 0 +1988 1 +1989 0 +1990 0 +1991 0 +1992 0 +1993 0 +1994 0 +1995 0 +1996 1 +1997 0 +1998 0 +1999 0 +2000 0 +2001 0 +2002 0 +2003 0 +2004 1 +2005 0 +2006 0 +2007 0 +2008 0 +2009 0 +2010 0 +2011 0 +2012 0 +2013 0 +2014 1 +2015 0 +2016 0 +2017 0 +2018 0 +2019 0 +2020 0 +2021 0 +2022 0 +2023 0 +2024 1 +2025 0 +2026 0 +2027 0 +2028 0 +2029 0 +2030 0 +2031 0 +2032 0 +2033 1 +2034 0 +2035 0 +2036 0 +2037 0 +2038 0 +2039 0 +2040 0 +2041 2 +2042 0 +2043 0 +2044 0 +2045 0 +2046 0 +2047 0 +2048 0 +2049 1 +2050 0 +2051 0 +2052 0 +2053 0 +2054 0 +2055 0 +2056 0 +2057 0 +2058 0 +2059 0 +2060 0 +2061 0 +2062 0 +2063 0 +2064 0 +2065 0 +2066 0 +2067 1 +2068 0 +2069 0 +2070 0 +2071 0 +2072 0 +2073 0 +2074 0 +2075 0 +2076 1 +2077 0 +2078 0 +2079 0 +2080 0 +2081 0 +2082 0 +2083 0 +2084 0 +2085 0 +2086 1 +2087 0 +2088 0 +2089 0 +2090 0 +2091 0 +2092 0 +2093 0 +2094 0 +2095 0 +2096 1 +2097 0 +2098 0 +2099 0 +2100 0 +2101 0 +2102 0 +2103 0 +2104 0 +2105 1 +2106 0 +2107 0 +2108 0 +2109 0 +2110 0 +2111 0 +2112 0 +2113 0 +2114 0 +2115 0 +2116 1 +2117 0 +2118 0 +2119 0 +2120 0 +2121 0 +2122 0 +2123 0 +2124 0 +2125 1 +2126 0 +2127 0 +2128 0 +2129 0 +2130 0 +2131 0 +2132 0 +2133 1 +2134 0 +2135 0 +2136 0 +2137 0 +2138 0 +2139 0 +2140 0 +2141 1 +2142 0 +2143 0 +2144 0 +2145 0 +2146 0 +2147 0 +2148 0 +2149 0 +2150 1 +2151 0 +2152 0 +2153 0 +2154 0 +2155 0 +2156 0 +2157 0 +2158 0 +2159 1 +2160 0 +2161 0 +2162 0 +2163 0 +2164 0 +2165 0 +2166 0 +2167 0 +2168 0 +2169 1 +2170 0 +2171 0 +2172 0 +2173 0 +2174 0 +2175 0 +2176 0 +2177 1 +2178 0 +2179 0 +2180 0 +2181 0 +2182 0 +2183 0 +2184 0 +2185 0 +2186 0 +2187 1 +2188 0 +2189 0 +2190 0 +2191 0 +2192 0 +2193 0 +2194 0 +2195 0 +2196 1 +2197 0 +2198 0 +2199 0 +2200 0 +2201 0 +2202 0 +2203 0 +2204 1 +2205 0 +2206 0 +2207 0 +2208 0 +2209 0 +2210 0 +2211 0 +2212 0 +2213 0 +2214 1 +2215 0 +2216 0 +2217 0 +2218 0 +2219 0 +2220 0 +2221 0 +2222 0 +2223 0 +2224 1 +2225 0 +2226 0 +2227 0 +2228 0 +2229 0 +2230 0 +2231 0 +2232 0 +2233 1 +2234 0 +2235 0 +2236 0 +2237 0 +2238 0 +2239 0 +2240 0 +2241 0 +2242 1 +2243 0 +2244 0 +2245 0 +2246 0 +2247 0 +2248 0 +2249 0 +2250 1 +2251 0 +2252 0 +2253 0 +2254 0 +2255 0 +2256 0 +2257 0 +2258 0 +2259 0 +2260 1 +2261 0 +2262 0 +2263 0 +2264 0 +2265 0 +2266 0 +2267 0 +2268 0 +2269 0 +2270 1 +2271 0 +2272 0 +2273 0 +2274 0 +2275 0 +2276 0 +2277 0 +2278 0 +2279 0 +2280 1 +2281 0 +2282 0 +2283 0 +2284 0 +2285 0 +2286 0 +2287 0 +2288 0 +2289 0 +2290 1 +2291 0 +2292 0 +2293 0 +2294 0 +2295 0 +2296 0 +2297 0 +2298 1 +2299 0 +2300 0 +2301 0 +2302 0 +2303 0 +2304 0 +2305 0 +2306 1 +2307 0 +2308 0 +2309 0 +2310 0 +2311 0 +2312 0 +2313 0 +2314 0 +2315 1 +2316 0 +2317 0 +2318 0 +2319 0 +2320 0 +2321 0 +2322 0 +2323 0 +2324 0 +2325 1 +2326 0 +2327 0 +2328 0 +2329 0 +2330 0 +2331 0 +2332 0 +2333 0 +2334 0 +2335 1 +2336 0 +2337 0 +2338 0 +2339 0 +2340 0 +2341 0 +2342 0 +2343 0 +2344 0 +2345 1 +2346 0 +2347 0 +2348 0 +2349 0 +2350 0 +2351 0 +2352 0 +2353 1 +2354 0 +2355 0 +2356 0 +2357 0 +2358 0 +2359 0 +2360 0 +2361 1 +2362 0 +2363 0 +2364 0 +2365 0 +2366 0 +2367 0 +2368 0 +2369 0 +2370 0 +2371 1 +2372 0 +2373 0 +2374 0 +2375 0 +2376 0 +2377 0 +2378 0 +2379 0 +2380 0 +2381 1 +2382 0 +2383 0 +2384 0 +2385 0 +2386 0 +2387 0 +2388 0 +2389 0 +2390 1 +2391 0 +2392 0 +2393 0 +2394 0 +2395 0 +2396 0 +2397 0 +2398 0 +2399 0 +2400 0 +2401 0 +2402 0 +2403 0 +2404 0 +2405 0 +2406 0 +2407 0 +2408 0 +2409 0 +2410 0 +2411 1 +2412 0 +2413 0 +2414 0 +2415 0 +2416 0 +2417 0 +2418 0 +2419 0 +2420 0 +2421 1 +2422 0 +2423 0 +2424 0 +2425 0 +2426 0 +2427 0 +2428 0 +2429 0 +2430 0 +2431 0 +2432 0 +2433 0 +2434 0 +2435 0 +2436 0 +2437 0 +2438 0 +2439 0 +2440 1 +2441 0 +2442 0 +2443 0 +2444 0 +2445 0 +2446 0 +2447 0 +2448 0 +2449 0 +2450 0 +2451 1 +2452 0 +2453 0 +2454 0 +2455 0 +2456 0 +2457 0 +2458 0 +2459 0 +2460 0 +2461 1 +2462 0 +2463 0 +2464 0 +2465 0 +2466 0 +2467 0 +2468 0 +2469 1 +2470 0 +2471 0 +2472 0 +2473 0 +2474 0 +2475 0 +2476 0 +2477 1 +2478 0 +2479 0 +2480 0 +2481 0 +2482 0 +2483 0 +2484 0 +2485 0 +2486 1 +2487 0 +2488 0 +2489 0 +2490 0 +2491 0 +2492 0 +2493 0 +2494 0 +2495 0 +2496 1 +2497 0 +2498 0 +2499 0 +2500 0 +2501 0 +2502 0 +2503 0 +2504 0 +2505 0 +2506 1 +2507 0 +2508 0 +2509 0 +2510 0 +2511 0 +2512 0 +2513 0 +2514 0 +2515 0 +2516 1 +2517 0 +2518 0 +2519 0 +2520 0 +2521 0 +2522 0 +2523 0 +2524 0 +2525 0 +2526 0 +2527 1 +2528 0 +2529 0 +2530 0 +2531 0 +2532 0 +2533 0 +2534 0 +2535 0 +2536 0 +2537 1 +2538 0 +2539 0 +2540 0 +2541 0 +2542 0 +2543 0 +2544 0 +2545 0 +2546 0 +2547 0 +2548 0 +2549 0 +2550 0 +2551 0 +2552 0 +2553 0 +2554 0 +2555 0 +2556 0 +2557 1 +2558 0 +2559 0 +2560 0 +2561 0 +2562 0 +2563 0 +2564 0 +2565 0 +2566 1 +2567 0 +2568 0 +2569 0 +2570 0 +2571 0 +2572 0 +2573 0 +2574 0 +2575 1 +2576 0 +2577 0 +2578 0 +2579 0 +2580 0 +2581 0 +2582 0 +2583 0 +2584 1 +2585 0 +2586 0 +2587 0 +2588 0 +2589 0 +2590 0 +2591 0 +2592 0 +2593 0 +2594 0 +2595 1 +2596 0 +2597 0 +2598 0 +2599 0 +2600 0 +2601 0 +2602 0 +2603 0 +2604 0 +2605 1 +2606 0 +2607 0 +2608 0 +2609 0 +2610 0 +2611 0 +2612 0 +2613 0 +2614 0 +2615 0 +2616 0 +2617 0 +2618 0 +2619 0 +2620 0 +2621 0 +2622 0 +2623 0 +2624 0 +2625 1 +2626 0 +2627 0 +2628 0 +2629 0 +2630 0 +2631 0 +2632 0 +2633 0 +2634 0 +2635 1 +2636 0 +2637 0 +2638 0 +2639 1 +2640 0 +2641 0 +2642 0 +2643 1 +2644 0 +2645 0 +2646 0 +2647 0 +2648 0 +2649 0 +2650 0 +2651 0 +2652 0 +2653 1 +2654 0 +2655 0 +2656 0 +2657 0 +2658 0 +2659 0 +2660 0 +2661 0 +2662 0 +2663 1 +2664 0 +2665 0 +2666 0 +2667 0 +2668 0 +2669 0 +2670 0 +2671 1 +2672 0 +2673 0 +2674 0 +2675 0 +2676 0 +2677 0 +2678 0 +2679 1 +2680 0 +2681 0 +2682 0 +2683 0 +2684 0 +2685 0 +2686 0 +2687 0 +2688 0 +2689 1 +2690 0 +2691 0 +2692 0 +2693 0 +2694 0 +2695 0 +2696 0 +2697 0 +2698 0 +2699 1 +2700 0 +2701 0 +2702 0 +2703 0 +2704 0 +2705 0 +2706 0 +2707 0 +2708 0 +2709 1 +2710 0 +2711 0 +2712 0 +2713 0 +2714 0 +2715 0 +2716 1 +2717 0 +2718 0 +2719 0 +2720 0 +2721 0 +2722 0 +2723 0 +2724 1 +2725 0 +2726 0 +2727 0 +2728 0 +2729 0 +2730 0 +2731 0 +2732 0 +2733 0 +2734 1 +2735 0 +2736 0 +2737 0 +2738 0 +2739 0 +2740 0 +2741 0 +2742 0 +2743 0 +2744 1 +2745 0 +2746 0 +2747 0 +2748 0 +2749 0 +2750 0 +2751 0 +2752 0 +2753 1 +2754 0 +2755 0 +2756 0 +2757 0 +2758 0 +2759 0 +2760 0 +2761 0 +2762 0 +2763 1 +2764 0 +2765 0 +2766 0 +2767 0 +2768 0 +2769 0 +2770 0 +2771 0 +2772 0 +2773 1 +2774 0 +2775 0 +2776 0 +2777 0 +2778 0 +2779 0 +2780 0 +2781 0 +2782 0 +2783 1 +2784 0 +2785 0 +2786 0 +2787 0 +2788 0 +2789 0 +2790 0 +2791 0 +2792 1 +2793 0 +2794 0 +2795 0 +2796 0 +2797 0 +2798 0 +2799 0 +2800 0 +2801 0 +2802 0 +2803 0 +2804 0 +2805 0 +2806 0 +2807 0 +2808 0 +2809 0 +2810 0 +2811 0 +2812 0 +2813 0 +2814 0 +2815 0 +2816 0 +2817 0 +2818 0 +2819 0 +2820 0 +2821 1 +2822 0 +2823 0 +2824 0 +2825 0 +2826 0 +2827 0 +2828 0 +2829 0 +2830 0 +2831 1 +2832 0 +2833 0 +2834 0 +2835 0 +2836 0 +2837 0 +2838 0 +2839 0 +2840 0 +2841 1 +2842 0 +2843 0 +2844 0 +2845 0 +2846 0 +2847 0 +2848 0 +2849 0 +2850 0 +2851 1 +2852 0 +2853 0 +2854 0 +2855 0 +2856 0 +2857 0 +2858 0 +2859 0 +2860 0 +2861 1 +2862 0 +2863 0 +2864 0 +2865 0 +2866 0 +2867 0 +2868 0 +2869 0 +2870 0 +2871 1 +2872 0 +2873 0 +2874 0 +2875 0 +2876 0 +2877 0 +2878 0 +2879 0 +2880 1 +2881 0 +2882 0 +2883 0 +2884 0 +2885 0 +2886 0 +2887 0 +2888 1 +2889 0 +2890 0 +2891 0 +2892 0 +2893 0 +2894 0 +2895 0 +2896 0 +2897 1 +2898 0 +2899 0 +2900 0 +2901 0 +2902 0 +2903 0 +2904 0 +2905 0 +2906 1 +2907 0 +2908 0 +2909 0 +2910 0 +2911 0 +2912 0 +2913 0 +2914 1 +2915 0 +2916 0 +2917 0 +2918 0 +2919 0 +2920 0 +2921 0 +2922 1 +2923 0 +2924 0 +2925 0 +2926 0 +2927 0 +2928 0 +2929 0 +2930 0 +2931 0 +2932 0 +2933 0 +2934 0 +2935 0 +2936 0 +2937 0 +2938 1 +2939 0 +2940 0 +2941 0 +2942 0 +2943 0 +2944 0 +2945 0 +2946 0 +2947 0 +2948 0 +2949 1 +2950 0 +2951 0 +2952 0 +2953 0 +2954 0 +2955 0 +2956 0 +2957 0 +2958 0 +2959 1 +2960 0 +2961 0 +2962 0 +2963 0 +2964 0 +2965 0 +2966 0 +2967 0 +2968 1 +2969 0 +2970 0 +2971 0 +2972 0 +2973 0 +2974 0 +2975 0 +2976 0 +2977 1 +2978 0 +2979 0 +2980 0 +2981 0 +2982 0 +2983 0 +2984 0 +2985 0 +2986 0 +2987 1 +2988 0 +2989 0 +2990 0 +2991 0 +2992 0 +2993 0 +2994 0 +2995 0 +2996 0 +2997 1 +2998 0 +2999 0 +3000 0 +3001 0 +3002 0 +3003 0 +3004 0 +3005 0 +3006 0 +3007 0 +3008 0 +3009 0 +3010 0 +3011 0 +3012 0 +3013 0 +3014 0 +3015 1 +3016 0 +3017 0 +3018 0 +3019 0 +3020 0 +3021 0 +3022 0 +3023 0 +3024 0 +3025 1 +3026 0 +3027 0 +3028 0 +3029 0 +3030 0 +3031 0 +3032 0 +3033 0 +3034 1 +3035 0 +3036 0 +3037 0 +3038 0 +3039 0 +3040 0 +3041 0 +3042 1 +3043 0 +3044 0 +3045 0 +3046 0 +3047 0 +3048 0 +3049 0 +3050 0 +3051 0 +3052 1 +3053 0 +3054 0 +3055 0 +3056 0 +3057 0 +3058 0 +3059 0 +3060 0 +3061 0 +3062 1 +3063 0 +3064 0 +3065 0 +3066 0 +3067 0 +3068 0 +3069 0 +3070 0 +3071 0 +3072 1 +3073 0 +3074 0 +3075 0 +3076 0 +3077 0 +3078 0 +3079 0 +3080 0 +3081 0 +3082 1 +3083 0 +3084 0 +3085 0 +3086 0 +3087 0 +3088 0 +3089 0 +3090 0 +3091 0 +3092 1 +3093 0 +3094 0 +3095 0 +3096 0 +3097 0 +3098 0 +3099 0 +3100 0 +3101 0 +3102 1 +3103 0 +3104 0 +3105 0 +3106 0 +3107 0 +3108 0 +3109 0 +3110 0 +3111 0 +3112 1 +3113 0 +3114 0 +3115 0 +3116 0 +3117 0 +3118 0 +3119 0 +3120 1 +3121 0 +3122 0 +3123 0 +3124 0 +3125 0 +3126 0 +3127 0 +3128 0 +3129 1 +3130 0 +3131 0 +3132 0 +3133 0 +3134 0 +3135 0 +3136 0 +3137 0 +3138 0 +3139 1 +3140 0 +3141 0 +3142 0 +3143 0 +3144 0 +3145 0 +3146 0 +3147 0 +3148 0 +3149 1 +3150 0 +3151 0 +3152 0 +3153 0 +3154 0 +3155 0 +3156 0 +3157 1 +3158 0 +3159 0 +3160 0 +3161 0 +3162 0 +3163 0 +3164 0 +3165 1 +3166 0 +3167 0 +3168 0 +3169 0 +3170 0 +3171 0 +3172 0 +3173 0 +3174 0 +3175 1 +3176 0 +3177 0 +3178 0 +3179 0 +3180 0 +3181 0 +3182 0 +3183 0 +3184 0 +3185 1 +3186 0 +3187 0 +3188 0 +3189 0 +3190 0 +3191 0 +3192 0 +3193 0 +3194 0 +3195 0 +3196 1 +3197 0 +3198 0 +3199 0 +3200 0 +3201 0 +3202 0 +3203 0 +3204 0 +3205 0 +3206 0 +3207 1 +3208 0 +3209 0 +3210 0 +3211 0 +3212 0 +3213 0 +3214 0 +3215 1 +3216 0 +3217 0 +3218 0 +3219 0 +3220 0 +3221 0 +3222 0 +3223 1 +3224 0 +3225 0 +3226 0 +3227 0 +3228 0 +3229 0 +3230 0 +3231 0 +3232 1 +3233 0 +3234 1 +3235 0 +3236 0 +3237 0 +3238 0 +3239 1 +3240 0 +3241 0 +3242 0 +3243 0 +3244 0 +3245 0 +3246 0 +3247 0 +3248 1 +3249 0 +3250 0 +3251 0 +3252 0 +3253 0 +3254 0 +3255 0 +3256 0 +3257 0 +3258 1 +3259 0 +3260 0 +3261 0 +3262 0 +3263 0 +3264 0 +3265 0 +3266 0 +3267 0 +3268 0 +3269 1 +3270 0 +3271 0 +3272 0 +3273 0 +3274 0 +3275 0 +3276 0 +3277 0 +3278 1 +3279 0 +3280 0 +3281 0 +3282 0 +3283 0 +3284 0 +3285 0 +3286 0 +3287 1 +3288 0 +3289 0 +3290 0 +3291 0 +3292 0 +3293 0 +3294 0 +3295 0 +3296 0 +3297 1 +3298 0 +3299 0 +3300 0 +3301 0 +3302 0 +3303 0 +3304 0 +3305 0 +3306 0 +3307 1 +3308 0 +3309 0 +3310 0 +3311 0 +3312 0 +3313 0 +3314 0 +3315 0 +3316 0 +3317 1 +3318 0 +3319 0 +3320 0 +3321 0 +3322 0 +3323 0 +3324 0 +3325 1 +3326 0 +3327 0 +3328 0 +3329 0 +3330 0 +3331 0 +3332 0 +3333 0 +3334 0 +3335 1 +3336 0 +3337 0 +3338 0 +3339 0 +3340 0 +3341 0 +3342 0 +3343 0 +3344 1 +3345 0 +3346 0 +3347 0 +3348 0 +3349 0 +3350 0 +3351 0 +3352 0 +3353 0 +3354 1 +3355 0 +3356 0 +3357 0 +3358 0 +3359 0 +3360 0 +3361 0 +3362 0 +3363 0 +3364 0 +3365 1 +3366 0 +3367 0 +3368 0 +3369 0 +3370 0 +3371 0 +3372 0 +3373 0 +3374 0 +3375 1 +3376 0 +3377 0 +3378 0 +3379 0 +3380 0 +3381 0 +3382 0 +3383 0 +3384 0 +3385 0 +3386 1 +3387 0 +3388 0 +3389 0 +3390 0 +3391 0 +3392 0 +3393 0 +3394 0 +3395 0 +3396 0 +3397 1 +3398 0 +3399 0 +3400 0 +3401 0 +3402 0 +3403 0 +3404 0 +3405 0 +3406 0 +3407 1 +3408 0 +3409 0 +3410 0 +3411 0 +3412 0 +3413 0 +3414 0 +3415 0 +3416 0 +3417 1 +3418 0 +3419 0 +3420 0 +3421 0 +3422 0 +3423 0 +3424 0 +3425 0 +3426 0 +3427 0 +3428 1 +3429 0 +3430 0 +3431 0 +3432 0 +3433 0 +3434 0 +3435 0 +3436 0 +3437 1 +3438 0 +3439 0 +3440 0 +3441 0 +3442 0 +3443 0 +3444 0 +3445 1 +3446 0 +3447 0 +3448 0 +3449 0 +3450 0 +3451 0 +3452 0 +3453 0 +3454 1 +3455 0 +3456 0 +3457 0 +3458 0 +3459 0 +3460 0 +3461 0 +3462 0 +3463 0 +3464 1 +3465 0 +3466 0 +3467 0 +3468 0 +3469 0 +3470 0 +3471 0 +3472 0 +3473 0 +3474 1 +3475 0 +3476 0 +3477 0 +3478 0 +3479 0 +3480 0 +3481 0 +3482 0 +3483 0 +3484 1 +3485 0 +3486 0 +3487 0 +3488 0 +3489 0 +3490 0 +3491 0 +3492 0 +3493 0 +3494 1 +3495 0 +3496 0 +3497 0 +3498 0 +3499 0 +3500 0 +3501 0 +3502 0 +3503 0 +3504 1 +3505 0 +3506 0 +3507 0 +3508 0 +3509 0 +3510 0 +3511 0 +3512 0 +3513 0 +3514 1 +3515 0 +3516 0 +3517 0 +3518 0 +3519 0 +3520 0 +3521 0 +3522 0 +3523 0 +3524 1 +3525 0 +3526 0 +3527 0 +3528 0 +3529 0 +3530 0 +3531 0 +3532 0 +3533 1 +3534 0 +3535 0 +3536 0 +3537 0 +3538 0 +3539 0 +3540 0 +3541 0 +3542 0 +3543 0 +3544 0 +3545 0 +3546 0 +3547 0 +3548 0 +3549 0 +3550 0 +3551 1 +3552 0 +3553 0 +3554 0 +3555 0 +3556 0 +3557 0 +3558 0 +3559 0 +3560 0 +3561 1 +3562 0 +3563 0 +3564 0 +3565 0 +3566 0 +3567 0 +3568 0 +3569 0 +3570 1 +3571 0 +3572 0 +3573 0 +3574 0 +3575 0 +3576 0 +3577 0 +3578 0 +3579 0 +3580 1 +3581 0 +3582 0 +3583 0 +3584 0 +3585 0 +3586 0 +3587 0 +3588 0 +3589 0 +3590 1 +3591 0 +3592 0 +3593 0 +3594 0 +3595 0 +3596 0 +3597 0 +3598 0 +3599 1 +3600 0 +3601 0 +3602 0 +3603 0 +3604 0 +3605 0 +3606 0 +3607 0 +3608 0 +3609 1 +3610 0 +3611 0 +3612 0 +3613 0 +3614 0 +3615 0 +3616 0 +3617 0 +3618 0 +3619 0 +3620 1 +3621 0 +3622 0 +3623 0 +3624 0 +3625 0 +3626 0 +3627 0 +3628 0 +3629 0 +3630 1 +3631 0 +3632 0 +3633 0 +3634 0 +3635 0 +3636 0 +3637 0 +3638 0 +3639 1 +3640 0 +3641 0 +3642 0 +3643 0 +3644 0 +3645 1 +3646 0 +3647 0 +3648 0 +3649 0 +3650 0 +3651 1 +3652 0 +3653 0 +3654 0 +3655 0 +3656 0 +3657 0 +3658 1 +3659 0 +3660 0 +3661 0 +3662 0 +3663 0 +3664 0 +3665 0 +3666 1 +3667 0 +3668 0 +3669 0 +3670 0 +3671 0 +3672 0 +3673 0 +3674 0 +3675 0 +3676 1 +3677 0 +3678 0 +3679 0 +3680 0 +3681 0 +3682 0 +3683 0 +3684 0 +3685 1 +3686 0 +3687 0 +3688 0 +3689 0 +3690 0 +3691 0 +3692 0 +3693 0 +3694 0 +3695 1 +3696 0 +3697 0 +3698 0 +3699 0 +3700 0 +3701 0 +3702 0 +3703 0 +3704 0 +3705 0 +3706 1 +3707 0 +3708 0 +3709 0 +3710 0 +3711 0 +3712 0 +3713 0 +3714 0 +3715 0 +3716 1 +3717 0 +3718 0 +3719 0 +3720 0 +3721 0 +3722 0 +3723 0 +3724 0 +3725 0 +3726 0 +3727 0 +3728 0 +3729 0 +3730 0 +3731 0 +3732 0 +3733 0 +3734 0 +3735 0 +3736 1 +3737 0 +3738 0 +3739 0 +3740 0 +3741 0 +3742 0 +3743 0 +3744 0 +3745 0 +3746 1 +3747 0 +3748 0 +3749 0 +3750 0 +3751 0 +3752 0 +3753 0 +3754 0 +3755 0 +3756 1 +3757 0 +3758 0 +3759 0 +3760 0 +3761 0 +3762 0 +3763 1 +3764 0 +3765 0 +3766 0 +3767 0 +3768 0 +3769 0 +3770 0 +3771 1 +3772 0 +3773 0 +3774 0 +3775 0 +3776 0 +3777 0 +3778 1 +3779 0 +3780 0 +3781 0 +3782 0 +3783 0 +3784 0 +3785 0 +3786 0 +3787 0 +3788 0 +3789 0 +3790 0 +3791 0 +3792 0 +3793 0 +3794 0 +3795 0 +3796 0 +3797 1 +3798 0 +3799 0 +3800 0 +3801 0 +3802 0 +3803 0 +3804 0 +3805 0 +3806 1 +3807 0 +3808 0 +3809 0 +3810 0 +3811 0 +3812 0 +3813 0 +3814 0 +3815 0 +3816 0 +3817 1 +3818 0 +3819 0 +3820 0 +3821 0 +3822 0 +3823 0 +3824 0 +3825 0 +3826 0 +3827 1 +3828 0 +3829 1 +3830 0 +3831 0 +3832 0 +3833 0 +3834 1 +3835 0 +3836 0 +3837 0 +3838 0 +3839 0 +3840 0 +3841 0 +3842 0 +3843 0 +3844 0 +3845 1 +3846 0 +3847 0 +3848 0 +3849 0 +3850 0 +3851 0 +3852 0 +3853 0 +3854 0 +3855 1 +3856 0 +3857 0 +3858 0 +3859 0 +3860 0 +3861 0 +3862 0 +3863 1 +3864 0 +3865 0 +3866 0 +3867 0 +3868 0 +3869 0 +3870 0 +3871 0 +3872 0 +3873 1 +3874 0 +3875 0 +3876 0 +3877 0 +3878 0 +3879 0 +3880 0 +3881 0 +3882 0 +3883 1 +3884 0 +3885 0 +3886 0 +3887 0 +3888 0 +3889 0 +3890 0 +3891 0 +3892 0 +3893 0 +3894 1 +3895 0 +3896 0 +3897 0 +3898 0 +3899 0 +3900 0 +3901 0 +3902 0 +3903 0 +3904 0 +3905 1 +3906 0 +3907 0 +3908 0 +3909 0 +3910 0 +3911 0 +3912 0 +3913 0 +3914 1 +3915 0 +3916 0 +3917 0 +3918 0 +3919 0 +3920 0 +3921 0 +3922 0 +3923 0 +3924 0 +3925 1 +3926 0 +3927 0 +3928 0 +3929 0 +3930 0 +3931 0 +3932 0 +3933 0 +3934 1 +3935 0 +3936 0 +3937 0 +3938 0 +3939 0 +3940 0 +3941 0 +3942 0 +3943 0 +3944 0 +3945 1 +3946 0 +3947 0 +3948 0 +3949 0 +3950 0 +3951 0 +3952 0 +3953 0 +3954 0 +3955 1 +3956 0 +3957 0 +3958 0 +3959 0 +3960 0 +3961 0 +3962 0 +3963 0 +3964 0 +3965 0 +3966 1 +3967 0 +3968 0 +3969 0 +3970 0 +3971 0 +3972 0 +3973 0 +3974 0 +3975 1 +3976 0 +3977 0 +3978 0 +3979 0 +3980 0 +3981 0 +3982 0 +3983 0 +3984 1 +3985 0 +3986 0 +3987 0 +3988 0 +3989 0 +3990 0 +3991 0 +3992 0 +3993 0 +3994 1 +3995 0 +3996 0 +3997 0 +3998 0 +3999 0 +4000 0 +4001 0 +4002 0 +4003 0 +4004 0 +4005 0 +4006 0 +4007 0 +4008 0 +4009 0 +4010 0 +4011 0 +4012 0 +4013 0 +4014 1 +4015 0 +4016 0 +4017 0 +4018 0 +4019 0 +4020 0 +4021 0 +4022 0 +4023 0 +4024 1 +4025 0 +4026 0 +4027 0 +4028 0 +4029 0 +4030 0 +4031 0 +4032 0 +4033 0 +4034 0 +4035 1 +4036 0 +4037 0 +4038 0 +4039 0 +4040 0 +4041 0 +4042 0 +4043 0 +4044 0 +4045 1 +4046 0 +4047 0 +4048 0 +4049 0 +4050 0 +4051 0 +4052 0 +4053 0 +4054 0 +4055 0 +4056 1 +4057 0 +4058 0 +4059 0 +4060 0 +4061 0 +4062 0 +4063 0 +4064 0 +4065 0 +4066 1 +4067 0 +4068 0 +4069 0 +4070 0 +4071 0 +4072 0 +4073 0 +4074 1 +4075 0 +4076 0 +4077 0 +4078 0 +4079 0 +4080 0 +4081 0 +4082 0 +4083 0 +4084 1 +4085 0 +4086 0 +4087 0 +4088 0 +4089 0 +4090 0 +4091 0 +4092 0 +4093 1 +4094 0 +4095 0 +4096 0 +4097 0 +4098 0 +4099 0 +4100 0 +4101 0 +4102 1 +4103 0 +4104 0 +4105 0 +4106 0 +4107 0 +4108 0 +4109 0 +4110 0 +4111 0 +4112 1 +4113 0 +4114 0 +4115 0 +4116 0 +4117 0 +4118 0 +4119 0 +4120 0 +4121 0 +4122 1 +4123 0 +4124 0 +4125 0 +4126 0 +4127 0 +4128 0 +4129 0 +4130 0 +4131 0 +4132 0 +4133 1 +4134 0 +4135 0 +4136 0 +4137 0 +4138 0 +4139 0 +4140 0 +4141 0 +4142 0 +4143 0 +4144 1 +4145 0 +4146 0 +4147 0 +4148 0 +4149 0 +4150 0 +4151 0 +4152 0 +4153 0 +4154 1 +4155 0 +4156 0 +4157 0 +4158 0 +4159 0 +4160 0 +4161 0 +4162 0 +4163 0 +4164 0 +4165 1 +4166 0 +4167 0 +4168 0 +4169 0 +4170 0 +4171 0 +4172 0 +4173 0 +4174 0 +4175 0 +4176 1 +4177 0 +4178 0 +4179 0 +4180 0 +4181 0 +4182 0 +4183 0 +4184 0 +4185 1 +4186 0 +4187 0 +4188 0 +4189 0 +4190 0 +4191 0 +4192 0 +4193 0 +4194 0 +4195 1 +4196 0 +4197 0 +4198 0 +4199 0 +4200 0 +4201 0 +4202 0 +4203 0 +4204 0 +4205 0 +4206 0 +4207 0 +4208 0 +4209 0 +4210 0 +4211 0 +4212 1 +4213 0 +4214 0 +4215 0 +4216 0 +4217 0 +4218 0 +4219 0 +4220 0 +4221 1 +4222 0 +4223 0 +4224 0 +4225 0 +4226 0 +4227 0 +4228 0 +4229 0 +4230 1 +4231 0 +4232 0 +4233 0 +4234 0 +4235 0 +4236 0 +4237 0 +4238 0 +4239 1 +4240 0 +4241 0 +4242 0 +4243 0 +4244 0 +4245 0 +4246 0 +4247 0 +4248 0 +4249 1 +4250 0 +4251 0 +4252 0 +4253 0 +4254 0 +4255 0 +4256 0 +4257 0 +4258 1 +4259 0 +4260 0 +4261 0 +4262 0 +4263 0 +4264 0 +4265 0 +4266 0 +4267 0 +4268 1 +4269 0 +4270 0 +4271 0 +4272 0 +4273 0 +4274 0 +4275 0 +4276 0 +4277 0 +4278 1 +4279 0 +4280 0 +4281 0 +4282 0 +4283 0 +4284 0 +4285 0 +4286 0 +4287 0 +4288 0 +4289 1 +4290 0 +4291 0 +4292 0 +4293 0 +4294 0 +4295 0 +4296 0 +4297 0 +4298 0 +4299 1 +4300 0 +4301 0 +4302 0 +4303 0 +4304 0 +4305 0 +4306 0 +4307 0 +4308 0 +4309 1 +4310 0 +4311 0 +4312 0 +4313 0 +4314 0 +4315 0 +4316 0 +4317 0 +4318 1 +4319 0 +4320 0 +4321 0 +4322 0 +4323 0 +4324 0 +4325 0 +4326 0 +4327 1 +4328 0 +4329 0 +4330 0 +4331 0 +4332 0 +4333 0 +4334 0 +4335 0 +4336 0 +4337 1 +4338 0 +4339 0 +4340 0 +4341 0 +4342 0 +4343 0 +4344 0 +4345 0 +4346 0 +4347 1 +4348 0 +4349 0 +4350 0 +4351 0 +4352 0 +4353 0 +4354 0 +4355 1 +4356 0 +4357 0 +4358 0 +4359 0 +4360 0 +4361 0 +4362 0 +4363 0 +4364 0 +4365 0 +4366 0 +4367 0 +4368 0 +4369 0 +4370 0 +4371 0 +4372 0 +4373 0 +4374 1 +4375 0 +4376 0 +4377 0 +4378 0 +4379 0 +4380 0 +4381 0 +4382 0 +4383 0 +4384 1 +4385 0 +4386 0 +4387 0 +4388 0 +4389 0 +4390 0 +4391 0 +4392 0 +4393 1 +4394 0 +4395 0 +4396 0 +4397 0 +4398 0 +4399 0 +4400 0 +4401 0 +4402 0 +4403 1 +4404 0 +4405 0 +4406 0 +4407 0 +4408 0 +4409 0 +4410 0 +4411 0 +4412 1 +4413 0 +4414 0 +4415 0 +4416 0 +4417 0 +4418 0 +4419 0 +4420 0 +4421 0 +4422 0 +4423 1 +4424 0 +4425 0 +4426 0 +4427 0 +4428 0 +4429 0 +4430 2 +4431 0 +4432 0 +4433 0 +4434 0 +4435 0 +4436 0 +4437 1 +4438 0 +4439 0 +4440 0 +4441 0 +4442 0 +4443 0 +4444 0 +4445 1 +4446 0 +4447 0 +4448 0 +4449 0 +4450 0 +4451 0 +4452 0 +4453 0 +4454 1 +4455 0 +4456 0 +4457 0 +4458 0 +4459 0 +4460 0 +4461 0 +4462 1 +4463 0 +4464 0 +4465 0 +4466 0 +4467 0 +4468 0 +4469 0 +4470 0 +4471 1 +4472 0 +4473 0 +4474 0 +4475 0 +4476 0 +4477 0 +4478 0 +4479 0 +4480 1 +4481 0 +4482 0 +4483 0 +4484 0 +4485 0 +4486 0 +4487 0 +4488 1 +4489 0 +4490 0 +4491 0 +4492 0 +4493 0 +4494 0 +4495 0 +4496 0 +4497 1 +4498 0 +4499 0 +4500 0 +4501 0 +4502 0 +4503 0 +4504 0 +4505 1 +4506 0 +4507 0 +4508 0 +4509 0 +4510 0 +4511 0 +4512 0 +4513 1 +4514 0 +4515 0 +4516 0 +4517 0 +4518 0 +4519 0 +4520 1 +4521 0 +4522 0 +4523 0 +4524 0 +4525 0 +4526 0 +4527 0 +4528 0 +4529 1 +4530 0 +4531 0 +4532 0 +4533 0 +4534 0 +4535 0 +4536 0 +4537 0 +4538 1 +4539 0 +4540 0 +4541 0 +4542 0 +4543 0 +4544 0 +4545 0 +4546 1 +4547 0 +4548 0 +4549 0 +4550 0 +4551 0 +4552 1 +4553 0 +4554 0 +4555 0 +4556 0 +4557 0 +4558 0 +4559 1 +4560 0 +4561 0 +4562 0 +4563 0 +4564 0 +4565 0 +4566 0 +4567 1 +4568 0 +4569 0 +4570 0 +4571 0 +4572 0 +4573 0 +4574 0 +4575 1 +4576 0 +4577 0 +4578 0 +4579 0 +4580 0 +4581 0 +4582 0 +4583 1 +4584 0 +4585 0 +4586 0 +4587 0 +4588 0 +4589 0 +4590 0 +4591 1 +4592 0 +4593 0 +4594 0 +4595 0 +4596 0 +4597 0 +4598 0 +4599 0 +4600 1 +4601 0 +4602 0 +4603 0 +4604 0 +4605 0 +4606 0 +4607 1 +4608 0 +4609 0 +4610 0 +4611 0 +4612 0 +4613 0 +4614 0 +4615 0 +4616 1 +4617 0 +4618 0 +4619 0 +4620 0 +4621 0 +4622 0 +4623 0 +4624 0 +4625 1 +4626 0 +4627 0 +4628 0 +4629 0 +4630 0 +4631 0 +4632 0 +4633 0 +4634 1 +4635 0 +4636 0 +4637 0 +4638 0 +4639 0 +4640 0 +4641 0 +4642 0 +4643 0 +4644 0 +4645 0 +4646 0 +4647 0 +4648 0 +4649 0 +4650 0 +4651 0 +4652 1 +4653 0 +4654 0 +4655 0 +4656 0 +4657 0 +4658 0 +4659 0 +4660 0 +4661 1 +4662 0 +4663 0 +4664 0 +4665 1 +4666 0 +4667 0 +4668 0 +4669 0 +4670 0 +4671 0 +4672 1 +4673 0 +4674 0 +4675 0 +4676 0 +4677 0 +4678 1 +4679 0 +4680 0 +4681 0 +4682 0 +4683 0 +4684 0 +4685 0 +4686 1 +4687 0 +4688 0 +4689 0 +4690 0 +4691 0 +4692 0 +4693 0 +4694 1 +4695 0 +4696 0 +4697 0 +4698 0 +4699 0 +4700 0 +4701 0 +4702 1 +4703 0 +4704 0 +4705 0 +4706 0 +4707 0 +4708 0 +4709 1 +4710 0 +4711 0 +4712 0 +4713 0 +4714 0 +4715 0 +4716 0 +4717 1 +4718 0 +4719 0 +4720 0 +4721 0 +4722 0 +4723 0 +4724 0 +4725 1 +4726 0 +4727 0 +4728 0 +4729 0 +4730 0 +4731 0 +4732 0 +4733 0 +4734 1 +4735 0 +4736 0 +4737 0 +4738 0 +4739 0 +4740 0 +4741 0 +4742 0 +4743 0 +4744 1 +4745 0 +4746 0 +4747 0 +4748 0 +4749 0 +4750 0 +4751 0 +4752 1 +4753 0 +4754 0 +4755 0 +4756 0 +4757 0 +4758 0 +4759 0 +4760 1 +4761 0 +4762 0 +4763 0 +4764 0 +4765 0 +4766 0 +4767 0 +4768 0 +4769 1 +4770 0 +4771 0 +4772 0 +4773 0 +4774 0 +4775 0 +4776 0 +4777 0 +4778 1 +4779 0 +4780 0 +4781 0 +4782 0 +4783 0 +4784 0 +4785 0 +4786 1 +4787 0 +4788 0 +4789 0 +4790 0 +4791 0 +4792 0 +4793 0 +4794 0 +4795 0 +4796 1 +4797 0 +4798 0 +4799 0 +4800 0 +4801 0 +4802 0 +4803 0 +4804 1 +4805 0 +4806 0 +4807 0 +4808 0 +4809 0 +4810 0 +4811 0 +4812 0 +4813 1 +4814 0 +4815 0 +4816 0 +4817 0 +4818 0 +4819 0 +4820 0 +4821 0 +4822 1 +4823 0 +4824 0 +4825 0 +4826 0 +4827 0 +4828 0 +4829 0 +4830 0 +4831 1 +4832 0 +4833 0 +4834 0 +4835 0 +4836 0 +4837 0 +4838 0 +4839 0 +4840 0 +4841 0 +4842 0 +4843 0 +4844 0 +4845 0 +4846 0 +4847 0 +4848 0 +4849 0 +4850 0 +4851 0 +4852 0 +4853 0 +4854 0 +4855 0 +4856 0 +4857 0 +4858 0 +4859 0 +4860 0 +4861 0 +4862 0 +4863 0 +4864 0 +4865 1 +4866 0 +4867 0 +4868 0 +4869 0 +4870 0 +4871 0 +4872 1 +4873 0 +4874 0 +4875 0 +4876 0 +4877 0 +4878 0 +4879 0 +4880 1 +4881 0 +4882 0 +4883 0 +4884 0 +4885 0 +4886 0 +4887 0 +4888 0 +4889 0 +4890 1 +4891 0 +4892 0 +4893 0 +4894 0 +4895 0 +4896 0 +4897 0 +4898 1 +4899 0 +4900 0 +4901 0 +4902 0 +4903 0 +4904 0 +4905 1 +4906 0 +4907 0 +4908 0 +4909 0 +4910 0 +4911 0 +4912 0 +4913 1 +4914 0 +4915 0 +4916 0 +4917 0 +4918 0 +4919 0 +4920 0 +4921 0 +4922 0 +4923 1 +4924 0 +4925 0 +4926 0 +4927 0 +4928 0 +4929 0 +4930 0 +4931 0 +4932 0 +4933 1 +4934 0 +4935 0 +4936 0 +4937 0 +4938 0 +4939 0 +4940 0 +4941 0 +4942 0 +4943 0 +4944 0 +4945 0 +4946 0 +4947 0 +4948 1 +4949 0 +4950 0 +4951 0 +4952 0 +4953 0 +4954 0 +4955 0 +4956 1 +4957 0 +4958 0 +4959 0 +4960 0 +4961 0 +4962 0 +4963 0 +4964 1 +4965 0 +4966 0 +4967 0 +4968 0 +4969 0 +4970 0 +4971 0 +4972 1 +4973 0 +4974 0 +4975 0 +4976 0 +4977 0 +4978 0 +4979 1 +4980 0 +4981 0 +4982 0 +4983 0 +4984 0 +4985 0 +4986 0 +4987 1 +4988 0 +4989 0 +4990 0 +4991 0 +4992 0 +4993 0 +4994 1 +4995 0 +4996 0 +4997 0 +4998 0 +4999 0 +5000 0 +5001 0 +5002 0 +5003 1 +5004 0 +5005 0 +5006 0 +5007 0 +5008 0 +5009 0 +5010 0 +5011 0 +5012 1 +5013 0 +5014 0 +5015 0 +5016 0 +5017 0 +5018 0 +5019 0 +5020 1 +5021 0 +5022 0 +5023 0 +5024 0 +5025 0 +5026 0 +5027 0 +5028 0 +5029 1 +5030 0 +5031 0 +5032 0 +5033 0 +5034 0 +5035 0 +5036 0 +5037 1 +5038 0 +5039 0 +5040 0 +5041 0 +5042 0 +5043 0 +5044 0 +5045 1 +5046 0 +5047 0 +5048 0 +5049 0 +5050 0 +5051 0 +5052 0 +5053 1 +5054 0 +5055 0 +5056 0 +5057 0 +5058 0 +5059 0 +5060 0 +5061 0 +5062 1 +5063 0 +5064 0 +5065 0 +5066 0 +5067 0 +5068 0 +5069 0 +5070 0 +5071 0 +5072 0 +5073 0 +5074 0 +5075 0 +5076 0 +5077 0 +5078 0 +5079 1 +5080 0 +5081 0 +5082 0 +5083 0 +5084 0 +5085 0 +5086 1 +5087 0 +5088 0 +5089 0 +5090 0 +5091 0 +5092 0 +5093 0 +5094 1 +5095 0 +5096 0 +5097 0 +5098 0 +5099 0 +5100 0 +5101 0 +5102 0 +5103 1 +5104 0 +5105 0 +5106 0 +5107 0 +5108 0 +5109 0 +5110 1 +5111 0 +5112 0 +5113 0 +5114 0 +5115 0 +5116 0 +5117 0 +5118 1 +5119 0 +5120 0 +5121 0 +5122 0 +5123 0 +5124 0 +5125 0 +5126 0 +5127 1 +5128 0 +5129 0 +5130 0 +5131 0 +5132 0 +5133 0 +5134 1 +5135 0 +5136 0 +5137 0 +5138 0 +5139 0 +5140 0 +5141 1 +5142 0 +5143 0 +5144 0 +5145 0 +5146 0 +5147 0 +5148 0 +5149 1 +5150 0 +5151 0 +5152 0 +5153 0 +5154 0 +5155 0 +5156 0 +5157 0 +5158 1 +5159 0 +5160 0 +5161 0 +5162 0 +5163 0 +5164 0 +5165 0 +5166 0 +5167 1 +5168 0 +5169 0 +5170 0 +5171 0 +5172 0 +5173 0 +5174 0 +5175 1 +5176 0 +5177 0 +5178 0 +5179 0 +5180 0 +5181 0 +5182 1 +5183 0 +5184 0 +5185 0 +5186 0 +5187 0 +5188 0 +5189 0 +5190 1 +5191 0 +5192 0 +5193 0 +5194 0 +5195 0 +5196 0 +5197 0 +5198 0 +5199 1 +5200 0 +5201 0 +5202 0 +5203 0 +5204 0 +5205 0 +5206 0 +5207 0 +5208 1 +5209 0 +5210 0 +5211 0 +5212 0 +5213 0 +5214 0 +5215 0 +5216 0 +5217 0 +5218 1 +5219 0 +5220 0 +5221 0 +5222 0 +5223 0 +5224 0 +5225 0 +5226 1 +5227 0 +5228 0 +5229 0 +5230 0 +5231 0 +5232 0 +5233 0 +5234 1 +5235 0 +5236 0 +5237 0 +5238 0 +5239 0 +5240 0 +5241 0 +5242 1 +5243 0 +5244 0 +5245 0 +5246 0 +5247 0 +5248 0 +5249 0 +5250 0 +5251 1 +5252 0 +5253 0 +5254 0 +5255 0 +5256 0 +5257 0 +5258 0 +5259 0 +5260 0 +5261 0 +5262 0 +5263 0 +5264 0 +5265 0 +5266 0 +5267 0 +5268 1 +5269 0 +5270 0 +5271 0 +5272 0 +5273 0 +5274 0 +5275 0 +5276 1 +5277 0 +5278 0 +5279 0 +5280 0 +5281 0 +5282 0 +5283 1 +5284 0 +5285 0 +5286 0 +5287 0 +5288 0 +5289 0 +5290 0 +5291 0 +5292 0 +5293 1 +5294 0 +5295 0 +5296 0 +5297 0 +5298 0 +5299 0 +5300 0 +5301 1 +5302 0 +5303 0 +5304 0 +5305 0 +5306 0 +5307 0 +5308 0 +5309 0 +5310 1 +5311 0 +5312 0 +5313 0 +5314 0 +5315 0 +5316 0 +5317 0 +5318 1 +5319 0 +5320 0 +5321 0 +5322 0 +5323 0 +5324 0 +5325 1 +5326 0 +5327 0 +5328 0 +5329 0 +5330 0 +5331 0 +5332 0 +5333 0 +5334 0 +5335 0 +5336 0 +5337 0 +5338 0 +5339 0 +5340 0 +5341 0 +5342 1 +5343 0 +5344 0 +5345 0 +5346 0 +5347 0 +5348 0 +5349 1 +5350 0 +5351 0 +5352 0 +5353 0 +5354 0 +5355 0 +5356 0 +5357 0 +5358 1 +5359 0 +5360 0 +5361 0 +5362 0 +5363 0 +5364 0 +5365 0 +5366 1 +5367 0 +5368 0 +5369 0 +5370 0 +5371 0 +5372 0 +5373 1 +5374 0 +5375 0 +5376 0 +5377 0 +5378 0 +5379 0 +5380 0 +5381 1 +5382 0 +5383 0 +5384 0 +5385 0 +5386 0 +5387 0 +5388 0 +5389 0 +5390 1 +5391 0 +5392 0 +5393 0 +5394 0 +5395 0 +5396 0 +5397 0 +5398 1 +5399 0 +5400 0 +5401 0 +5402 0 +5403 0 +5404 0 +5405 0 +5406 1 +5407 0 +5408 0 +5409 0 +5410 0 +5411 0 +5412 0 +5413 0 +5414 1 +5415 0 +5416 0 +5417 0 +5418 0 +5419 0 +5420 0 +5421 0 +5422 1 +5423 0 +5424 0 +5425 0 +5426 0 +5427 0 +5428 0 +5429 0 +5430 0 +5431 0 +5432 0 +5433 0 +5434 0 +5435 0 +5436 0 +5437 0 +5438 1 +5439 0 +5440 0 +5441 0 +5442 0 +5443 0 +5444 0 +5445 0 +5446 0 +5447 1 +5448 0 +5449 0 +5450 0 +5451 0 +5452 0 +5453 0 +5454 0 +5455 0 +5456 1 +5457 0 +5458 0 +5459 0 +5460 0 +5461 0 +5462 0 +5463 0 +5464 1 +5465 0 +5466 0 +5467 0 +5468 0 +5469 0 +5470 0 +5471 0 +5472 1 +5473 0 +5474 0 +5475 0 +5476 0 +5477 0 +5478 0 +5479 0 +5480 0 +5481 1 +5482 0 +5483 0 +5484 0 +5485 0 +5486 0 +5487 0 +5488 0 +5489 1 +5490 0 +5491 0 +5492 0 +5493 0 +5494 0 +5495 0 +5496 0 +5497 0 +5498 1 +5499 0 +5500 0 +5501 0 +5502 0 +5503 0 +5504 0 +5505 0 +5506 1 +5507 0 +5508 0 +5509 0 +5510 0 +5511 0 +5512 0 +5513 0 +5514 1 +5515 0 +5516 0 +5517 0 +5518 0 +5519 0 +5520 0 +5521 0 +5522 0 +5523 1 +5524 0 +5525 0 +5526 0 +5527 0 +5528 0 +5529 0 +5530 0 +5531 1 +5532 0 +5533 0 +5534 0 +5535 0 +5536 0 +5537 0 +5538 0 +5539 0 +5540 1 +5541 0 +5542 0 +5543 0 +5544 0 +5545 0 +5546 0 +5547 0 +5548 0 +5549 1 +5550 0 +5551 0 +5552 0 +5553 0 +5554 0 +5555 0 +5556 0 +5557 0 +5558 0 +5559 0 +5560 0 +5561 0 +5562 0 +5563 0 +5564 0 +5565 1 +5566 0 +5567 0 +5568 0 +5569 0 +5570 0 +5571 1 +5572 0 +5573 0 +5574 0 +5575 0 +5576 0 +5577 0 +5578 0 +5579 1 +5580 0 +5581 0 +5582 0 +5583 0 +5584 0 +5585 0 +5586 0 +5587 0 +5588 1 +5589 0 +5590 0 +5591 0 +5592 0 +5593 0 +5594 0 +5595 0 +5596 1 +5597 0 +5598 0 +5599 0 +5600 0 +5601 0 +5602 0 +5603 0 +5604 0 +5605 0 +5606 1 +5607 0 +5608 0 +5609 0 +5610 0 +5611 0 +5612 0 +5613 0 +5614 1 +5615 0 +5616 0 +5617 0 +5618 0 +5619 0 +5620 0 +5621 0 +5622 1 +5623 0 +5624 0 +5625 0 +5626 0 +5627 0 +5628 0 +5629 0 +5630 0 +5631 0 +5632 0 +5633 0 +5634 0 +5635 0 +5636 0 +5637 0 +5638 1 +5639 0 +5640 0 +5641 0 +5642 0 +5643 0 +5644 0 +5645 0 +5646 0 +5647 1 +5648 0 +5649 0 +5650 0 +5651 0 +5652 0 +5653 0 +5654 1 +5655 0 +5656 0 +5657 0 +5658 0 +5659 0 +5660 0 +5661 0 +5662 1 +5663 0 +5664 0 +5665 0 +5666 0 +5667 0 +5668 0 +5669 0 +5670 1 +5671 0 +5672 0 +5673 0 +5674 0 +5675 0 +5676 0 +5677 0 +5678 0 +5679 1 +5680 2 +5681 1 +5682 0 +5683 0 +5684 0 +5685 0 +5686 0 +5687 1 +5688 0 +5689 0 +5690 0 +5691 0 +5692 1 +5693 0 +5694 0 +5695 0 +5696 0 +5697 1 +5698 0 +5699 0 +5700 0 +5701 0 +5702 0 +5703 0 +5704 0 +5705 1 +5706 0 +5707 0 +5708 0 +5709 0 +5710 0 +5711 1 +5712 0 +5713 0 +5714 0 +5715 0 +5716 0 +5717 0 +5718 0 +5719 0 +5720 0 +5721 0 +5722 0 +5723 0 +5724 0 +5725 0 +5726 1 +5727 0 +5728 0 +5729 0 +5730 0 +5731 0 +5732 0 +5733 0 +5734 1 +5735 0 +5736 0 +5737 0 +5738 0 +5739 0 +5740 0 +5741 0 +5742 1 +5743 0 +5744 0 +5745 0 +5746 0 +5747 0 +5748 0 +5749 0 +5750 0 +5751 1 +5752 0 +5753 0 +5754 0 +5755 0 +5756 0 +5757 0 +5758 0 +5759 1 +5760 0 +5761 0 +5762 0 +5763 0 +5764 0 +5765 0 +5766 1 +5767 0 +5768 0 +5769 0 +5770 0 +5771 0 +5772 0 +5773 0 +5774 1 +5775 0 +5776 0 +5777 0 +5778 0 +5779 0 +5780 0 +5781 0 +5782 1 +5783 0 +5784 0 +5785 0 +5786 0 +5787 0 +5788 0 +5789 0 +5790 0 +5791 1 +5792 0 +5793 0 +5794 0 +5795 0 +5796 0 +5797 0 +5798 0 +5799 0 +5800 1 +5801 0 +5802 0 +5803 0 +5804 0 +5805 0 +5806 0 +5807 0 +5808 0 +5809 1 +5810 0 +5811 0 +5812 0 +5813 0 +5814 0 +5815 0 +5816 1 +5817 0 +5818 0 +5819 0 +5820 0 +5821 0 +5822 0 +5823 0 +5824 0 +5825 1 +5826 0 +5827 0 +5828 0 +5829 0 +5830 0 +5831 0 +5832 0 +5833 0 +5834 1 +5835 0 +5836 0 +5837 0 +5838 0 +5839 0 +5840 0 +5841 0 +5842 1 +5843 0 +5844 0 +5845 0 +5846 0 +5847 0 +5848 0 +5849 0 +5850 1 +5851 0 +5852 0 +5853 0 +5854 0 +5855 0 +5856 0 +5857 0 +5858 1 +5859 0 +5860 0 +5861 0 +5862 0 +5863 0 +5864 0 +5865 0 +5866 0 +5867 1 +5868 0 +5869 0 +5870 0 +5871 0 +5872 0 +5873 0 +5874 0 +5875 1 +5876 0 +5877 0 +5878 0 +5879 0 +5880 0 +5881 0 +5882 0 +5883 0 +5884 1 +5885 0 +5886 0 +5887 0 +5888 0 +5889 0 +5890 0 +5891 1 +5892 0 +5893 0 +5894 0 +5895 0 +5896 0 +5897 0 +5898 0 +5899 0 +5900 1 +5901 0 +5902 0 +5903 0 +5904 0 +5905 0 +5906 0 +5907 0 +5908 0 +5909 1 +5910 0 +5911 0 +5912 0 +5913 0 +5914 0 +5915 0 +5916 0 +5917 1 +5918 0 +5919 0 +5920 0 +5921 0 +5922 0 +5923 0 +5924 0 +5925 0 +5926 1 +5927 0 +5928 0 +5929 0 +5930 0 +5931 0 +5932 0 +5933 0 +5934 1 +5935 0 +5936 0 +5937 0 +5938 0 +5939 0 +5940 0 +5941 0 +5942 0 +5943 0 +5944 1 +5945 0 +5946 0 +5947 0 +5948 0 +5949 0 +5950 0 +5951 0 +5952 0 +5953 0 +5954 0 +5955 0 +5956 0 +5957 0 +5958 0 +5959 0 +5960 0 +5961 0 +5962 0 +5963 0 +5964 0 +5965 0 +5966 0 +5967 0 +5968 0 +5969 0 +5970 1 +5971 0 +5972 0 +5973 0 +5974 0 +5975 0 +5976 0 +5977 0 +5978 1 +5979 0 +5980 0 +5981 0 +5982 0 +5983 0 +5984 0 +5985 0 +5986 0 +5987 1 +5988 0 +5989 0 +5990 0 +5991 0 +5992 0 +5993 0 +5994 0 +5995 0 +5996 1 +5997 0 +5998 0 +5999 0 +6000 0 +6001 0 +6002 0 +6003 0 +6004 0 +6005 0 +6006 1 +6007 0 +6008 0 +6009 0 +6010 0 +6011 0 +6012 0 +6013 0 +6014 1 +6015 0 +6016 0 +6017 0 +6018 0 +6019 0 +6020 0 +6021 0 +6022 0 +6023 1 +6024 0 +6025 0 +6026 0 +6027 0 +6028 0 +6029 0 +6030 0 +6031 1 +6032 0 +6033 0 +6034 0 +6035 0 +6036 0 +6037 0 +6038 1 +6039 0 +6040 0 +6041 0 +6042 0 +6043 0 +6044 0 +6045 0 +6046 0 +6047 0 +6048 1 +6049 0 +6050 0 +6051 0 +6052 0 +6053 0 +6054 0 +6055 1 +6056 0 +6057 0 +6058 0 +6059 0 +6060 0 +6061 1 +6062 0 +6063 0 +6064 0 +6065 0 +6066 0 +6067 0 +6068 1 +6069 0 +6070 0 +6071 0 +6072 0 +6073 0 +6074 0 +6075 0 +6076 1 +6077 0 +6078 0 +6079 0 +6080 0 +6081 0 +6082 0 +6083 0 +6084 0 +6085 1 +6086 0 +6087 0 +6088 0 +6089 0 +6090 0 +6091 0 +6092 0 +6093 0 +6094 0 +6095 1 +6096 0 +6097 0 +6098 0 +6099 0 +6100 0 +6101 0 +6102 0 +6103 0 +6104 1 +6105 0 +6106 0 +6107 0 +6108 0 +6109 0 +6110 0 +6111 0 +6112 1 +6113 0 +6114 0 +6115 0 +6116 0 +6117 0 +6118 0 +6119 0 +6120 0 +6121 0 +6122 0 +6123 0 +6124 0 +6125 1 +6126 0 +6127 0 +6128 0 +6129 0 +6130 0 +6131 0 +6132 0 +6133 0 +6134 0 +6135 0 +6136 0 +6137 0 +6138 0 +6139 0 +6140 0 +6141 0 +6142 1 +6143 0 +6144 0 +6145 0 +6146 0 +6147 0 +6148 0 +6149 0 +6150 1 +6151 0 +6152 0 +6153 0 +6154 0 +6155 0 +6156 0 +6157 0 +6158 0 +6159 1 +6160 0 +6161 0 +6162 0 +6163 0 +6164 0 +6165 0 +6166 0 +6167 1 +6168 0 +6169 0 +6170 0 +6171 0 +6172 0 +6173 0 +6174 0 +6175 1 +6176 0 +6177 0 +6178 0 +6179 0 +6180 0 +6181 0 +6182 0 +6183 1 +6184 0 +6185 0 +6186 0 +6187 0 +6188 0 +6189 0 +6190 0 +6191 0 +6192 1 +6193 0 +6194 0 +6195 0 +6196 0 +6197 0 +6198 0 +6199 0 +6200 0 +6201 1 +6202 0 +6203 0 +6204 0 +6205 0 +6206 0 +6207 0 +6208 0 +6209 0 +6210 1 +6211 0 +6212 0 +6213 0 +6214 0 +6215 0 +6216 0 +6217 1 +6218 0 +6219 0 +6220 0 +6221 0 +6222 0 +6223 0 +6224 0 +6225 1 +6226 0 +6227 0 +6228 0 +6229 0 +6230 0 +6231 0 +6232 0 +6233 0 +6234 1 +6235 0 +6236 0 +6237 0 +6238 0 +6239 0 +6240 0 +6241 1 +6242 0 +6243 0 +6244 0 +6245 0 +6246 0 +6247 0 +6248 0 +6249 0 +6250 1 +6251 0 +6252 0 +6253 0 +6254 0 +6255 0 +6256 0 +6257 0 +6258 1 +6259 0 +6260 0 +6261 0 +6262 0 +6263 0 +6264 0 +6265 0 +6266 0 +6267 0 +6268 1 +6269 0 +6270 0 +6271 0 +6272 0 +6273 0 +6274 0 +6275 0 +6276 0 +6277 1 +6278 0 +6279 0 +6280 0 +6281 0 +6282 0 +6283 0 +6284 0 +6285 1 +6286 0 +6287 0 +6288 0 +6289 0 +6290 0 +6291 0 +6292 1 +6293 0 +6294 0 +6295 0 +6296 0 +6297 0 +6298 0 +6299 1 +6300 0 +6301 0 +6302 0 +6303 0 +6304 0 +6305 0 +6306 0 +6307 1 +6308 0 +6309 0 +6310 0 +6311 0 +6312 0 +6313 0 +6314 0 +6315 1 +6316 0 +6317 0 +6318 0 +6319 0 +6320 0 +6321 0 +6322 0 +6323 0 +6324 1 +6325 0 +6326 0 +6327 0 +6328 0 +6329 0 +6330 0 +6331 0 +6332 1 +6333 0 +6334 0 +6335 0 +6336 0 +6337 0 +6338 0 +6339 0 +6340 0 +6341 1 +6342 0 +6343 0 +6344 0 +6345 0 +6346 0 +6347 0 +6348 0 +6349 0 +6350 1 +6351 0 +6352 0 +6353 0 +6354 0 +6355 0 +6356 0 +6357 0 +6358 1 +6359 0 +6360 0 +6361 0 +6362 0 +6363 0 +6364 0 +6365 0 +6366 1 +6367 0 +6368 0 +6369 0 +6370 0 +6371 0 +6372 0 +6373 0 +6374 0 +6375 1 +6376 0 +6377 0 +6378 0 +6379 0 +6380 0 +6381 0 +6382 0 +6383 1 +6384 0 +6385 0 +6386 0 +6387 0 +6388 0 +6389 0 +6390 0 +6391 4 +6392 0 +6393 1 +6394 0 +6395 0 +6396 0 +6397 1 +6398 0 +6399 0 +6400 0 +6401 0 +6402 1 +6403 0 +6404 0 +6405 0 +6406 0 +6407 1 +6408 0 +6409 0 +6410 0 +6411 0 +6412 1 +6413 0 +6414 0 +6415 0 +6416 0 +6417 0 +6418 1 +6419 0 +6420 0 +6421 0 +6422 0 +6423 0 +6424 0 +6425 1 +6426 0 +6427 0 +6428 0 +6429 0 +6430 0 +6431 0 +6432 0 +6433 0 +6434 1 +6435 0 +6436 0 +6437 0 +6438 0 +6439 0 +6440 0 +6441 0 +6442 0 +6443 1 +6444 0 +6445 0 +6446 0 +6447 0 +6448 0 +6449 0 +6450 0 +6451 0 +6452 1 +6453 0 +6454 0 +6455 0 +6456 0 +6457 0 +6458 0 +6459 0 +6460 0 +6461 0 +6462 0 +6463 1 +6464 0 +6465 0 +6466 0 +6467 0 +6468 0 +6469 0 +6470 0 +6471 0 +6472 1 +6473 0 +6474 0 +6475 0 +6476 0 +6477 0 +6478 0 +6479 0 +6480 0 +6481 0 +6482 1 +6483 0 +6484 0 +6485 0 +6486 0 +6487 0 +6488 0 +6489 0 +6490 0 +6491 0 +6492 1 +6493 0 +6494 0 +6495 0 +6496 0 +6497 0 +6498 0 +6499 0 +6500 0 +6501 0 +6502 0 +6503 0 +6504 0 +6505 0 +6506 0 +6507 0 +6508 0 +6509 0 +6510 0 +6511 0 +6512 1 +6513 0 +6514 0 +6515 0 +6516 0 +6517 0 +6518 0 +6519 0 +6520 0 +6521 1 +6522 0 +6523 0 +6524 0 +6525 0 +6526 0 +6527 0 +6528 0 +6529 0 +6530 0 +6531 1 +6532 0 +6533 0 +6534 0 +6535 0 +6536 0 +6537 0 +6538 0 +6539 0 +6540 1 +6541 0 +6542 0 +6543 0 +6544 0 +6545 0 +6546 0 +6547 0 +6548 0 +6549 0 +6550 1 +6551 0 +6552 0 +6553 0 +6554 0 +6555 0 +6556 0 +6557 0 +6558 0 +6559 0 +6560 1 +6561 0 +6562 0 +6563 0 +6564 0 +6565 0 +6566 0 +6567 0 +6568 0 +6569 1 +6570 0 +6571 0 +6572 0 +6573 0 +6574 0 +6575 0 +6576 0 +6577 1 +6578 0 +6579 0 +6580 0 +6581 0 +6582 0 +6583 0 +6584 0 +6585 0 +6586 1 +6587 0 +6588 0 +6589 0 +6590 0 +6591 0 +6592 0 +6593 0 +6594 0 +6595 1 +6596 0 +6597 0 +6598 0 +6599 0 +6600 0 +6601 0 +6602 0 +6603 0 +6604 1 +6605 0 +6606 0 +6607 0 +6608 0 +6609 0 +6610 0 +6611 0 +6612 0 +6613 1 +6614 0 +6615 0 +6616 0 +6617 0 +6618 0 +6619 0 +6620 0 +6621 0 +6622 1 +6623 0 +6624 0 +6625 0 +6626 0 +6627 0 +6628 0 +6629 0 +6630 0 +6631 1 +6632 0 +6633 0 +6634 0 +6635 0 +6636 0 +6637 0 +6638 0 +6639 0 +6640 1 +6641 0 +6642 0 +6643 0 +6644 0 +6645 0 +6646 0 +6647 0 +6648 0 +6649 0 +6650 1 +6651 0 +6652 0 +6653 0 +6654 0 +6655 0 +6656 0 +6657 0 +6658 0 +6659 0 +6660 1 +6661 0 +6662 0 +6663 0 +6664 0 +6665 0 +6666 0 +6667 0 +6668 0 +6669 1 +6670 0 +6671 0 +6672 0 +6673 0 +6674 0 +6675 0 +6676 0 +6677 0 +6678 0 +6679 1 +6680 0 +6681 0 +6682 0 +6683 0 +6684 0 +6685 0 +6686 0 +6687 0 +6688 1 +6689 0 +6690 0 +6691 0 +6692 0 +6693 0 +6694 0 +6695 0 +6696 0 +6697 0 +6698 1 +6699 0 +6700 0 +6701 0 +6702 0 +6703 0 +6704 0 +6705 0 +6706 1 +6707 0 +6708 0 +6709 0 +6710 0 +6711 0 +6712 0 +6713 0 +6714 0 +6715 0 +6716 1 +6717 0 +6718 0 +6719 0 +6720 0 +6721 0 +6722 0 +6723 0 +6724 0 +6725 0 +6726 1 +6727 0 +6728 0 +6729 0 +6730 0 +6731 0 +6732 0 +6733 0 +6734 0 +6735 0 +6736 0 +6737 1 +6738 0 +6739 0 +6740 0 +6741 0 +6742 0 +6743 0 +6744 0 +6745 0 +6746 1 +6747 0 +6748 0 +6749 0 +6750 0 +6751 0 +6752 0 +6753 0 +6754 0 +6755 0 +6756 1 +6757 0 +6758 0 +6759 0 +6760 0 +6761 0 +6762 0 +6763 0 +6764 0 +6765 0 +6766 1 +6767 0 +6768 0 +6769 0 +6770 0 +6771 0 +6772 0 +6773 0 +6774 0 +6775 1 +6776 0 +6777 0 +6778 0 +6779 0 +6780 0 +6781 0 +6782 0 +6783 0 +6784 1 +6785 0 +6786 0 +6787 0 +6788 0 +6789 0 +6790 0 +6791 0 +6792 0 +6793 0 +6794 1 +6795 0 +6796 0 +6797 0 +6798 0 +6799 0 +6800 0 +6801 0 +6802 0 +6803 1 +6804 0 +6805 0 +6806 0 +6807 0 +6808 0 +6809 0 +6810 0 +6811 0 +6812 0 +6813 1 +6814 0 +6815 0 +6816 0 +6817 0 +6818 0 +6819 0 +6820 0 +6821 0 +6822 0 +6823 0 +6824 1 +6825 0 +6826 0 +6827 0 +6828 0 +6829 0 +6830 0 +6831 0 +6832 1 +6833 0 +6834 0 +6835 0 +6836 0 +6837 0 +6838 0 +6839 0 +6840 0 +6841 0 +6842 1 +6843 0 +6844 0 +6845 0 +6846 0 +6847 0 +6848 0 +6849 0 +6850 0 +6851 1 +6852 0 +6853 0 +6854 0 +6855 0 +6856 0 +6857 0 +6858 0 +6859 0 +6860 0 +6861 0 +6862 1 +6863 0 +6864 0 +6865 0 +6866 0 +6867 0 +6868 0 +6869 0 +6870 0 +6871 1 +6872 0 +6873 0 +6874 0 +6875 0 +6876 0 +6877 0 +6878 0 +6879 1 +6880 0 +6881 0 +6882 0 +6883 0 +6884 0 +6885 0 +6886 1 +6887 0 +6888 0 +6889 0 +6890 0 +6891 0 +6892 0 +6893 0 +6894 0 +6895 1 +6896 0 +6897 0 +6898 0 +6899 0 +6900 0 +6901 0 +6902 0 +6903 0 +6904 0 +6905 0 +6906 0 +6907 0 +6908 0 +6909 0 +6910 0 +6911 0 +6912 0 +6913 0 +6914 1 +6915 0 +6916 0 +6917 0 +6918 0 +6919 0 +6920 0 +6921 0 +6922 0 +6923 1 +6924 0 +6925 0 +6926 0 +6927 0 +6928 0 +6929 0 +6930 0 +6931 0 +6932 0 +6933 0 +6934 1 +6935 0 +6936 0 +6937 0 +6938 0 +6939 0 +6940 0 +6941 0 +6942 0 +6943 0 +6944 1 +6945 0 +6946 0 +6947 0 +6948 0 +6949 0 +6950 0 +6951 0 +6952 0 +6953 0 +6954 1 +6955 0 +6956 0 +6957 0 +6958 0 +6959 0 +6960 0 +6961 0 +6962 0 +6963 0 +6964 1 +6965 0 +6966 0 +6967 0 +6968 0 +6969 0 +6970 0 +6971 0 +6972 0 +6973 0 +6974 1 +6975 0 +6976 0 +6977 0 +6978 0 +6979 0 +6980 0 +6981 0 +6982 0 +6983 1 +6984 0 +6985 0 +6986 0 +6987 0 +6988 0 +6989 0 +6990 0 +6991 0 +6992 1 +6993 0 +6994 0 +6995 0 +6996 0 +6997 0 +6998 0 +6999 0 +7000 0 +7001 1 +7002 0 +7003 0 +7004 0 +7005 0 +7006 0 +7007 0 +7008 0 +7009 0 +7010 1 +7011 0 +7012 0 +7013 0 +7014 0 +7015 0 +7016 0 +7017 0 +7018 0 +7019 0 +7020 1 +7021 0 +7022 0 +7023 0 +7024 0 +7025 0 +7026 0 +7027 0 +7028 0 +7029 0 +7030 1 +7031 0 +7032 0 +7033 0 +7034 0 +7035 0 +7036 0 +7037 0 +7038 0 +7039 1 +7040 0 +7041 0 +7042 0 +7043 0 +7044 0 +7045 0 +7046 0 +7047 0 +7048 1 +7049 0 +7050 0 +7051 0 +7052 0 +7053 0 +7054 0 +7055 0 +7056 0 +7057 0 +7058 0 +7059 1 +7060 0 +7061 0 +7062 0 +7063 0 +7064 0 +7065 0 +7066 0 +7067 0 +7068 0 +7069 1 +7070 0 +7071 0 +7072 0 +7073 0 +7074 0 +7075 0 +7076 0 +7077 0 +7078 0 +7079 1 +7080 0 +7081 0 +7082 0 +7083 0 +7084 0 +7085 0 +7086 0 +7087 1 +7088 0 +7089 0 +7090 0 +7091 0 +7092 0 +7093 0 +7094 0 +7095 0 +7096 0 +7097 1 +7098 0 +7099 0 +7100 0 +7101 0 +7102 0 +7103 0 +7104 0 +7105 1 +7106 0 +7107 0 +7108 0 +7109 0 +7110 0 +7111 0 +7112 0 +7113 0 +7114 1 +7115 0 +7116 0 +7117 0 +7118 0 +7119 0 +7120 0 +7121 0 +7122 0 +7123 0 +7124 1 +7125 0 +7126 0 +7127 0 +7128 0 +7129 0 +7130 0 +7131 0 +7132 0 +7133 0 +7134 1 +7135 0 +7136 0 +7137 0 +7138 0 +7139 0 +7140 0 +7141 0 +7142 0 +7143 1 +7144 0 +7145 0 +7146 0 +7147 0 +7148 0 +7149 0 +7150 0 +7151 0 +7152 1 +7153 0 +7154 0 +7155 0 +7156 0 +7157 0 +7158 0 +7159 0 +7160 0 +7161 0 +7162 1 +7163 0 +7164 0 +7165 0 +7166 0 +7167 0 +7168 0 +7169 0 +7170 0 +7171 0 +7172 1 +7173 0 +7174 0 +7175 0 +7176 0 +7177 0 +7178 0 +7179 0 +7180 0 +7181 0 +7182 1 +7183 0 +7184 0 +7185 0 +7186 0 +7187 0 +7188 0 +7189 0 +7190 0 +7191 0 +7192 0 +7193 1 +7194 0 +7195 0 +7196 0 +7197 0 +7198 0 +7199 0 +7200 0 +7201 0 +7202 0 +7203 1 +7204 0 +7205 0 +7206 0 +7207 0 +7208 0 +7209 0 +7210 0 +7211 0 +7212 0 +7213 0 +7214 0 +7215 0 +7216 0 +7217 0 +7218 0 +7219 0 +7220 0 +7221 0 +7222 1 +7223 0 +7224 0 +7225 0 +7226 0 +7227 0 +7228 0 +7229 0 +7230 0 +7231 0 +7232 1 +7233 0 +7234 0 +7235 0 +7236 0 +7237 0 +7238 0 +7239 0 +7240 0 +7241 0 +7242 0 +7243 1 +7244 0 +7245 0 +7246 0 +7247 0 +7248 0 +7249 0 +7250 0 +7251 0 +7252 0 +7253 1 +7254 0 +7255 0 +7256 0 +7257 0 +7258 0 +7259 0 +7260 0 +7261 0 +7262 0 +7263 0 +7264 1 +7265 0 +7266 0 +7267 0 +7268 0 +7269 0 +7270 0 +7271 0 +7272 0 +7273 0 +7274 1 +7275 0 +7276 0 +7277 0 +7278 0 +7279 0 +7280 0 +7281 0 +7282 0 +7283 0 +7284 0 +7285 1 +7286 0 +7287 0 +7288 0 +7289 0 +7290 0 +7291 0 +7292 0 +7293 0 +7294 0 +7295 0 +7296 0 +7297 0 +7298 0 +7299 0 +7300 0 +7301 0 +7302 0 +7303 0 +7304 1 +7305 0 +7306 0 +7307 0 +7308 0 +7309 0 +7310 0 +7311 0 +7312 0 +7313 0 +7314 0 +7315 1 +7316 0 +7317 0 +7318 0 +7319 0 +7320 0 +7321 0 +7322 0 +7323 0 +7324 1 +7325 0 +7326 0 +7327 0 +7328 0 +7329 0 +7330 0 +7331 0 +7332 0 +7333 1 +7334 0 +7335 0 +7336 0 +7337 0 +7338 0 +7339 0 +7340 0 +7341 0 +7342 1 +7343 0 +7344 0 +7345 0 +7346 0 +7347 0 +7348 0 +7349 0 +7350 0 +7351 0 +7352 1 +7353 0 +7354 0 +7355 0 +7356 0 +7357 0 +7358 0 +7359 0 +7360 0 +7361 0 +7362 0 +7363 1 +7364 0 +7365 0 +7366 0 +7367 0 +7368 0 +7369 0 +7370 0 +7371 0 +7372 1 +7373 0 +7374 0 +7375 0 +7376 0 +7377 0 +7378 0 +7379 0 +7380 0 +7381 0 +7382 1 +7383 0 +7384 0 +7385 0 +7386 0 +7387 0 +7388 0 +7389 0 +7390 0 +7391 1 +7392 0 +7393 0 +7394 0 +7395 0 +7396 0 +7397 0 +7398 0 +7399 0 +7400 0 +7401 1 +7402 0 +7403 0 +7404 0 +7405 0 +7406 0 +7407 0 +7408 0 +7409 0 +7410 0 +7411 0 +7412 1 +7413 0 +7414 0 +7415 0 +7416 0 +7417 0 +7418 0 +7419 0 +7420 0 +7421 0 +7422 1 +7423 0 +7424 0 +7425 0 +7426 0 +7427 0 +7428 0 +7429 0 +7430 0 +7431 0 +7432 1 +7433 0 +7434 0 +7435 0 +7436 0 +7437 0 +7438 0 +7439 0 +7440 0 +7441 1 +7442 0 +7443 0 +7444 0 +7445 0 +7446 0 +7447 0 +7448 0 +7449 1 +7450 0 +7451 0 +7452 0 +7453 0 +7454 0 +7455 0 +7456 0 +7457 0 +7458 0 +7459 0 +7460 1 +7461 0 +7462 0 +7463 0 +7464 0 +7465 0 +7466 0 +7467 0 +7468 0 +7469 1 +7470 0 +7471 0 +7472 0 +7473 0 +7474 0 +7475 0 +7476 0 +7477 0 +7478 1 +7479 0 +7480 0 +7481 0 +7482 0 +7483 0 +7484 0 +7485 0 +7486 0 +7487 1 +7488 0 +7489 0 +7490 0 +7491 0 +7492 0 +7493 0 +7494 0 +7495 0 +7496 0 +7497 1 +7498 0 +7499 0 +7500 0 +7501 0 +7502 0 +7503 0 +7504 0 +7505 0 +7506 0 +7507 0 +7508 1 +7509 0 +7510 0 +7511 0 +7512 0 +7513 0 +7514 0 +7515 0 +7516 0 +7517 0 +7518 1 +7519 0 +7520 0 +7521 0 +7522 0 +7523 0 +7524 0 +7525 0 +7526 0 +7527 0 +7528 0 +7529 0 +7530 0 +7531 0 +7532 0 +7533 0 +7534 0 +7535 0 +7536 0 +7537 0 +7538 0 +7539 1 +7540 0 +7541 0 +7542 0 +7543 0 +7544 0 +7545 0 +7546 0 +7547 0 +7548 0 +7549 2 +7550 0 +7551 0 +7552 0 +7553 0 +7554 0 +7555 0 +7556 0 +7557 1 +7558 0 +7559 0 +7560 0 +7561 0 +7562 0 +7563 0 +7564 0 +7565 0 +7566 0 +7567 0 +7568 1 +7569 0 +7570 0 +7571 0 +7572 0 +7573 0 +7574 0 +7575 0 +7576 0 +7577 0 +7578 0 +7579 0 +7580 0 +7581 0 +7582 0 +7583 0 +7584 0 +7585 0 +7586 0 +7587 0 +7588 1 +7589 0 +7590 0 +7591 0 +7592 0 +7593 0 +7594 0 +7595 0 +7596 0 +7597 0 +7598 0 +7599 1 +7600 0 +7601 0 +7602 0 +7603 0 +7604 0 +7605 0 +7606 0 +7607 0 +7608 0 +7609 0 +7610 1 +7611 0 +7612 0 +7613 0 +7614 0 +7615 0 +7616 0 +7617 0 +7618 0 +7619 0 +7620 0 +7621 1 +7622 0 +7623 0 +7624 0 +7625 0 +7626 0 +7627 1 +7628 0 +7629 0 +7630 0 +7631 0 +7632 0 +7633 0 +7634 1 +7635 0 +7636 0 +7637 0 +7638 0 +7639 0 +7640 0 +7641 1 +7642 0 +7643 0 +7644 0 +7645 0 +7646 0 +7647 0 +7648 0 +7649 1 +7650 0 +7651 0 +7652 0 +7653 0 +7654 0 +7655 0 +7656 0 +7657 0 +7658 0 +7659 0 +7660 1 +7661 0 +7662 0 +7663 0 +7664 0 +7665 0 +7666 0 +7667 0 +7668 0 +7669 0 +7670 1 +7671 0 +7672 0 +7673 0 +7674 0 +7675 0 +7676 0 +7677 0 +7678 0 +7679 0 +7680 0 +7681 1 +7682 0 +7683 0 +7684 0 +7685 0 +7686 0 +7687 0 +7688 0 +7689 0 +7690 0 +7691 1 +7692 0 +7693 0 +7694 0 +7695 0 +7696 0 +7697 0 +7698 0 +7699 0 +7700 0 +7701 0 +7702 1 +7703 0 +7704 0 +7705 0 +7706 0 +7707 0 +7708 0 +7709 0 +7710 0 +7711 0 +7712 1 +7713 0 +7714 0 +7715 0 +7716 0 +7717 0 +7718 0 +7719 0 +7720 0 +7721 0 +7722 1 +7723 0 +7724 0 +7725 0 +7726 0 +7727 0 +7728 0 +7729 0 +7730 0 +7731 0 +7732 1 +7733 0 +7734 0 +7735 0 +7736 0 +7737 0 +7738 0 +7739 0 +7740 0 +7741 0 +7742 1 +7743 0 +7744 0 +7745 0 +7746 0 +7747 0 +7748 0 +7749 0 +7750 0 +7751 0 +7752 1 +7753 0 +7754 0 +7755 0 +7756 0 +7757 0 +7758 0 +7759 0 +7760 0 +7761 1 +7762 0 +7763 0 +7764 0 +7765 0 +7766 0 +7767 0 +7768 0 +7769 0 +7770 1 +7771 0 +7772 0 +7773 0 +7774 0 +7775 0 +7776 0 +7777 0 +7778 0 +7779 1 +7780 0 +7781 0 +7782 0 +7783 0 +7784 0 +7785 0 +7786 0 +7787 0 +7788 0 +7789 1 +7790 0 +7791 0 +7792 0 +7793 0 +7794 0 +7795 0 +7796 0 +7797 0 +7798 0 +7799 1 +7800 0 +7801 0 +7802 0 +7803 0 +7804 0 +7805 0 +7806 0 +7807 0 +7808 0 +7809 0 +7810 1 +7811 0 +7812 0 +7813 0 +7814 0 +7815 0 +7816 0 +7817 0 +7818 0 +7819 1 +7820 0 +7821 0 +7822 0 +7823 0 +7824 0 +7825 0 +7826 0 +7827 0 +7828 1 +7829 0 +7830 0 +7831 0 +7832 0 +7833 0 +7834 0 +7835 0 +7836 0 +7837 0 +7838 0 +7839 1 +7840 0 +7841 0 +7842 0 +7843 0 +7844 0 +7845 0 +7846 0 +7847 0 +7848 0 +7849 1 +7850 0 +7851 0 +7852 0 +7853 0 +7854 0 +7855 0 +7856 0 +7857 0 +7858 1 +7859 0 +7860 0 +7861 0 +7862 0 +7863 0 +7864 0 +7865 0 +7866 0 +7867 0 +7868 1 +7869 0 +7870 0 +7871 0 +7872 0 +7873 0 +7874 0 +7875 0 +7876 0 +7877 0 +7878 0 +7879 0 +7880 0 +7881 0 +7882 0 +7883 0 +7884 0 +7885 0 +7886 0 +7887 1 +7888 0 +7889 0 +7890 0 +7891 0 +7892 0 +7893 0 +7894 0 +7895 0 +7896 0 +7897 0 +7898 1 +7899 0 +7900 0 +7901 0 +7902 0 +7903 0 +7904 0 +7905 0 +7906 0 +7907 0 +7908 1 +7909 0 +7910 0 +7911 0 +7912 0 +7913 0 +7914 0 +7915 0 +7916 0 +7917 0 +7918 1 +7919 0 +7920 0 +7921 0 +7922 0 +7923 0 +7924 0 +7925 0 +7926 0 +7927 0 +7928 1 +7929 0 +7930 0 +7931 0 +7932 0 +7933 0 +7934 0 +7935 0 +7936 0 +7937 0 +7938 1 +7939 0 +7940 0 +7941 0 +7942 0 +7943 0 +7944 0 +7945 0 +7946 0 +7947 0 +7948 1 +7949 0 +7950 0 +7951 0 +7952 0 +7953 0 +7954 0 +7955 0 +7956 0 +7957 0 +7958 1 +7959 0 +7960 0 +7961 0 +7962 0 +7963 0 +7964 0 +7965 0 +7966 0 +7967 0 +7968 1 +7969 0 +7970 0 +7971 0 +7972 0 +7973 0 +7974 0 +7975 0 +7976 0 +7977 0 +7978 1 +7979 0 +7980 0 +7981 0 +7982 0 +7983 0 +7984 0 +7985 1 +7986 0 +7987 0 +7988 0 +7989 0 +7990 0 +7991 0 +7992 0 +7993 0 +7994 0 +7995 1 +7996 0 +7997 0 +7998 0 +7999 0 +8000 0 +8001 0 +8002 0 +8003 0 +8004 0 +8005 0 +8006 1 +8007 0 +8008 0 +8009 0 +8010 0 +8011 0 +8012 0 +8013 0 +8014 0 +8015 1 +8016 0 +8017 0 +8018 0 +8019 0 +8020 0 +8021 0 +8022 0 +8023 0 +8024 0 +8025 1 +8026 0 +8027 0 +8028 0 +8029 0 +8030 0 +8031 0 +8032 0 +8033 0 +8034 0 +8035 0 +8036 1 +8037 0 +8038 0 +8039 0 +8040 0 +8041 0 +8042 0 +8043 0 +8044 0 +8045 0 +8046 1 +8047 0 +8048 0 +8049 0 +8050 0 +8051 0 +8052 0 +8053 0 +8054 0 +8055 0 +8056 0 +8057 1 +8058 0 +8059 0 +8060 0 +8061 0 +8062 0 +8063 0 +8064 0 +8065 0 +8066 0 +8067 1 +8068 0 +8069 0 +8070 0 +8071 0 +8072 0 +8073 0 +8074 0 +8075 0 +8076 0 +8077 0 +8078 1 +8079 0 +8080 0 +8081 0 +8082 0 +8083 0 +8084 0 +8085 0 +8086 0 +8087 0 +8088 1 +8089 0 +8090 0 +8091 0 +8092 0 +8093 0 +8094 0 +8095 0 +8096 0 +8097 0 +8098 1 +8099 0 +8100 0 +8101 0 +8102 0 +8103 0 +8104 0 +8105 1 +8106 0 +8107 0 +8108 0 +8109 0 +8110 0 +8111 0 +8112 0 +8113 0 +8114 0 +8115 1 +8116 0 +8117 0 +8118 0 +8119 0 +8120 0 +8121 0 +8122 0 +8123 0 +8124 0 +8125 1 +8126 0 +8127 0 +8128 0 +8129 0 +8130 0 +8131 0 +8132 0 +8133 0 +8134 1 +8135 0 +8136 0 +8137 0 +8138 0 +8139 0 +8140 0 +8141 0 +8142 0 +8143 0 +8144 0 +8145 1 +8146 0 +8147 0 +8148 0 +8149 0 +8150 0 +8151 0 +8152 0 +8153 0 +8154 0 +8155 0 +8156 1 +8157 0 +8158 0 +8159 0 +8160 0 +8161 0 +8162 0 +8163 0 +8164 0 +8165 0 +8166 1 +8167 0 +8168 0 +8169 0 +8170 0 +8171 0 +8172 0 +8173 0 +8174 0 +8175 0 +8176 1 +8177 0 +8178 0 +8179 0 +8180 0 +8181 0 +8182 0 +8183 0 +8184 0 +8185 0 +8186 1 +8187 0 +8188 0 +8189 0 +8190 0 +8191 0 +8192 0 +8193 0 +8194 0 +8195 0 +8196 0 +8197 1 +8198 0 +8199 0 +8200 0 +8201 0 +8202 0 +8203 0 +8204 0 +8205 0 +8206 0 +8207 1 +8208 0 +8209 0 +8210 0 +8211 0 +8212 0 +8213 0 +8214 0 +8215 0 +8216 1 +8217 0 +8218 0 +8219 0 +8220 0 +8221 0 +8222 0 +8223 0 +8224 0 +8225 1 +8226 0 +8227 0 +8228 0 +8229 0 +8230 0 +8231 0 +8232 0 +8233 0 +8234 0 +8235 1 +8236 0 +8237 0 +8238 0 +8239 0 +8240 0 +8241 0 +8242 0 +8243 0 +8244 1 +8245 0 +8246 0 +8247 0 +8248 0 +8249 0 +8250 0 +8251 0 +8252 0 +8253 0 +8254 1 +8255 0 +8256 0 +8257 0 +8258 0 +8259 0 +8260 0 +8261 0 +8262 0 +8263 0 +8264 0 +8265 1 +8266 0 +8267 0 +8268 0 +8269 0 +8270 0 +8271 0 +8272 0 +8273 0 +8274 0 +8275 1 +8276 0 +8277 0 +8278 0 +8279 0 +8280 0 +8281 0 +8282 0 +8283 0 +8284 0 +8285 0 +8286 1 +8287 0 +8288 0 +8289 0 +8290 0 +8291 0 +8292 0 +8293 0 +8294 0 +8295 0 +8296 1 +8297 0 +8298 0 +8299 0 +8300 0 +8301 0 +8302 0 +8303 0 +8304 1 +8305 0 +8306 0 +8307 0 +8308 0 +8309 0 +8310 0 +8311 0 +8312 0 +8313 0 +8314 1 +8315 0 +8316 0 +8317 0 +8318 0 +8319 0 +8320 0 +8321 0 +8322 0 +8323 0 +8324 1 +8325 0 +8326 0 +8327 0 +8328 0 +8329 0 +8330 0 +8331 0 +8332 0 +8333 0 +8334 0 +8335 0 +8336 0 +8337 0 +8338 0 +8339 0 +8340 0 +8341 0 +8342 1 +8343 0 +8344 0 +8345 0 +8346 0 +8347 0 +8348 0 +8349 0 +8350 0 +8351 1 +8352 0 +8353 0 +8354 0 +8355 0 +8356 0 +8357 0 +8358 0 +8359 0 +8360 0 +8361 1 +8362 0 +8363 0 +8364 0 +8365 0 +8366 0 +8367 0 +8368 0 +8369 0 +8370 0 +8371 1 +8372 0 +8373 0 +8374 0 +8375 0 +8376 0 +8377 0 +8378 0 +8379 0 +8380 1 +8381 0 +8382 0 +8383 0 +8384 0 +8385 0 +8386 0 +8387 0 +8388 0 +8389 1 +8390 0 +8391 0 +8392 0 +8393 0 +8394 0 +8395 0 +8396 0 +8397 0 +8398 0 +8399 1 +8400 0 +8401 0 +8402 0 +8403 0 +8404 0 +8405 0 +8406 0 +8407 0 +8408 0 +8409 1 +8410 0 +8411 0 +8412 0 +8413 0 +8414 0 +8415 0 +8416 0 +8417 0 +8418 0 +8419 1 +8420 0 +8421 0 +8422 0 +8423 0 +8424 0 +8425 0 +8426 0 +8427 0 +8428 0 +8429 0 +8430 1 +8431 0 +8432 0 +8433 0 +8434 0 +8435 0 +8436 0 +8437 0 +8438 1 +8439 0 +8440 0 +8441 0 +8442 0 +8443 0 +8444 0 +8445 0 +8446 0 +8447 1 +8448 0 +8449 0 +8450 0 +8451 0 +8452 0 +8453 0 +8454 0 +8455 0 +8456 0 +8457 1 +8458 0 +8459 0 +8460 0 +8461 0 +8462 0 +8463 0 +8464 0 +8465 0 +8466 0 +8467 1 +8468 0 +8469 0 +8470 0 +8471 0 +8472 0 +8473 0 +8474 0 +8475 0 +8476 0 +8477 1 +8478 0 +8479 0 +8480 0 +8481 0 +8482 0 +8483 0 +8484 0 +8485 0 +8486 1 +8487 0 +8488 0 +8489 0 +8490 0 +8491 0 +8492 0 +8493 0 +8494 0 +8495 0 +8496 0 +8497 0 +8498 0 +8499 0 +8500 0 +8501 0 +8502 0 +8503 0 +8504 0 +8505 0 +8506 1 +8507 0 +8508 0 +8509 0 +8510 0 +8511 0 +8512 0 +8513 0 +8514 0 +8515 0 +8516 0 +8517 0 +8518 0 +8519 0 +8520 0 +8521 0 +8522 0 +8523 1 +8524 0 +8525 0 +8526 0 +8527 0 +8528 0 +8529 0 +8530 0 +8531 0 +8532 1 +8533 0 +8534 0 +8535 0 +8536 0 +8537 0 +8538 0 +8539 0 +8540 0 +8541 1 +8542 0 +8543 0 +8544 0 +8545 0 +8546 0 +8547 0 +8548 0 +8549 1 +8550 0 +8551 0 +8552 0 +8553 0 +8554 0 +8555 0 +8556 0 +8557 0 +8558 0 +8559 1 +8560 0 +8561 0 +8562 0 +8563 0 +8564 0 +8565 0 +8566 0 +8567 0 +8568 1 +8569 0 +8570 0 +8571 0 +8572 0 +8573 0 +8574 0 +8575 0 +8576 0 +8577 1 +8578 0 +8579 0 +8580 0 +8581 0 +8582 0 +8583 0 +8584 0 +8585 0 +8586 1 +8587 0 +8588 0 +8589 0 +8590 0 +8591 0 +8592 0 +8593 0 +8594 0 +8595 0 +8596 1 +8597 0 +8598 0 +8599 0 +8600 0 +8601 0 +8602 0 +8603 0 +8604 0 +8605 0 +8606 1 +8607 0 +8608 0 +8609 0 +8610 0 +8611 0 +8612 0 +8613 0 +8614 0 +8615 0 +8616 1 +8617 0 +8618 0 +8619 0 +8620 0 +8621 0 +8622 0 +8623 0 +8624 0 +8625 1 +8626 0 +8627 0 +8628 0 +8629 0 +8630 0 +8631 0 +8632 0 +8633 1 +8634 0 +8635 0 +8636 0 +8637 0 +8638 0 +8639 0 +8640 0 +8641 0 +8642 0 +8643 1 +8644 0 +8645 0 +8646 0 +8647 0 +8648 0 +8649 0 +8650 0 +8651 1 +8652 0 +8653 0 +8654 0 +8655 0 +8656 0 +8657 0 +8658 0 +8659 0 +8660 1 +8661 0 +8662 0 +8663 0 +8664 0 +8665 0 +8666 0 +8667 0 +8668 0 +8669 1 +8670 0 +8671 0 +8672 0 +8673 0 +8674 0 +8675 0 +8676 0 +8677 1 +8678 0 +8679 0 +8680 0 +8681 0 +8682 0 +8683 0 +8684 0 +8685 0 +8686 1 +8687 0 +8688 0 +8689 0 +8690 0 +8691 0 +8692 0 +8693 0 +8694 0 +8695 0 +8696 1 +8697 0 +8698 0 +8699 0 +8700 0 +8701 0 +8702 0 +8703 0 +8704 0 +8705 1 +8706 0 +8707 0 +8708 0 +8709 0 +8710 0 +8711 0 +8712 0 +8713 0 +8714 0 +8715 1 +8716 0 +8717 0 +8718 0 +8719 0 +8720 0 +8721 0 +8722 0 +8723 0 +8724 0 +8725 1 +8726 0 +8727 0 +8728 0 +8729 0 +8730 0 +8731 0 +8732 0 +8733 0 +8734 0 +8735 1 +8736 0 +8737 0 +8738 0 +8739 0 +8740 0 +8741 0 +8742 0 +8743 0 +8744 0 +8745 1 +8746 0 +8747 0 +8748 0 +8749 0 +8750 0 +8751 0 +8752 0 +8753 0 +8754 0 +8755 1 +8756 0 +8757 0 +8758 0 +8759 0 +8760 0 +8761 0 +8762 0 +8763 1 +8764 0 +8765 0 +8766 0 +8767 0 +8768 0 +8769 0 +8770 1 +8771 0 +8772 0 +8773 0 +8774 0 +8775 0 +8776 0 +8777 0 +8778 0 +8779 0 +8780 1 +8781 0 +8782 0 +8783 0 +8784 0 +8785 0 +8786 0 +8787 0 +8788 0 +8789 1 +8790 0 +8791 0 +8792 0 +8793 0 +8794 0 +8795 0 +8796 0 +8797 0 +8798 1 +8799 0 +8800 0 +8801 0 +8802 0 +8803 0 +8804 0 +8805 0 +8806 0 +8807 3 +8808 0 +8809 0 +8810 1 +8811 0 +8812 0 +8813 0 +8814 0 +8815 1 +8816 0 +8817 0 +8818 0 +8819 0 +8820 1 +8821 0 +8822 0 +8823 0 +8824 1 +8825 0 +8826 0 +8827 0 +8828 0 +8829 0 +8830 1 +8831 0 +8832 0 +8833 0 +8834 0 +8835 0 +8836 0 +8837 1 +8838 0 +8839 0 +8840 0 +8841 0 +8842 0 +8843 0 +8844 0 +8845 1 +8846 0 +8847 0 +8848 0 +8849 0 +8850 0 +8851 0 +8852 0 +8853 0 +8854 0 +8855 1 +8856 0 +8857 0 +8858 0 +8859 0 +8860 0 +8861 0 +8862 0 +8863 0 +8864 0 +8865 1 +8866 0 +8867 0 +8868 0 +8869 0 +8870 0 +8871 0 +8872 1 +8873 0 +8874 0 +8875 0 +8876 0 +8877 0 +8878 0 +8879 0 +8880 1 +8881 0 +8882 0 +8883 0 +8884 0 +8885 0 +8886 0 +8887 0 +8888 1 +8889 0 +8890 0 +8891 0 +8892 0 +8893 0 +8894 0 +8895 0 +8896 0 +8897 0 +8898 0 +8899 0 +8900 0 +8901 0 +8902 0 +8903 0 +8904 0 +8905 1 +8906 0 +8907 0 +8908 0 +8909 0 +8910 0 +8911 0 +8912 1 +8913 0 +8914 0 +8915 0 +8916 0 +8917 0 +8918 0 +8919 0 +8920 1 +8921 0 +8922 0 +8923 0 +8924 0 +8925 0 +8926 0 +8927 0 +8928 0 +8929 1 +8930 0 +8931 0 +8932 0 +8933 0 +8934 0 +8935 0 +8936 0 +8937 0 +8938 0 +8939 1 +8940 0 +8941 0 +8942 0 +8943 0 +8944 0 +8945 0 +8946 0 +8947 0 +8948 0 +8949 1 +8950 0 +8951 0 +8952 0 +8953 0 +8954 0 +8955 0 +8956 0 +8957 0 +8958 0 +8959 1 +8960 0 +8961 0 +8962 0 +8963 0 +8964 0 +8965 0 +8966 0 +8967 0 +8968 0 +8969 1 +8970 0 +8971 0 +8972 0 +8973 0 +8974 0 +8975 0 +8976 0 +8977 0 +8978 1 +8979 0 +8980 0 +8981 0 +8982 0 +8983 0 +8984 0 +8985 0 +8986 0 +8987 1 +8988 0 +8989 0 +8990 0 +8991 0 +8992 0 +8993 0 +8994 0 +8995 0 +8996 0 +8997 1 +8998 0 +8999 0 +9000 0 +9001 0 +9002 0 +9003 0 +9004 0 +9005 0 +9006 1 +9007 0 +9008 0 +9009 0 +9010 0 +9011 0 +9012 0 +9013 0 +9014 1 +9015 0 +9016 0 +9017 0 +9018 0 +9019 0 +9020 0 +9021 0 +9022 1 +9023 0 +9024 0 +9025 0 +9026 0 +9027 0 +9028 0 +9029 0 +9030 1 +9031 0 +9032 0 +9033 0 +9034 0 +9035 0 +9036 0 +9037 0 +9038 1 +9039 0 +9040 0 +9041 0 +9042 0 +9043 0 +9044 0 +9045 0 +9046 0 +9047 1 +9048 0 +9049 0 +9050 0 +9051 0 +9052 0 +9053 0 +9054 0 +9055 1 +9056 0 +9057 0 +9058 0 +9059 0 +9060 0 +9061 0 +9062 0 +9063 1 +9064 0 +9065 0 +9066 0 +9067 0 +9068 0 +9069 0 +9070 0 +9071 0 +9072 0 +9073 1 +9074 0 +9075 0 +9076 0 +9077 0 +9078 0 +9079 0 +9080 0 +9081 0 +9082 0 +9083 0 +9084 0 +9085 0 +9086 0 +9087 0 +9088 0 +9089 0 +9090 0 +9091 0 +9092 1 +9093 0 +9094 0 +9095 0 +9096 0 +9097 0 +9098 0 +9099 0 +9100 1 +9101 0 +9102 0 +9103 0 +9104 0 +9105 0 +9106 0 +9107 0 +9108 1 +9109 0 +9110 0 +9111 0 +9112 0 +9113 0 +9114 0 +9115 0 +9116 0 +9117 1 +9118 0 +9119 0 +9120 0 +9121 0 +9122 0 +9123 0 +9124 0 +9125 0 +9126 1 +9127 0 +9128 0 +9129 0 +9130 0 +9131 0 +9132 0 +9133 0 +9134 0 +9135 1 +9136 0 +9137 0 +9138 0 +9139 0 +9140 0 +9141 0 +9142 0 +9143 1 +9144 0 +9145 0 +9146 0 +9147 0 +9148 0 +9149 0 +9150 0 +9151 0 +9152 1 +9153 0 +9154 0 +9155 0 +9156 0 +9157 0 +9158 0 +9159 0 +9160 0 +9161 1 +9162 0 +9163 0 +9164 0 +9165 0 +9166 0 +9167 0 +9168 0 +9169 1 +9170 0 +9171 0 +9172 0 +9173 0 +9174 0 +9175 0 +9176 0 +9177 0 +9178 1 +9179 0 +9180 0 +9181 0 +9182 0 +9183 0 +9184 0 +9185 0 +9186 0 +9187 0 +9188 1 +9189 0 +9190 0 +9191 0 +9192 0 +9193 0 +9194 0 +9195 0 +9196 0 +9197 1 +9198 0 +9199 0 +9200 0 +9201 0 +9202 0 +9203 0 +9204 0 +9205 0 +9206 0 +9207 0 +9208 0 +9209 0 +9210 0 +9211 0 +9212 0 +9213 0 +9214 0 +9215 0 +9216 0 +9217 0 +9218 0 +9219 0 +9220 0 +9221 1 +9222 0 +9223 0 +9224 0 +9225 0 +9226 0 +9227 0 +9228 1 +9229 0 +9230 0 +9231 0 +9232 0 +9233 0 +9234 0 +9235 0 +9236 0 +9237 1 +9238 0 +9239 0 +9240 0 +9241 0 +9242 0 +9243 0 +9244 0 +9245 0 +9246 1 +9247 0 +9248 0 +9249 0 +9250 0 +9251 0 +9252 0 +9253 0 +9254 0 +9255 1 +9256 0 +9257 0 +9258 0 +9259 0 +9260 0 +9261 1 +9262 0 +9263 0 +9264 0 +9265 0 +9266 0 +9267 0 +9268 0 +9269 0 +9270 0 +9271 0 +9272 0 +9273 0 +9274 0 +9275 0 +9276 1 +9277 0 +9278 0 +9279 0 +9280 0 +9281 0 +9282 0 +9283 0 +9284 0 +9285 0 +9286 0 +9287 0 +9288 0 +9289 0 +9290 1 +9291 0 +9292 0 +9293 0 +9294 0 +9295 0 +9296 0 +9297 0 +9298 0 +9299 0 +9300 1 +9301 0 +9302 0 +9303 0 +9304 0 +9305 0 +9306 0 +9307 0 +9308 1 +9309 0 +9310 0 +9311 0 +9312 0 +9313 0 +9314 0 +9315 0 +9316 1 +9317 0 +9318 0 +9319 0 +9320 0 +9321 0 +9322 0 +9323 1 +9324 0 +9325 0 +9326 0 +9327 0 +9328 0 +9329 0 +9330 0 +9331 1 +9332 0 +9333 0 +9334 0 +9335 0 +9336 0 +9337 0 +9338 1 +9339 0 +9340 0 +9341 0 +9342 0 +9343 0 +9344 0 +9345 1 +9346 0 +9347 0 +9348 0 +9349 0 +9350 0 +9351 0 +9352 0 +9353 0 +9354 0 +9355 1 +9356 0 +9357 0 +9358 0 +9359 0 +9360 0 +9361 0 +9362 0 +9363 1 +9364 0 +9365 0 +9366 0 +9367 0 +9368 0 +9369 0 +9370 1 +9371 0 +9372 0 +9373 0 +9374 0 +9375 0 +9376 0 +9377 0 +9378 1 +9379 0 +9380 0 +9381 0 +9382 0 +9383 0 +9384 0 +9385 0 +9386 0 +9387 0 +9388 0 +9389 0 +9390 0 +9391 0 +9392 0 +9393 0 +9394 0 +9395 1 +9396 0 +9397 0 +9398 0 +9399 0 +9400 0 +9401 0 +9402 0 +9403 1 +9404 0 +9405 0 +9406 0 +9407 0 +9408 0 +9409 0 +9410 0 +9411 0 +9412 1 +9413 0 +9414 0 +9415 0 +9416 0 +9417 0 +9418 0 +9419 0 +9420 1 +9421 0 +9422 0 +9423 0 +9424 0 +9425 0 +9426 0 +9427 0 +9428 0 +9429 1 +9430 0 +9431 0 +9432 0 +9433 0 +9434 0 +9435 0 +9436 0 +9437 0 +9438 0 +9439 1 +9440 0 +9441 0 +9442 0 +9443 0 +9444 0 +9445 0 +9446 0 +9447 0 +9448 0 +9449 1 +9450 0 +9451 0 +9452 0 +9453 0 +9454 0 +9455 0 +9456 0 +9457 1 +9458 0 +9459 0 +9460 0 +9461 0 +9462 0 +9463 0 +9464 1 +9465 0 +9466 0 +9467 0 +9468 0 +9469 0 +9470 0 +9471 0 +9472 0 +9473 1 +9474 0 +9475 0 +9476 0 +9477 0 +9478 0 +9479 0 +9480 0 +9481 1 +9482 0 +9483 0 +9484 0 +9485 0 +9486 0 +9487 0 +9488 1 +9489 0 +9490 0 +9491 0 +9492 0 +9493 0 +9494 0 +9495 0 +9496 0 +9497 1 +9498 0 +9499 0 +9500 0 +9501 0 +9502 0 +9503 0 +9504 0 +9505 0 +9506 0 +9507 0 +9508 0 +9509 0 +9510 0 +9511 0 +9512 0 +9513 0 +9514 1 +9515 0 +9516 0 +9517 0 +9518 0 +9519 0 +9520 0 +9521 0 +9522 1 +9523 0 +9524 0 +9525 0 +9526 0 +9527 0 +9528 0 +9529 0 +9530 1 +9531 0 +9532 0 +9533 0 +9534 0 +9535 0 +9536 0 +9537 0 +9538 1 +9539 0 +9540 0 +9541 0 +9542 0 +9543 0 +9544 0 +9545 0 +9546 0 +9547 1 +9548 0 +9549 0 +9550 0 +9551 0 +9552 0 +9553 0 +9554 0 +9555 1 +9556 0 +9557 0 +9558 0 +9559 0 +9560 0 +9561 0 +9562 0 +9563 1 +9564 0 +9565 0 +9566 0 +9567 0 +9568 0 +9569 0 +9570 0 +9571 0 +9572 1 +9573 0 +9574 0 +9575 0 +9576 0 +9577 0 +9578 0 +9579 0 +9580 1 +9581 0 +9582 0 +9583 0 +9584 0 +9585 0 +9586 0 +9587 0 +9588 0 +9589 1 +9590 0 +9591 0 +9592 0 +9593 0 +9594 0 +9595 0 +9596 0 +9597 0 +9598 0 +9599 0 +9600 0 +9601 0 +9602 0 +9603 0 +9604 0 +9605 0 +9606 0 +9607 0 +9608 1 +9609 0 +9610 0 +9611 0 +9612 0 +9613 0 +9614 0 +9615 1 +9616 0 +9617 0 +9618 0 +9619 0 +9620 0 +9621 0 +9622 1 +9623 0 +9624 0 +9625 0 +9626 0 +9627 0 +9628 0 +9629 0 +9630 1 +9631 0 +9632 0 +9633 0 +9634 0 +9635 0 +9636 0 +9637 0 +9638 0 +9639 1 +9640 0 +9641 0 +9642 0 +9643 0 +9644 0 +9645 0 +9646 0 +9647 0 +9648 1 +9649 0 +9650 0 +9651 0 +9652 0 +9653 0 +9654 0 +9655 0 +9656 1 +9657 0 +9658 0 +9659 0 +9660 0 +9661 0 +9662 0 +9663 1 +9664 0 +9665 0 +9666 0 +9667 0 +9668 0 +9669 0 +9670 0 +9671 0 +9672 0 +9673 1 +9674 0 +9675 0 +9676 0 +9677 0 +9678 0 +9679 0 +9680 0 +9681 1 +9682 0 +9683 0 +9684 0 +9685 0 +9686 0 +9687 0 +9688 0 +9689 1 +9690 0 +9691 0 +9692 0 +9693 0 +9694 0 +9695 0 +9696 1 +9697 0 +9698 0 +9699 0 +9700 0 +9701 0 +9702 0 +9703 0 +9704 1 +9705 0 +9706 0 +9707 0 +9708 0 +9709 0 +9710 0 +9711 0 +9712 1 +9713 0 +9714 0 +9715 0 +9716 0 +9717 0 +9718 0 +9719 0 +9720 0 +9721 0 +9722 1 +9723 0 +9724 0 +9725 0 +9726 0 +9727 0 +9728 0 +9729 0 +9730 0 +9731 1 +9732 0 +9733 0 +9734 0 +9735 0 +9736 0 +9737 0 +9738 0 +9739 0 +9740 1 +9741 0 +9742 0 +9743 0 +9744 0 +9745 0 +9746 0 +9747 0 +9748 0 +9749 1 +9750 0 +9751 0 +9752 0 +9753 0 +9754 0 +9755 0 +9756 1 +9757 0 +9758 0 +9759 0 +9760 0 +9761 0 +9762 0 +9763 0 +9764 0 +9765 0 +9766 0 +9767 0 +9768 0 +9769 0 +9770 0 +9771 0 +9772 0 +9773 1 +9774 0 +9775 0 +9776 0 +9777 0 +9778 0 +9779 0 +9780 1 +9781 0 +9782 0 +9783 0 +9784 0 +9785 0 +9786 0 +9787 0 +9788 1 +9789 0 +9790 0 +9791 0 +9792 0 +9793 0 +9794 0 +9795 0 +9796 0 +9797 0 +9798 0 +9799 0 +9800 0 +9801 0 +9802 0 +9803 1 +9804 0 +9805 0 +9806 0 +9807 0 +9808 0 +9809 0 +9810 0 +9811 0 +9812 1 +9813 0 +9814 0 +9815 0 +9816 0 +9817 0 +9818 0 +9819 0 +9820 1 +9821 0 +9822 0 +9823 0 +9824 0 +9825 0 +9826 0 +9827 0 +9828 0 +9829 1 +9830 0 +9831 0 +9832 0 +9833 0 +9834 0 +9835 0 +9836 0 +9837 0 +9838 1 +9839 0 +9840 0 +9841 0 +9842 0 +9843 0 +9844 0 +9845 0 +9846 0 +9847 0 +9848 1 +9849 0 +9850 0 +9851 0 +9852 0 +9853 0 +9854 4 +9855 0 +9856 0 +9857 1 +9858 0 +9859 0 +9860 0 +9861 0 +9862 1 +9863 0 +9864 0 +9865 0 +9866 0 +9867 0 +9868 1 +9869 0 +9870 0 +9871 0 +9872 0 +9873 1 +9874 0 +9875 0 +9876 0 +9877 0 +9878 1 +9879 0 +9880 0 +9881 0 +9882 0 +9883 0 +9884 0 +9885 0 +9886 1 +9887 0 +9888 0 +9889 0 +9890 0 +9891 0 +9892 0 +9893 0 +9894 0 +9895 1 +9896 0 +9897 0 +9898 0 +9899 0 +9900 0 +9901 0 +9902 0 +9903 0 +9904 1 +9905 0 +9906 0 +9907 0 +9908 0 +9909 0 +9910 0 +9911 0 +9912 0 +9913 0 +9914 0 +9915 0 +9916 0 +9917 0 +9918 0 +9919 0 +9920 0 +9921 0 +9922 0 +9923 0 +9924 1 +9925 0 +9926 0 +9927 0 +9928 0 +9929 0 +9930 0 +9931 0 +9932 0 +9933 0 +9934 1 +9935 0 +9936 0 +9937 0 +9938 0 +9939 0 +9940 0 +9941 0 +9942 0 +9943 0 +9944 1 +9945 0 +9946 0 +9947 0 +9948 0 +9949 0 +9950 0 +9951 0 +9952 0 +9953 0 +9954 1 +9955 0 +9956 0 +9957 0 +9958 0 +9959 0 +9960 0 +9961 0 +9962 0 +9963 1 +9964 0 +9965 0 +9966 0 +9967 0 +9968 0 +9969 0 +9970 0 +9971 0 +9972 1 +9973 0 +9974 0 +9975 0 +9976 0 +9977 0 +9978 0 +9979 0 +9980 0 +9981 0 +9982 0 +9983 1 +9984 0 +9985 0 +9986 0 +9987 0 +9988 0 +9989 0 +9990 0 +9991 0 +9992 0 +9993 1 +9994 0 +9995 0 +9996 0 +9997 0 +9998 0 +9999 0 +10000 0 +10001 0 +10002 0 +10003 0 +10004 1 +10005 0 +10006 0 +10007 0 +10008 0 +10009 0 +10010 0 +10011 0 +10012 0 +10013 1 +10014 0 +10015 0 +10016 0 +10017 0 +10018 0 +10019 0 +10020 0 +10021 0 +10022 0 +10023 1 +10024 0 +10025 0 +10026 0 +10027 0 +10028 0 +10029 0 +10030 0 +10031 1 +10032 0 +10033 0 +10034 0 +10035 0 +10036 0 +10037 0 +10038 0 +10039 0 +10040 0 +10041 1 +10042 0 +10043 0 +10044 0 +10045 0 +10046 0 +10047 0 +10048 0 +10049 0 +10050 0 +10051 1 +10052 0 +10053 0 +10054 0 +10055 0 +10056 0 +10057 0 +10058 0 +10059 0 +10060 1 +10061 0 +10062 0 +10063 0 +10064 0 +10065 0 +10066 0 +10067 0 +10068 0 +10069 1 +10070 0 +10071 0 +10072 0 +10073 0 +10074 0 +10075 0 +10076 0 +10077 0 +10078 1 +10079 0 +10080 0 +10081 0 +10082 0 +10083 0 +10084 0 +10085 0 +10086 0 +10087 1 +10088 0 +10089 0 +10090 0 +10091 0 +10092 0 +10093 0 +10094 0 +10095 0 +10096 0 +10097 1 +10098 0 +10099 0 +10100 0 +10101 0 +10102 0 +10103 0 +10104 0 +10105 0 +10106 0 +10107 0 +10108 1 +10109 0 +10110 0 +10111 0 +10112 0 +10113 0 +10114 0 +10115 0 +10116 0 +10117 0 +10118 1 +10119 0 +10120 0 +10121 0 +10122 0 +10123 0 +10124 0 +10125 0 +10126 0 +10127 1 +10128 0 +10129 0 +10130 0 +10131 0 +10132 0 +10133 0 +10134 0 +10135 0 +10136 0 +10137 1 +10138 0 +10139 0 +10140 0 +10141 0 +10142 0 +10143 0 +10144 0 +10145 0 +10146 0 +10147 1 +10148 0 +10149 0 +10150 0 +10151 0 +10152 0 +10153 0 +10154 0 +10155 0 +10156 0 +10157 1 +10158 0 +10159 0 +10160 0 +10161 0 +10162 0 +10163 0 +10164 0 +10165 0 +10166 0 +10167 1 +10168 0 +10169 0 +10170 0 +10171 0 +10172 0 +10173 0 +10174 0 +10175 0 +10176 1 +10177 0 +10178 0 +10179 0 +10180 0 +10181 0 +10182 0 +10183 0 +10184 0 +10185 1 +10186 0 +10187 0 +10188 0 +10189 0 +10190 0 +10191 0 +10192 0 +10193 1 +10194 0 +10195 0 +10196 0 +10197 0 +10198 0 +10199 0 +10200 0 +10201 1 +10202 0 +10203 0 +10204 0 +10205 0 +10206 0 +10207 0 +10208 0 +10209 0 +10210 0 +10211 1 +10212 0 +10213 0 +10214 0 +10215 0 +10216 0 +10217 0 +10218 0 +10219 0 +10220 1 +10221 0 +10222 0 +10223 0 +10224 0 +10225 0 +10226 0 +10227 0 +10228 0 +10229 0 +10230 1 +10231 0 +10232 0 +10233 0 +10234 0 +10235 0 +10236 0 +10237 0 +10238 0 +10239 0 +10240 1 +10241 0 +10242 0 +10243 0 +10244 0 +10245 0 +10246 0 +10247 0 +10248 0 +10249 0 +10250 1 +10251 0 +10252 0 +10253 0 +10254 0 +10255 0 +10256 0 +10257 0 +10258 0 +10259 0 +10260 1 +10261 0 +10262 0 +10263 0 +10264 1 +10265 0 +10266 0 +10267 0 +10268 0 +10269 0 +10270 1 +10271 0 +10272 0 +10273 0 +10274 0 +10275 0 +10276 0 +10277 0 +10278 1 +10279 0 +10280 0 +10281 0 +10282 0 +10283 0 +10284 0 +10285 0 +10286 1 +10287 0 +10288 0 +10289 0 +10290 0 +10291 0 +10292 0 +10293 0 +10294 0 +10295 0 +10296 1 +10297 0 +10298 0 +10299 0 +10300 0 +10301 0 +10302 0 +10303 0 +10304 0 +10305 1 +10306 0 +10307 0 +10308 0 +10309 0 +10310 0 +10311 0 +10312 0 +10313 0 +10314 1 +10315 0 +10316 0 +10317 0 +10318 0 +10319 0 +10320 0 +10321 0 +10322 0 +10323 1 +10324 0 +10325 0 +10326 0 +10327 0 +10328 0 +10329 0 +10330 0 +10331 0 +10332 0 +10333 1 +10334 0 +10335 0 +10336 0 +10337 0 +10338 0 +10339 0 +10340 0 +10341 0 +10342 0 +10343 0 +10344 0 +10345 0 +10346 0 +10347 0 +10348 0 +10349 0 +10350 0 +10351 1 +10352 0 +10353 0 +10354 0 +10355 0 +10356 0 +10357 0 +10358 0 +10359 0 +10360 1 +10361 0 +10362 0 +10363 0 +10364 0 +10365 0 +10366 0 +10367 0 +10368 0 +10369 0 +10370 1 +10371 0 +10372 0 +10373 0 +10374 0 +10375 0 +10376 0 +10377 0 +10378 0 +10379 0 +10380 1 +10381 0 +10382 0 +10383 0 +10384 0 +10385 0 +10386 0 +10387 1 +10388 0 +10389 0 +10390 0 +10391 0 +10392 0 +10393 0 +10394 0 +10395 1 +10396 0 +10397 0 +10398 0 +10399 0 +10400 0 +10401 0 +10402 0 +10403 0 +10404 1 +10405 0 +10406 0 +10407 0 +10408 0 +10409 0 +10410 0 +10411 0 +10412 0 +10413 0 +10414 1 +10415 0 +10416 0 +10417 0 +10418 0 +10419 0 +10420 0 +10421 0 +10422 0 +10423 1 +10424 0 +10425 0 +10426 0 +10427 0 +10428 0 +10429 0 +10430 0 +10431 0 +10432 0 +10433 1 +10434 0 +10435 0 +10436 0 +10437 0 +10438 0 +10439 0 +10440 0 +10441 0 +10442 0 +10443 1 +10444 0 +10445 0 +10446 0 +10447 0 +10448 0 +10449 0 +10450 0 +10451 0 +10452 1 +10453 0 +10454 0 +10455 0 +10456 0 +10457 0 +10458 0 +10459 0 +10460 1 +10461 0 +10462 0 +10463 0 +10464 0 +10465 0 +10466 0 +10467 0 +10468 0 +10469 1 +10470 0 +10471 0 +10472 0 +10473 0 +10474 0 +10475 0 +10476 0 +10477 0 +10478 0 +10479 1 +10480 0 +10481 0 +10482 0 +10483 0 +10484 0 +10485 0 +10486 0 +10487 0 +10488 0 +10489 1 +10490 0 +10491 0 +10492 0 +10493 0 +10494 0 +10495 0 +10496 0 +10497 0 +10498 1 +10499 0 +10500 0 +10501 0 +10502 0 +10503 0 +10504 0 +10505 0 +10506 1 +10507 0 +10508 0 +10509 0 +10510 0 +10511 0 +10512 0 +10513 0 +10514 0 +10515 0 +10516 0 +10517 1 +10518 0 +10519 0 +10520 0 +10521 0 +10522 0 +10523 0 +10524 0 +10525 0 +10526 0 +10527 1 +10528 0 +10529 0 +10530 0 +10531 0 +10532 0 +10533 0 +10534 0 +10535 0 +10536 1 +10537 0 +10538 0 +10539 0 +10540 0 +10541 0 +10542 0 +10543 0 +10544 0 +10545 1 +10546 0 +10547 0 +10548 0 +10549 0 +10550 0 +10551 0 +10552 0 +10553 0 +10554 0 +10555 1 +10556 0 +10557 0 +10558 0 +10559 0 +10560 0 +10561 0 +10562 0 +10563 0 +10564 0 +10565 0 +10566 1 +10567 0 +10568 0 +10569 0 +10570 0 +10571 0 +10572 0 +10573 0 +10574 0 +10575 0 +10576 0 +10577 0 +10578 0 +10579 0 +10580 0 +10581 0 +10582 0 +10583 0 +10584 0 +10585 0 +10586 0 +10587 1 +10588 0 +10589 0 +10590 0 +10591 0 +10592 0 +10593 0 +10594 0 +10595 0 +10596 0 +10597 0 +10598 1 +10599 0 +10600 0 +10601 0 +10602 0 +10603 0 +10604 0 +10605 0 +10606 0 +10607 0 +10608 0 +10609 1 +10610 0 +10611 0 +10612 0 +10613 0 +10614 0 +10615 0 +10616 0 +10617 1 +10618 0 +10619 0 +10620 0 +10621 0 +10622 0 +10623 0 +10624 0 +10625 1 +10626 0 +10627 0 +10628 0 +10629 0 +10630 0 +10631 0 +10632 0 +10633 0 +10634 1 +10635 0 +10636 0 +10637 0 +10638 0 +10639 0 +10640 0 +10641 0 +10642 0 +10643 0 +10644 1 +10645 0 +10646 0 +10647 0 +10648 0 +10649 0 +10650 0 +10651 0 +10652 0 +10653 1 +10654 0 +10655 0 +10656 0 +10657 0 +10658 0 +10659 0 +10660 0 +10661 1 +10662 0 +10663 0 +10664 0 +10665 0 +10666 0 +10667 0 +10668 0 +10669 0 +10670 0 +10671 1 +10672 0 +10673 0 +10674 0 +10675 0 +10676 0 +10677 0 +10678 0 +10679 0 +10680 0 +10681 1 +10682 0 +10683 0 +10684 0 +10685 0 +10686 0 +10687 0 +10688 0 +10689 0 +10690 0 +10691 0 +10692 0 +10693 0 +10694 0 +10695 0 +10696 0 +10697 0 +10698 0 +10699 0 +10700 0 +10701 1 +10702 0 +10703 0 +10704 0 +10705 0 +10706 0 +10707 0 +10708 0 +10709 0 +10710 0 +10711 1 +10712 0 +10713 0 +10714 0 +10715 0 +10716 0 +10717 0 +10718 0 +10719 0 +10720 0 +10721 1 +10722 0 +10723 0 +10724 0 +10725 0 +10726 0 +10727 0 +10728 0 +10729 0 +10730 1 +10731 0 +10732 0 +10733 0 +10734 0 +10735 0 +10736 0 +10737 0 +10738 0 +10739 0 +10740 1 +10741 0 +10742 0 +10743 0 +10744 0 +10745 0 +10746 0 +10747 0 +10748 0 +10749 1 +10750 0 +10751 0 +10752 0 +10753 0 +10754 0 +10755 0 +10756 0 +10757 0 +10758 0 +10759 1 +10760 0 +10761 0 +10762 0 +10763 0 +10764 0 +10765 0 +10766 0 +10767 0 +10768 0 +10769 0 +10770 1 +10771 0 +10772 0 +10773 0 +10774 0 +10775 0 +10776 0 +10777 0 +10778 0 +10779 0 +10780 1 +10781 0 +10782 0 +10783 0 +10784 0 +10785 0 +10786 0 +10787 0 +10788 0 +10789 0 +10790 1 +10791 0 +10792 0 +10793 0 +10794 0 +10795 0 +10796 0 +10797 0 +10798 0 +10799 0 +10800 1 +10801 0 +10802 0 +10803 0 +10804 0 +10805 0 +10806 0 +10807 0 +10808 0 +10809 0 +10810 0 +10811 0 +10812 0 +10813 0 +10814 0 +10815 0 +10816 0 +10817 0 +10818 0 +10819 0 +10820 1 +10821 0 +10822 0 +10823 0 +10824 0 +10825 0 +10826 0 +10827 0 +10828 0 +10829 0 +10830 0 +10831 1 +10832 0 +10833 0 +10834 0 +10835 0 +10836 0 +10837 0 +10838 0 +10839 0 +10840 1 +10841 0 +10842 0 +10843 0 +10844 0 +10845 0 +10846 0 +10847 0 +10848 0 +10849 0 +10850 0 +10851 0 +10852 0 +10853 0 +10854 0 +10855 0 +10856 0 +10857 0 +10858 0 +10859 0 +10860 1 +10861 0 +10862 0 +10863 0 +10864 0 +10865 0 +10866 0 +10867 0 +10868 0 +10869 1 +10870 0 +10871 0 +10872 0 +10873 0 +10874 0 +10875 0 +10876 0 +10877 0 +10878 0 +10879 0 +10880 1 +10881 0 +10882 0 +10883 0 +10884 0 +10885 0 +10886 0 +10887 0 +10888 0 +10889 0 +10890 1 +10891 0 +10892 0 +10893 0 +10894 0 +10895 0 +10896 0 +10897 0 +10898 0 +10899 0 +10900 1 +10901 0 +10902 0 +10903 0 +10904 0 +10905 0 +10906 0 +10907 0 +10908 0 +10909 0 +10910 0 +10911 1 +10912 0 +10913 0 +10914 0 +10915 0 +10916 0 +10917 0 +10918 0 +10919 0 +10920 0 +10921 1 +10922 0 +10923 0 +10924 0 +10925 0 +10926 0 +10927 0 +10928 0 +10929 0 +10930 0 +10931 1 +10932 0 +10933 0 +10934 0 +10935 0 +10936 0 +10937 0 +10938 0 +10939 0 +10940 1 +10941 0 +10942 0 +10943 0 +10944 0 +10945 0 +10946 0 +10947 0 +10948 0 +10949 1 +10950 0 +10951 0 +10952 0 +10953 0 +10954 0 +10955 0 +10956 0 +10957 0 +10958 1 +10959 0 +10960 0 +10961 0 +10962 0 +10963 0 +10964 0 +10965 0 +10966 0 +10967 0 +10968 1 +10969 0 +10970 0 +10971 0 +10972 0 +10973 0 +10974 0 +10975 0 +10976 0 +10977 0 +10978 1 +10979 0 +10980 0 +10981 0 +10982 0 +10983 0 +10984 0 +10985 0 +10986 0 +10987 0 +10988 0 +10989 1 +10990 0 +10991 0 +10992 0 +10993 0 +10994 0 +10995 0 +10996 0 +10997 0 +10998 0 +10999 0 +11000 1
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test.js new file mode 100644 index 00000000..88642843 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test.js @@ -0,0 +1,71 @@ +var ReplSet = require('./lib2/topologies/replset'), + ReadPreference = require('./lib2/topologies/read_preference'); + +// Attempt to connect +var server = new ReplSet([{ + host: 'localhost', port: 31000 +}, { + host: 'localhost', port: 31001 +}], { + setName: 'rs' +}); + +function executeCursors(_server, cb) { + var count = 100; + + for(var i = 0; i < 100; i++) { + // Execute the write + var cursor = _server.cursor('test.test', { + find: 'test.test' + , query: {a:1} + }, {readPreference: new ReadPreference('secondary')}); + + // Get the first document + cursor.next(function(err, doc) { + count = count - 1; + if(err) console.dir(err) + if(count == 0) return cb(); + }); + } +} + +server.on('connect', function(_server) { + console.log("---------------------------------- 0") + // Attempt authentication + _server.auth('scram-sha-1', 'admin', 'root', 'root', function(err, r) { + console.log("---------------------------------- 1") + // console.dir(err) + // console.dir(r) + + _server.insert('test.test', [{a:1}], function(err, r) { + console.log("---------------------------------- 2") + console.dir(err) + if(r)console.dir(r.result) + var name = null; + + _server.on('joined', function(_t, _server) { + if(name == _server.name) { + console.log("=========== joined :: " + _t + " :: " + _server.name) + executeCursors(_server, function() { + }); + } + }) + + // var s = _server.s.replicaSetState.secondaries[0]; + // s.destroy({emitClose:true}); + executeCursors(_server, function() { + console.log("============== 0") + // Attempt to force a server reconnect + var s = _server.s.replicaSetState.secondaries[0]; + name = s.name; + s.destroy({emitClose:true}); + // console.log("============== 1") + + // _server.destroy(); + // test.done(); + }); + }); + }); +}); + +server.connect(); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test1.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test1.js new file mode 100644 index 00000000..6e05ebd5 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test1.js @@ -0,0 +1,72 @@ +var Server = require('./lib/topologies/server'); + +// Attempt to connect +var server = new Server({ + host: 'localhost', port: 27017, socketTimeout: 500 +}); + +// function executeCursors(_server, cb) { +// var count = 100; +// +// for(var i = 0; i < 100; i++) { +// // Execute the write +// var cursor = _server.cursor('test.test', { +// find: 'test.test' +// , query: {a:1} +// }, {readPreference: new ReadPreference('secondary')}); +// +// // Get the first document +// cursor.next(function(err, doc) { +// count = count - 1; +// if(err) console.dir(err) +// if(count == 0) return cb(); +// }); +// } +// } + +server.on('connect', function(_server) { + + setInterval(function() { + _server.insert('test.test', [{a:1}], function(err, r) { + console.log("insert") + }); + }, 1000) + // console.log("---------------------------------- 0") + // // Attempt authentication + // _server.auth('scram-sha-1', 'admin', 'root', 'root', function(err, r) { + // console.log("---------------------------------- 1") + // // console.dir(err) + // // console.dir(r) + // + // _server.insert('test.test', [{a:1}], function(err, r) { + // console.log("---------------------------------- 2") + // console.dir(err) + // if(r)console.dir(r.result) + // var name = null; + // + // _server.on('joined', function(_t, _server) { + // if(name == _server.name) { + // console.log("=========== joined :: " + _t + " :: " + _server.name) + // executeCursors(_server, function() { + // }); + // } + // }) + // + // // var s = _server.s.replicaSetState.secondaries[0]; + // // s.destroy({emitClose:true}); + // executeCursors(_server, function() { + // console.log("============== 0") + // // Attempt to force a server reconnect + // var s = _server.s.replicaSetState.secondaries[0]; + // name = s.name; + // s.destroy({emitClose:true}); + // // console.log("============== 1") + // + // // _server.destroy(); + // // test.done(); + // }); + // }); + // }); +}); + +server.connect(); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test_bug.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test_bug.js new file mode 100644 index 00000000..6606328f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/test_bug.js @@ -0,0 +1,22 @@ +var ReplSet = require('./').ReplSet; +var replSet = new ReplSet([ + { host: '10.211.55.6', port: 31000 }, + { host: '10.211.55.12', port: 31001 }, + { host: '10.211.55.13', port: 31002 } +], { + connectionTimeout: 10000, +}); + +replSet.on('connect', function(_server) { + setInterval(function() { + _server.command('system.$cmd', { ping: 1 }, function(err, result) { + if (err) { + console.error(err); + } else { + console.log(result.result); + } + }); + }, 1000); +}); + +replSet.connect() diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/yarn.lock b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/yarn.lock new file mode 100644 index 00000000..136a0275 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/mongodb-core/yarn.lock @@ -0,0 +1,2485 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 +abbrev@1, abbrev@1.0.x: + version "1.0.9" + resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.0.9.tgz#91b4792588a7738c25f35dd6f63752a2f8776135" + +align-text@^0.1.1, align-text@^0.1.3: + version "0.1.4" + resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" + dependencies: + kind-of "^3.0.2" + longest "^1.0.1" + repeat-string "^1.5.2" + +amdefine@>=0.0.4: + version "1.0.1" + resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" + +ampersand-events@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/ampersand-events/-/ampersand-events-2.0.2.tgz#f402bc2e18305fabd995dbdcd3b7057bbdd7d347" + dependencies: + ampersand-version "^1.0.2" + lodash "^4.6.1" + +ampersand-state@^5.0.1: + version "5.0.2" + resolved "https://registry.yarnpkg.com/ampersand-state/-/ampersand-state-5.0.2.tgz#16830def866c644ecd21da8c8ba8717aa2b8d23c" + dependencies: + ampersand-events "^2.0.1" + ampersand-version "^1.0.0" + array-next "~0.0.1" + key-tree-store "^1.3.0" + lodash "^4.11.1" + +ampersand-version@^1.0.0, ampersand-version@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/ampersand-version/-/ampersand-version-1.0.2.tgz#ff8f3d4ceac4d32ccd83f6bd6697397f7b59e2c0" + dependencies: + find-root "^0.1.1" + through2 "^0.6.3" + +ansi-regex@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.0.0.tgz#c5061b6e0ef8a81775e50f5d66151bf6bf371107" + +ansi-styles@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" + +ansi@^0.3.0, ansi@~0.3.0: + version "0.3.1" + resolved "https://registry.yarnpkg.com/ansi/-/ansi-0.3.1.tgz#0c42d4fb17160d5a9af1e484bace1c66922c1b21" + +append-transform@^0.2.0: + version "0.2.2" + resolved "https://registry.yarnpkg.com/append-transform/-/append-transform-0.2.2.tgz#c41f3763e910cfe79646092667e6471809938c85" + +are-we-there-yet@~1.0.0: + version "1.0.6" + resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.0.6.tgz#a2d28c93102aa6cc96245a26cb954de06ec53f0c" + dependencies: + delegates "^1.0.0" + readable-stream "^2.0.0 || ^1.1.13" + +argparse@^1.0.7: + version "1.0.9" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.9.tgz#73d83bc263f86e97f8cc4f6bae1b0e90a7d22c86" + dependencies: + sprintf-js "~1.0.2" + +arr-diff@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-1.1.0.tgz#687c32758163588fef7de7b36fabe495eb1a399a" + dependencies: + arr-flatten "^1.0.1" + array-slice "^0.2.3" + +arr-flatten@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.0.1.tgz#e5ffe54d45e19f32f216e91eb99c8ce892bb604b" + +array-find-index@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/array-find-index/-/array-find-index-1.0.2.tgz#df010aa1287e164bbda6f9723b0a96a1ec4187a1" + +array-next@~0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/array-next/-/array-next-0.0.1.tgz#e5e4660a4c27fda8151ff7764275d00900062be1" + +array-slice@^0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-0.2.3.tgz#dd3cfb80ed7973a75117cdac69b0b99ec86186f5" + +arrify@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" + +asn1@~0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86" + +assert-plus@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-0.2.0.tgz#d74e1b87e7affc0db8aadb7021f3fe48101ab234" + +assert-plus@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" + +async@^1.4.0, async@^1.5.0, async@~1.5.0, async@1.x: + version "1.5.2" + resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" + +async@~0.1.22: + version "0.1.22" + resolved "https://registry.yarnpkg.com/async/-/async-0.1.22.tgz#0fc1aaa088a0e3ef0ebe2d8831bab0dcf8845061" + +async@~0.2.6: + version "0.2.10" + resolved "https://registry.yarnpkg.com/async/-/async-0.2.10.tgz#b6bbe0b0674b9d719708ca38de8c237cb526c3d1" + +asynckit@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" + +aws-sign2@~0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.6.0.tgz#14342dd38dbcc94d0e5b87d763cd63612c0e794f" + +aws4@^1.2.1: + version "1.5.0" + resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.5.0.tgz#0a29ffb79c31c9e712eeb087e8e7a64b4a56d755" + +babel-code-frame@^6.16.0: + version "6.16.0" + resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.16.0.tgz#f90e60da0862909d3ce098733b5d3987c97cb8de" + dependencies: + chalk "^1.1.0" + esutils "^2.0.2" + js-tokens "^2.0.0" + +babel-core@^6.18.0, babel-core@^6.2.1: + version "6.18.2" + resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.18.2.tgz#d8bb14dd6986fa4f3566a26ceda3964fa0e04e5b" + dependencies: + babel-code-frame "^6.16.0" + babel-generator "^6.18.0" + babel-helpers "^6.16.0" + babel-messages "^6.8.0" + babel-register "^6.18.0" + babel-runtime "^6.9.1" + babel-template "^6.16.0" + babel-traverse "^6.18.0" + babel-types "^6.18.0" + babylon "^6.11.0" + convert-source-map "^1.1.0" + debug "^2.1.1" + json5 "^0.5.0" + lodash "^4.2.0" + minimatch "^3.0.2" + path-is-absolute "^1.0.0" + private "^0.1.6" + slash "^1.0.0" + source-map "^0.5.0" + +babel-generator@^6.18.0: + version "6.19.0" + resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.19.0.tgz#9b2f244204777a3d6810ec127c673c87b349fac5" + dependencies: + babel-messages "^6.8.0" + babel-runtime "^6.9.0" + babel-types "^6.19.0" + detect-indent "^4.0.0" + jsesc "^1.3.0" + lodash "^4.2.0" + source-map "^0.5.0" + +babel-helpers@^6.16.0: + version "6.16.0" + resolved "https://registry.yarnpkg.com/babel-helpers/-/babel-helpers-6.16.0.tgz#1095ec10d99279460553e67eb3eee9973d3867e3" + dependencies: + babel-runtime "^6.0.0" + babel-template "^6.16.0" + +babel-messages@^6.8.0: + version "6.8.0" + resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.8.0.tgz#bf504736ca967e6d65ef0adb5a2a5f947c8e0eb9" + dependencies: + babel-runtime "^6.0.0" + +babel-polyfill@^6.2.0: + version "6.16.0" + resolved "https://registry.yarnpkg.com/babel-polyfill/-/babel-polyfill-6.16.0.tgz#2d45021df87e26a374b6d4d1a9c65964d17f2422" + dependencies: + babel-runtime "^6.9.1" + core-js "^2.4.0" + regenerator-runtime "^0.9.5" + +babel-register@^6.18.0: + version "6.18.0" + resolved "https://registry.yarnpkg.com/babel-register/-/babel-register-6.18.0.tgz#892e2e03865078dd90ad2c715111ec4449b32a68" + dependencies: + babel-core "^6.18.0" + babel-runtime "^6.11.6" + core-js "^2.4.0" + home-or-tmp "^2.0.0" + lodash "^4.2.0" + mkdirp "^0.5.1" + source-map-support "^0.4.2" + +babel-runtime@^6.0.0, babel-runtime@^6.11.6, babel-runtime@^6.9.0, babel-runtime@^6.9.1: + version "6.18.0" + resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.18.0.tgz#0f4177ffd98492ef13b9f823e9994a02584c9078" + dependencies: + core-js "^2.4.0" + regenerator-runtime "^0.9.5" + +babel-template@^6.16.0: + version "6.16.0" + resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.16.0.tgz#e149dd1a9f03a35f817ddbc4d0481988e7ebc8ca" + dependencies: + babel-runtime "^6.9.0" + babel-traverse "^6.16.0" + babel-types "^6.16.0" + babylon "^6.11.0" + lodash "^4.2.0" + +babel-traverse@^6.16.0, babel-traverse@^6.18.0: + version "6.19.0" + resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.19.0.tgz#68363fb821e26247d52a519a84b2ceab8df4f55a" + dependencies: + babel-code-frame "^6.16.0" + babel-messages "^6.8.0" + babel-runtime "^6.9.0" + babel-types "^6.19.0" + babylon "^6.11.0" + debug "^2.2.0" + globals "^9.0.0" + invariant "^2.2.0" + lodash "^4.2.0" + +babel-types@^6.16.0, babel-types@^6.18.0, babel-types@^6.19.0: + version "6.19.0" + resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.19.0.tgz#8db2972dbed01f1192a8b602ba1e1e4c516240b9" + dependencies: + babel-runtime "^6.9.1" + esutils "^2.0.2" + lodash "^4.2.0" + to-fast-properties "^1.0.1" + +babylon@^6.11.0: + version "6.14.1" + resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.14.1.tgz#956275fab72753ad9b3435d7afe58f8bf0a29815" + +balanced-match@^0.4.1: + version "0.4.2" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-0.4.2.tgz#cb3f3e3c732dc0f01ee70b403f302e61d7709838" + +bcrypt-pbkdf@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.0.tgz#3ca76b85241c7170bf7d9703e7b9aa74630040d4" + dependencies: + tweetnacl "^0.14.3" + +"binary@>= 0.3.0 < 1": + version "0.3.0" + resolved "https://registry.yarnpkg.com/binary/-/binary-0.3.0.tgz#9f60553bc5ce8c3386f3b553cff47462adecaa79" + dependencies: + buffers "~0.1.1" + chainsaw "~0.1.0" + +bl@~1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/bl/-/bl-1.1.2.tgz#fdca871a99713aa00d19e3bbba41c44787a65398" + dependencies: + readable-stream "~2.0.5" + +block-stream@*: + version "0.0.9" + resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" + dependencies: + inherits "~2.0.0" + +boolbase@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" + +boom@2.x.x: + version "2.10.1" + resolved "https://registry.yarnpkg.com/boom/-/boom-2.10.1.tgz#39c8918ceff5799f83f9492a848f625add0c766f" + dependencies: + hoek "2.x.x" + +brace-expansion@^1.0.0: + version "1.1.6" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.6.tgz#7197d7eaa9b87e648390ea61fc66c84427420df9" + dependencies: + balanced-match "^0.4.1" + concat-map "0.0.1" + +braces@^1.8.0: + version "1.8.5" + resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7" + dependencies: + expand-range "^1.8.1" + preserve "^0.2.0" + repeat-element "^1.1.2" + +bson@~0.4.23: + version "0.4.23" + resolved "https://registry.yarnpkg.com/bson/-/bson-0.4.23.tgz#e65a2e3c7507ffade4109bc7575a76e50f8da915" + +bson@~0.5.7, bson@mongodb/js-bson#1.0-branch: + version "0.5.7" + resolved "https://codeload.github.com/mongodb/js-bson/tar.gz/99156a22772f35dbfa18db3f8b34ba48ccbb4e20" + +buffer-shims@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/buffer-shims/-/buffer-shims-1.0.0.tgz#9978ce317388c649ad8793028c3477ef044a8b51" + +buffers@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/buffers/-/buffers-0.1.1.tgz#b24579c3bed4d6d396aeee6d9a8ae7f5482ab7bb" + +builtin-modules@^1.0.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" + +caching-transform@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/caching-transform/-/caching-transform-1.0.1.tgz#6dbdb2f20f8d8fbce79f3e94e9d1742dcdf5c0a1" + dependencies: + md5-hex "^1.2.0" + mkdirp "^0.5.1" + write-file-atomic "^1.1.4" + +camelcase-keys@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-2.1.0.tgz#308beeaffdf28119051efa1d932213c91b8f92e7" + dependencies: + camelcase "^2.0.0" + map-obj "^1.0.0" + +camelcase@^1.0.2: + version "1.2.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" + +camelcase@^2.0.0, camelcase@^2.0.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-2.1.1.tgz#7c1d16d679a1bbe59ca02cacecfb011e201f5a1f" + +caseless@~0.11.0: + version "0.11.0" + resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.11.0.tgz#715b96ea9841593cc33067923f5ec60ebda4f7d7" + +catharsis@~0.8.2: + version "0.8.8" + resolved "https://registry.yarnpkg.com/catharsis/-/catharsis-0.8.8.tgz#693479f43aac549d806bd73e924cd0d944951a06" + dependencies: + underscore-contrib "~0.3.0" + +center-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" + dependencies: + align-text "^0.1.3" + lazy-cache "^1.0.3" + +chainsaw@~0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/chainsaw/-/chainsaw-0.1.0.tgz#5eab50b28afe58074d0d58291388828b5e5fbc98" + dependencies: + traverse ">=0.3.0 <0.4" + +chalk@^1.1.0, chalk@^1.1.1: + version "1.1.3" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" + dependencies: + ansi-styles "^2.2.1" + escape-string-regexp "^1.0.2" + has-ansi "^2.0.0" + strip-ansi "^3.0.0" + supports-color "^2.0.0" + +cheerio@^0.19.0: + version "0.19.0" + resolved "https://registry.yarnpkg.com/cheerio/-/cheerio-0.19.0.tgz#772e7015f2ee29965096d71ea4175b75ab354925" + dependencies: + css-select "~1.0.0" + dom-serializer "~0.1.0" + entities "~1.1.1" + htmlparser2 "~3.8.1" + lodash "^3.2.0" + +cliui@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" + dependencies: + center-align "^0.1.1" + right-align "^0.1.1" + wordwrap "0.0.2" + +cliui@^3.0.3: + version "3.2.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz#120601537a916d29940f934da3b48d585a39213d" + dependencies: + string-width "^1.0.1" + strip-ansi "^3.0.1" + wrap-ansi "^2.0.0" + +co@^4.5.4, co@^4.6.0: + version "4.6.0" + resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" + +code-point-at@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" + +combined-stream@^1.0.5, combined-stream@~1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.5.tgz#938370a57b4a51dea2c77c15d5c5fdf895164009" + dependencies: + delayed-stream "~1.0.0" + +commander@^2.9.0: + version "2.9.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-2.9.0.tgz#9c99094176e12240cb22d6c5146098400fe0f7d4" + dependencies: + graceful-readlink ">= 1.0.0" + +commondir@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b" + +concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + +convert-source-map@^1.1.0, convert-source-map@^1.1.2: + version "1.3.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.3.0.tgz#e9f3e9c6e2728efc2676696a70eb382f73106a67" + +core-js@^2.4.0: + version "2.4.1" + resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.4.1.tgz#4de911e667b0eae9124e34254b53aea6fc618d3e" + +core-util-is@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + +coveralls@^2.11.6: + version "2.11.15" + resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-2.11.15.tgz#37d3474369d66c14f33fa73a9d25cee6e099fca0" + dependencies: + js-yaml "3.6.1" + lcov-parse "0.0.10" + log-driver "1.2.5" + minimist "1.2.0" + request "2.75.0" + +cross-spawn@^4: + version "4.0.2" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-4.0.2.tgz#7b9247621c23adfdd3856004a823cbe397424d41" + dependencies: + lru-cache "^4.0.1" + which "^1.2.9" + +cryptiles@2.x.x: + version "2.0.5" + resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-2.0.5.tgz#3bdfecdc608147c1c67202fa291e7dca59eaa3b8" + dependencies: + boom "2.x.x" + +css-select@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/css-select/-/css-select-1.0.0.tgz#b1121ca51848dd264e2244d058cee254deeb44b0" + dependencies: + boolbase "~1.0.0" + css-what "1.0" + domutils "1.4" + nth-check "~1.0.0" + +css-what@1.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/css-what/-/css-what-1.0.0.tgz#d7cc2df45180666f99d2b14462639469e00f736c" + +currently-unhandled@^0.4.1: + version "0.4.1" + resolved "https://registry.yarnpkg.com/currently-unhandled/-/currently-unhandled-0.4.1.tgz#988df33feab191ef799a61369dd76c17adf957ea" + dependencies: + array-find-index "^1.0.1" + +dashdash@^1.12.0: + version "1.14.1" + resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" + dependencies: + assert-plus "^1.0.0" + +debug@^2.1.1, debug@^2.1.3, debug@^2.2.0: + version "2.3.3" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.3.3.tgz#40c453e67e6e13c901ddec317af8986cda9eff8c" + dependencies: + ms "0.7.2" + +debug@~2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.2.0.tgz#f87057e995b1a1f6ae6a4960664137bc56f039da" + dependencies: + ms "0.7.1" + +decamelize@^1.0.0, decamelize@^1.1.1, decamelize@^1.1.2: + version "1.2.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" + +deep-is@~0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" + +delayed-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" + +delegates@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" + +detect-indent@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-4.0.0.tgz#f76d064352cdf43a1cb6ce619c4ee3a9475de208" + dependencies: + repeating "^2.0.0" + +docopt@~0.6.2: + version "0.6.2" + resolved "https://registry.yarnpkg.com/docopt/-/docopt-0.6.2.tgz#b28e9e2220da5ec49f7ea5bb24a47787405eeb11" + +dom-serializer@~0.1.0, dom-serializer@0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-0.1.0.tgz#073c697546ce0780ce23be4a28e293e40bc30c82" + dependencies: + domelementtype "~1.1.1" + entities "~1.1.1" + +domelementtype@~1.1.1: + version "1.1.3" + resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-1.1.3.tgz#bd28773e2642881aec51544924299c5cd822185b" + +domelementtype@1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-1.3.0.tgz#b17aed82e8ab59e52dd9c19b1756e0fc187204c2" + +domhandler@2.3: + version "2.3.0" + resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-2.3.0.tgz#2de59a0822d5027fabff6f032c2b25a2a8abe738" + dependencies: + domelementtype "1" + +domutils@1.4: + version "1.4.3" + resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.4.3.tgz#0865513796c6b306031850e175516baf80b72a6f" + dependencies: + domelementtype "1" + +domutils@1.5: + version "1.5.1" + resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.5.1.tgz#dcd8488a26f563d61079e48c9f7b7e32373682cf" + dependencies: + dom-serializer "0" + domelementtype "1" + +downcache@0.0.8: + version "0.0.8" + resolved "https://registry.yarnpkg.com/downcache/-/downcache-0.0.8.tgz#332320dde5806ea55d2e6d2ea674990bda4e8b75" + dependencies: + extend "2.0.x" + graceful-fs "2.0.3" + limiter "1.0.x" + mkdirp "~0.3.5" + npmlog "1.0.0" + request "^2.34.0" + +ecc-jsbn@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505" + dependencies: + jsbn "~0.1.0" + +entities@~1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/entities/-/entities-1.1.1.tgz#6e5c2d0a5621b5dadaecef80b90edfb5cd7772f0" + +entities@1.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/entities/-/entities-1.0.0.tgz#b2987aa3821347fcde642b24fdfc9e4fb712bf26" + +error-ex@^1.2.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.0.tgz#e67b43f3e82c96ea3a584ffee0b9fc3325d802d9" + dependencies: + is-arrayish "^0.2.1" + +es6-promise@^3.0.2: + version "3.3.1" + resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.3.1.tgz#a08cdde84ccdbf34d027a1451bc91d4bcd28a613" + +es6-promise@3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.2.1.tgz#ec56233868032909207170c39448e24449dd1fc4" + +escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + +escodegen@1.1.x: + version "1.1.0" + resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.1.0.tgz#c663923f6e20aad48d0c0fa49f31c6d4f49360cf" + dependencies: + esprima "~1.0.4" + estraverse "~1.5.0" + esutils "~1.0.0" + optionalDependencies: + source-map "~0.1.30" + +escodegen@1.8.x: + version "1.8.1" + resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.8.1.tgz#5a5b53af4693110bebb0867aa3430dd3b70a1018" + dependencies: + esprima "^2.7.1" + estraverse "^1.9.1" + esutils "^2.0.2" + optionator "^0.8.1" + optionalDependencies: + source-map "~0.2.0" + +esprima@^2.6.0, esprima@^2.7.1, esprima@2.7.x: + version "2.7.3" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.7.3.tgz#96e3b70d5779f6ad49cd032673d1c312767ba581" + +esprima@~1.0.4, esprima@1.0.x: + version "1.0.4" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-1.0.4.tgz#9f557e08fc3b4d26ece9dd34f8fbf476b62585ad" + +"esprima@https://github.com/ariya/esprima/tarball/49a2eccb243f29bd653b11e9419241a9d726af7c": + version "1.1.0-dev-harmony" + resolved "https://github.com/ariya/esprima/tarball/49a2eccb243f29bd653b11e9419241a9d726af7c#a03eaca83ec1125aa3d4acddd2636b4dd707db67" + +estraverse@^1.9.1: + version "1.9.3" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.9.3.tgz#af67f2dc922582415950926091a4005d29c9bb44" + +estraverse@~1.5.0: + version "1.5.1" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.5.1.tgz#867a3e8e58a9f84618afb6c2ddbcd916b7cbaf71" + +esutils@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" + +esutils@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-1.0.0.tgz#8151d358e20c8acc7fb745e7472c0025fe496570" + +expand-brackets@^0.1.1: + version "0.1.5" + resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b" + dependencies: + is-posix-bracket "^0.1.0" + +expand-range@^1.8.1: + version "1.8.2" + resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337" + dependencies: + fill-range "^2.1.0" + +extend@~3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.0.tgz#5a474353b9f3353ddd8176dfd37b91c83a46f1d4" + +extend@2.0.x: + version "2.0.1" + resolved "https://registry.yarnpkg.com/extend/-/extend-2.0.1.tgz#1ee8010689e7395ff9448241c98652bc759a8260" + +extsprintf@1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.0.2.tgz#e1080e0658e300b06294990cc70e1502235fd550" + +fast-levenshtein@~2.0.4: + version "2.0.5" + resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.5.tgz#bd33145744519ab1c36c3ee9f31f08e9079b67f2" + +figures@^1.4.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/figures/-/figures-1.7.0.tgz#cbe1e3affcf1cd44b80cadfed28dc793a9701d2e" + dependencies: + escape-string-regexp "^1.0.5" + object-assign "^4.1.0" + +filename-regex@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.0.tgz#996e3e80479b98b9897f15a8a58b3d084e926775" + +fill-range@^2.1.0: + version "2.2.3" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.3.tgz#50b77dfd7e469bc7492470963699fe7a8485a723" + dependencies: + is-number "^2.1.0" + isobject "^2.0.0" + randomatic "^1.1.3" + repeat-element "^1.1.2" + repeat-string "^1.5.2" + +find-cache-dir@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-0.1.1.tgz#c8defae57c8a52a8a784f9e31c57c742e993a0b9" + dependencies: + commondir "^1.0.1" + mkdirp "^0.5.1" + pkg-dir "^1.0.0" + +find-root@^0.1.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/find-root/-/find-root-0.1.2.tgz#98d2267cff1916ccaf2743b3a0eea81d79d7dcd1" + +find-up@^1.0.0: + version "1.1.2" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f" + dependencies: + path-exists "^2.0.0" + pinkie-promise "^2.0.0" + +for-in@^0.1.5: + version "0.1.6" + resolved "https://registry.yarnpkg.com/for-in/-/for-in-0.1.6.tgz#c9f96e89bfad18a545af5ec3ed352a1d9e5b4dc8" + +for-own@^0.1.1: + version "0.1.4" + resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.4.tgz#0149b41a39088c7515f51ebe1c1386d45f935072" + dependencies: + for-in "^0.1.5" + +foreground-child@^1.3.3, foreground-child@^1.3.5: + version "1.5.3" + resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-1.5.3.tgz#94dd6aba671389867de8e57e99f1c2ecfb15c01a" + dependencies: + cross-spawn "^4" + signal-exit "^3.0.0" + +forever-agent@~0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" + +form-data@~2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.0.0.tgz#6f0aebadcc5da16c13e1ecc11137d85f9b883b25" + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.5" + mime-types "^2.1.11" + +form-data@~2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.1.2.tgz#89c3534008b97eada4cbb157d58f6f5df025eae4" + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.5" + mime-types "^2.1.12" + +fs-extra@^0.22.1: + version "0.22.1" + resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-0.22.1.tgz#5fd6f8049dc976ca19eb2355d658173cabcce056" + dependencies: + graceful-fs "^4.1.2" + jsonfile "^2.1.0" + rimraf "^2.2.8" + +fs-extra@~0.30.0: + version "0.30.0" + resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-0.30.0.tgz#f233ffcc08d4da7d432daa449776989db1df93f0" + dependencies: + graceful-fs "^4.1.2" + jsonfile "^2.1.0" + klaw "^1.0.0" + path-is-absolute "^1.0.0" + rimraf "^2.2.8" + +fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + +fstream@^1.0.2: + version "1.0.10" + resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.10.tgz#604e8a92fe26ffd9f6fae30399d4984e1ab22822" + dependencies: + graceful-fs "^4.1.2" + inherits "~2.0.0" + mkdirp ">=0.5 0" + rimraf "2" + +"fstream@>= 0.1.30 < 1": + version "0.1.31" + resolved "https://registry.yarnpkg.com/fstream/-/fstream-0.1.31.tgz#7337f058fbbbbefa8c9f561a28cab0849202c988" + dependencies: + graceful-fs "~3.0.2" + inherits "~2.0.0" + mkdirp "0.5" + rimraf "2" + +gauge@~1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/gauge/-/gauge-1.0.2.tgz#53e25965dfaf1c85be3a2a0633306a24a67dc2f9" + dependencies: + ansi "^0.3.0" + has-unicode "^1.0.0" + +generate-function@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/generate-function/-/generate-function-2.0.0.tgz#6858fe7c0969b7d4e9093337647ac79f60dfbe74" + +generate-object-property@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/generate-object-property/-/generate-object-property-1.2.0.tgz#9c0e1c40308ce804f4783618b937fa88f99d50d0" + dependencies: + is-property "^1.0.0" + +get-mongodb-version@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/get-mongodb-version/-/get-mongodb-version-0.0.1.tgz#bc8aa433ba2fdd57fa33312dcf89f06f3a908caa" + dependencies: + debug "^2.2.0" + lodash.startswith "^3.0.1" + minimist "^1.1.1" + mongodb "^2.0.39" + which "^1.1.1" + +get-stdin@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe" + +getpass@^0.1.1: + version "0.1.6" + resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.6.tgz#283ffd9fc1256840875311c1b60e8c40187110e6" + dependencies: + assert-plus "^1.0.0" + +gleak@0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/gleak/-/gleak-0.5.0.tgz#9cd7694be50d6dbeb842021ed8160814c51faddf" + +glob-base@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4" + dependencies: + glob-parent "^2.0.0" + is-glob "^2.0.0" + +glob-parent@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28" + dependencies: + is-glob "^2.0.0" + +glob@^5.0.15: + version "5.0.15" + resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1" + dependencies: + inflight "^1.0.4" + inherits "2" + minimatch "2 || 3" + once "^1.3.0" + path-is-absolute "^1.0.0" + +glob@^6.0.2: + version "6.0.4" + resolved "https://registry.yarnpkg.com/glob/-/glob-6.0.4.tgz#0f08860f6a155127b2fadd4f9ce24b1aab6e4d22" + dependencies: + inflight "^1.0.4" + inherits "2" + minimatch "2 || 3" + once "^1.3.0" + path-is-absolute "^1.0.0" + +glob@^7.0.5: + version "7.1.1" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.1.tgz#805211df04faaf1c63a3600306cdf5ade50b2ec8" + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.2" + once "^1.3.0" + path-is-absolute "^1.0.0" + +globals@^9.0.0: + version "9.14.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-9.14.0.tgz#8859936af0038741263053b39d0e76ca241e4034" + +graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9: + version "4.1.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658" + +graceful-fs@~3.0.2: + version "3.0.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-3.0.11.tgz#7613c778a1afea62f25c630a086d7f3acbbdd818" + dependencies: + natives "^1.1.0" + +graceful-fs@2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-2.0.3.tgz#7cd2cdb228a4a3f36e95efa6cc142de7d1a136d0" + +"graceful-readlink@>= 1.0.0": + version "1.0.1" + resolved "https://registry.yarnpkg.com/graceful-readlink/-/graceful-readlink-1.0.1.tgz#4cafad76bc62f02fa039b2f94e9a3dd3a391a725" + +handlebars@^4.0.1: + version "4.0.6" + resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.6.tgz#2ce4484850537f9c97a8026d5399b935c4ed4ed7" + dependencies: + async "^1.4.0" + optimist "^0.6.1" + source-map "^0.4.4" + optionalDependencies: + uglify-js "^2.6" + +handlebars@2.0.0-alpha.1: + version v2.0.0-alpha.1 + resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-2.0.0-alpha.1.tgz#c4d149068c713de0afa7f45bbb88a2ca73715afd" + dependencies: + optimist "~0.3" + optionalDependencies: + uglify-js "~2.3" + +har-validator@~2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-2.0.6.tgz#cdcbc08188265ad119b6a5a7c8ab70eecfb5d27d" + dependencies: + chalk "^1.1.1" + commander "^2.9.0" + is-my-json-valid "^2.12.4" + pinkie-promise "^2.0.0" + +has-ansi@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" + dependencies: + ansi-regex "^2.0.0" + +has-flag@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" + +has-unicode@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-1.0.1.tgz#c46fceea053eb8ec789bffbba25fca52dfdcf38e" + +hawk@~3.1.3: + version "3.1.3" + resolved "https://registry.yarnpkg.com/hawk/-/hawk-3.1.3.tgz#078444bd7c1640b0fe540d2c9b73d59678e8e1c4" + dependencies: + boom "2.x.x" + cryptiles "2.x.x" + hoek "2.x.x" + sntp "1.x.x" + +hoek@2.x.x: + version "2.16.3" + resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed" + +home-or-tmp@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8" + dependencies: + os-homedir "^1.0.0" + os-tmpdir "^1.0.1" + +hosted-git-info@^2.1.4: + version "2.1.5" + resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.1.5.tgz#0ba81d90da2e25ab34a332e6ec77936e1598118b" + +htmlparser2@~3.8.1: + version "3.8.3" + resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-3.8.3.tgz#996c28b191516a8be86501a7d79757e5c70c1068" + dependencies: + domelementtype "1" + domhandler "2.3" + domutils "1.5" + entities "1.0" + readable-stream "1.1" + +http-signature@~1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.1.1.tgz#df72e267066cd0ac67fb76adf8e134a8fbcf91bf" + dependencies: + assert-plus "^0.2.0" + jsprim "^1.2.2" + sshpk "^1.7.0" + +imurmurhash@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" + +indent-string@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-2.1.0.tgz#8e2d48348742121b4a8218b7a137e9a52049dc80" + dependencies: + repeating "^2.0.0" + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@~2.0.0, inherits@~2.0.1, inherits@2: + version "2.0.3" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" + +integra@0.1.8: + version "0.1.8" + resolved "https://registry.yarnpkg.com/integra/-/integra-0.1.8.tgz#8d5b8019f87ea3704e6c97da2c912e14ec3bece7" + dependencies: + escodegen "1.1.x" + esprima "1.0.x" + handlebars "2.0.0-alpha.1" + mkdirp latest + rimraf "2.2.6" + +invariant@^2.2.0: + version "2.2.2" + resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.2.tgz#9e1f56ac0acdb6bf303306f338be3b204ae60360" + dependencies: + loose-envify "^1.0.0" + +invert-kv@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6" + +is-arrayish@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" + +is-buffer@^1.0.2: + version "1.1.4" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.4.tgz#cfc86ccd5dc5a52fa80489111c6920c457e2d98b" + +is-builtin-module@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-builtin-module/-/is-builtin-module-1.0.0.tgz#540572d34f7ac3119f8f76c30cbc1b1e037affbe" + dependencies: + builtin-modules "^1.0.0" + +is-dotfile@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.2.tgz#2c132383f39199f8edc268ca01b9b007d205cc4d" + +is-equal-shallow@^0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534" + dependencies: + is-primitive "^2.0.0" + +is-extglob@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0" + +is-finite@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.0.2.tgz#cc6677695602be550ef11e8b4aa6305342b6d0aa" + dependencies: + number-is-nan "^1.0.0" + +is-fullwidth-code-point@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" + dependencies: + number-is-nan "^1.0.0" + +is-glob@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-1.1.3.tgz#b4c64b8303d39114492a460d364ccfb0d3c0a045" + +is-glob@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" + dependencies: + is-extglob "^1.0.0" + +is-my-json-valid@^2.12.4: + version "2.15.0" + resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.15.0.tgz#936edda3ca3c211fd98f3b2d3e08da43f7b2915b" + dependencies: + generate-function "^2.0.0" + generate-object-property "^1.1.0" + jsonpointer "^4.0.0" + xtend "^4.0.0" + +is-number@^2.0.2, is-number@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f" + dependencies: + kind-of "^3.0.2" + +is-posix-bracket@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" + +is-primitive@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575" + +is-property@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-property/-/is-property-1.0.2.tgz#57fe1c4e48474edd65b09911f26b1cd4095dda84" + +is-typedarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" + +is-utf8@^0.2.0: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" + +isarray@~1.0.0, isarray@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + +isarray@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" + +isexe@^1.1.1: + version "1.1.2" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-1.1.2.tgz#36f3e22e60750920f5e7241a476a8c6a42275ad0" + +isobject@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-0.2.0.tgz#a3432192f39b910b5f02cc989487836ec70aa85e" + +isobject@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" + dependencies: + isarray "1.0.0" + +isstream@~0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" + +istanbul@^0.4.1: + version "0.4.5" + resolved "https://registry.yarnpkg.com/istanbul/-/istanbul-0.4.5.tgz#65c7d73d4c4da84d4f3ac310b918fb0b8033733b" + dependencies: + abbrev "1.0.x" + async "1.x" + escodegen "1.8.x" + esprima "2.7.x" + glob "^5.0.15" + handlebars "^4.0.1" + js-yaml "3.x" + mkdirp "0.5.x" + nopt "3.x" + once "1.x" + resolve "1.1.x" + supports-color "^3.1.0" + which "^1.1.1" + wordwrap "^1.0.0" + +jodid25519@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/jodid25519/-/jodid25519-1.0.2.tgz#06d4912255093419477d425633606e0e90782967" + dependencies: + jsbn "~0.1.0" + +js-tokens@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-2.0.0.tgz#79903f5563ee778cc1162e6dcf1a0027c97f9cb5" + +js-yaml@3.6.1: + version "3.6.1" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.6.1.tgz#6e5fe67d8b205ce4d22fad05b7781e8dadcc4b30" + dependencies: + argparse "^1.0.7" + esprima "^2.6.0" + +js-yaml@3.x: + version "3.7.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.7.0.tgz#5c967ddd837a9bfdca5f2de84253abe8a1c03b80" + dependencies: + argparse "^1.0.7" + esprima "^2.6.0" + +js2xmlparser@~0.1.0: + version "0.1.9" + resolved "https://registry.yarnpkg.com/js2xmlparser/-/js2xmlparser-0.1.9.tgz#2c516788e09460637f9a403dfed7b925f71d239e" + +jsbn@~0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.0.tgz#650987da0dd74f4ebf5a11377a2aa2d273e97dfd" + +jsdoc@3.3.0-alpha8: + version "3.3.0-alpha8" + resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.3.0-alpha8.tgz#d7960708ec99f5390dca78ba8da9677188a17363" + dependencies: + async "~0.1.22" + catharsis "~0.8.2" + esprima "https://github.com/ariya/esprima/tarball/49a2eccb243f29bd653b11e9419241a9d726af7c" + js2xmlparser "~0.1.0" + marked "~0.3.1" + requizzle "~0.1.1" + strip-json-comments "~0.1.3" + taffydb "https://github.com/hegemonic/taffydb/tarball/master" + underscore "~1.6.0" + wrench "~1.3.9" + +jsesc@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-1.3.0.tgz#46c3fec8c1892b12b0833db9bc7622176dbab34b" + +json-schema@0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" + +json-stringify-safe@~5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" + +json5@^0.5.0: + version "0.5.1" + resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821" + +jsonfile@^2.1.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-2.4.0.tgz#3736a2b428b87bbda0cc83b53fa3d633a35c2ae8" + optionalDependencies: + graceful-fs "^4.1.6" + +jsonpointer@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/jsonpointer/-/jsonpointer-4.0.0.tgz#6661e161d2fc445f19f98430231343722e1fcbd5" + +jsprim@^1.2.2: + version "1.3.1" + resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.3.1.tgz#2a7256f70412a29ee3670aaca625994c4dcff252" + dependencies: + extsprintf "1.0.2" + json-schema "0.2.3" + verror "1.3.6" + +kerberos@0.0.17: + version "0.0.17" + resolved "https://registry.yarnpkg.com/kerberos/-/kerberos-0.0.17.tgz#29a67c0b127bfa52bdd3b53b7b8c8659a9a084f8" + dependencies: + nan "~2.0" + +key-tree-store@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/key-tree-store/-/key-tree-store-1.3.0.tgz#5ea29afc2529a425938437d6955b714ce6a9791f" + +kind-of@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-1.1.0.tgz#140a3d2d41a36d2efcfa9377b62c24f8495a5c44" + +kind-of@^3.0.2: + version "3.0.4" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.0.4.tgz#7b8ecf18a4e17f8269d73b501c9f232c96887a74" + dependencies: + is-buffer "^1.0.2" + +klaw@^1.0.0: + version "1.3.1" + resolved "https://registry.yarnpkg.com/klaw/-/klaw-1.3.1.tgz#4088433b46b3b1ba259d78785d8e96f73ba02439" + optionalDependencies: + graceful-fs "^4.1.9" + +lazy-cache@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" + +lcid@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835" + dependencies: + invert-kv "^1.0.0" + +lcov-parse@0.0.10: + version "0.0.10" + resolved "https://registry.yarnpkg.com/lcov-parse/-/lcov-parse-0.0.10.tgz#1b0b8ff9ac9c7889250582b70b71315d9da6d9a3" + +levn@~0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" + dependencies: + prelude-ls "~1.1.2" + type-check "~0.3.2" + +limiter@1.0.x: + version "1.0.5" + resolved "https://registry.yarnpkg.com/limiter/-/limiter-1.0.5.tgz#9630b2a0d3bad63203f96e3d96f32f83d442dfc8" + +load-json-file@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" + dependencies: + graceful-fs "^4.1.2" + parse-json "^2.2.0" + pify "^2.0.0" + pinkie-promise "^2.0.0" + strip-bom "^2.0.0" + +lodash._baseassign@^3.0.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz#8c38a099500f215ad09e59f1722fd0c52bfe0a4e" + dependencies: + lodash._basecopy "^3.0.0" + lodash.keys "^3.0.0" + +lodash._basecopy@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz#8da0e6a876cf344c0ad8a54882111dd3c5c7ca36" + +lodash._bindcallback@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz#e531c27644cf8b57a99e17ed95b35c748789392e" + +lodash._createassigner@^3.0.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/lodash._createassigner/-/lodash._createassigner-3.1.1.tgz#838a5bae2fdaca63ac22dee8e19fa4e6d6970b11" + dependencies: + lodash._bindcallback "^3.0.0" + lodash._isiterateecall "^3.0.0" + lodash.restparam "^3.0.0" + +lodash._getnative@^3.0.0: + version "3.9.1" + resolved "https://registry.yarnpkg.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz#570bc7dede46d61cdcde687d65d3eecbaa3aaff5" + +lodash._isiterateecall@^3.0.0: + version "3.0.9" + resolved "https://registry.yarnpkg.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz#5203ad7ba425fae842460e696db9cf3e6aac057c" + +lodash._root@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/lodash._root/-/lodash._root-3.0.1.tgz#fba1c4524c19ee9a5f8136b4609f017cf4ded692" + +lodash.assign@^3.0.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/lodash.assign/-/lodash.assign-3.2.0.tgz#3ce9f0234b4b2223e296b8fa0ac1fee8ebca64fa" + dependencies: + lodash._baseassign "^3.0.0" + lodash._createassigner "^3.0.0" + lodash.keys "^3.0.0" + +lodash.defaults@^3.1.2: + version "3.1.2" + resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-3.1.2.tgz#c7308b18dbf8bc9372d701a73493c61192bd2e2c" + dependencies: + lodash.assign "^3.0.0" + lodash.restparam "^3.0.0" + +lodash.defaults@^4.0.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-4.2.0.tgz#d09178716ffea4dde9e5fb7b37f6f0802274580c" + +lodash.difference@^4.1.1: + version "4.5.0" + resolved "https://registry.yarnpkg.com/lodash.difference/-/lodash.difference-4.5.0.tgz#9ccb4e505d486b91651345772885a2df27fd017c" + +lodash.isarguments@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a" + +lodash.isarray@^3.0.0: + version "3.0.4" + resolved "https://registry.yarnpkg.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz#79e4eb88c36a8122af86f844aa9bcd851b5fbb55" + +lodash.keys@^3.0.0: + version "3.1.2" + resolved "https://registry.yarnpkg.com/lodash.keys/-/lodash.keys-3.1.2.tgz#4dbc0472b156be50a0b286855d1bd0b0c656098a" + dependencies: + lodash._getnative "^3.0.0" + lodash.isarguments "^3.0.0" + lodash.isarray "^3.0.0" + +lodash.restparam@^3.0.0: + version "3.6.1" + resolved "https://registry.yarnpkg.com/lodash.restparam/-/lodash.restparam-3.6.1.tgz#936a4e309ef330a7645ed4145986c85ae5b20805" + +lodash.startswith@^3.0.1: + version "3.2.0" + resolved "https://registry.yarnpkg.com/lodash.startswith/-/lodash.startswith-3.2.0.tgz#fc2e1ed2c6df8c777117632e87fe4a9181d483fb" + dependencies: + lodash._root "^3.0.0" + +lodash@^3.2.0: + version "3.10.1" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6" + +lodash@^4.11.1, lodash@^4.2.0, lodash@^4.6.1: + version "4.17.2" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.2.tgz#34a3055babe04ce42467b607d700072c7ff6bf42" + +log-driver@1.2.5: + version "1.2.5" + resolved "https://registry.yarnpkg.com/log-driver/-/log-driver-1.2.5.tgz#7ae4ec257302fd790d557cb10c97100d857b0056" + +longest@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" + +loose-envify@^1.0.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.3.0.tgz#6b26248c42f6d4fa4b0d8542f78edfcde35642a8" + dependencies: + js-tokens "^2.0.0" + +loud-rejection@^1.0.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/loud-rejection/-/loud-rejection-1.6.0.tgz#5b46f80147edee578870f086d04821cf998e551f" + dependencies: + currently-unhandled "^0.4.1" + signal-exit "^3.0.0" + +lru-cache@^4.0.1: + version "4.0.2" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.0.2.tgz#1d17679c069cda5d040991a09dbc2c0db377e55e" + dependencies: + pseudomap "^1.0.1" + yallist "^2.0.0" + +map-obj@^1.0.0, map-obj@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-1.0.1.tgz#d933ceb9205d82bdcf4886f6742bdc2b4dea146d" + +marked@~0.3.1: + version "0.3.6" + resolved "https://registry.yarnpkg.com/marked/-/marked-0.3.6.tgz#b2c6c618fccece4ef86c4fc6cb8a7cbf5aeda8d7" + +"match-stream@>= 0.0.2 < 1": + version "0.0.2" + resolved "https://registry.yarnpkg.com/match-stream/-/match-stream-0.0.2.tgz#99eb050093b34dffade421b9ac0b410a9cfa17cf" + dependencies: + buffers "~0.1.1" + readable-stream "~1.0.0" + +md5-hex@^1.2.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/md5-hex/-/md5-hex-1.3.0.tgz#d2c4afe983c4370662179b8cad145219135046c4" + dependencies: + md5-o-matic "^0.1.1" + +md5-o-matic@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/md5-o-matic/-/md5-o-matic-0.1.1.tgz#822bccd65e117c514fab176b25945d54100a03c3" + +meow@^3.1.0: + version "3.7.0" + resolved "https://registry.yarnpkg.com/meow/-/meow-3.7.0.tgz#72cb668b425228290abbfa856892587308a801fb" + dependencies: + camelcase-keys "^2.0.0" + decamelize "^1.1.2" + loud-rejection "^1.0.0" + map-obj "^1.0.1" + minimist "^1.1.3" + normalize-package-data "^2.3.4" + object-assign "^4.0.1" + read-pkg-up "^1.0.1" + redent "^1.0.0" + trim-newlines "^1.0.0" + +micromatch@~2.1.6: + version "2.1.6" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.1.6.tgz#51a65a9dcbfb92113292a071e04da35a81e9050e" + dependencies: + arr-diff "^1.0.1" + braces "^1.8.0" + debug "^2.1.3" + expand-brackets "^0.1.1" + filename-regex "^2.0.0" + is-glob "^1.1.3" + kind-of "^1.1.0" + object.omit "^0.2.1" + parse-glob "^3.0.0" + regex-cache "^0.4.0" + +mime-db@~1.25.0: + version "1.25.0" + resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.25.0.tgz#c18dbd7c73a5dbf6f44a024dc0d165a1e7b1c392" + +mime-types@^2.1.11, mime-types@^2.1.12, mime-types@~2.1.7: + version "2.1.13" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.13.tgz#e07aaa9c6c6b9a7ca3012c69003ad25a39e92a88" + dependencies: + mime-db "~1.25.0" + +minimatch@^3.0.2, "minimatch@2 || 3": + version "3.0.3" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.3.tgz#2a4e4090b96b2db06a9d7df01055a62a77c9b774" + dependencies: + brace-expansion "^1.0.0" + +minimist@^1.1.0, minimist@^1.1.1, minimist@^1.1.3, minimist@^1.2.0, minimist@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" + +minimist@~0.0.1: + version "0.0.10" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" + +minimist@0.0.8: + version "0.0.8" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" + +mkdirp@^0.5.0, mkdirp@^0.5.1, "mkdirp@>=0.5 0", mkdirp@0.5, mkdirp@0.5.x, mkdirp@latest: + version "0.5.1" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" + dependencies: + minimist "0.0.8" + +mkdirp@~0.3.5: + version "0.3.5" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.3.5.tgz#de3e5f8961c88c787ee1368df849ac4413eca8d7" + +mkdirp@0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.0.tgz#1d73076a6df986cd9344e15e71fcc05a4c9abf12" + dependencies: + minimist "0.0.8" + +mongodb-core@^1.2.24: + version "1.3.21" + resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-1.3.21.tgz#fe129e7bee2b3b26c1409de02ab60d03f6291cca" + dependencies: + bson "~0.4.23" + require_optional "~1.0.0" + +mongodb-core@2.0.14: + version "2.0.14" + resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-2.0.14.tgz#4e8743b87343d169a7622535edbd47dcacd790be" + dependencies: + bson "~0.5.6" + require_optional "~1.0.0" + +mongodb-download-url@^0.1.10: + version "0.1.10" + resolved "https://registry.yarnpkg.com/mongodb-download-url/-/mongodb-download-url-0.1.10.tgz#a7047eec95001de9f4df39f7e4030dc87eb3f806" + dependencies: + async "^1.5.0" + debug "^2.2.0" + lodash.defaults "^4.0.0" + minimist "^1.2.0" + mongodb-version-list "^0.0.3" + request "^2.65.0" + semver "^5.0.3" + +mongodb-topology-manager@1.0.6: + version "1.0.6" + resolved "https://registry.yarnpkg.com/mongodb-topology-manager/-/mongodb-topology-manager-1.0.6.tgz#ac02c3bbe247ca41bd9a30a757b4394c0372c57f" + dependencies: + babel-core "^6.2.1" + babel-polyfill "^6.2.0" + co "^4.6.0" + es6-promise "^3.0.2" + kerberos "0.0.17" + mkdirp "^0.5.1" + mongodb-core "^1.2.24" + rimraf "^2.4.3" + +mongodb-version-list@^0.0.3, mongodb-version-list@0.0.3: + version "0.0.3" + resolved "https://registry.yarnpkg.com/mongodb-version-list/-/mongodb-version-list-0.0.3.tgz#bbb261861f041fcfc5bc72b5fe2681788bd52cef" + dependencies: + cheerio "^0.19.0" + debug "^2.2.0" + downcache "0.0.8" + fs-extra "^0.22.1" + minimist "^1.1.1" + semver "^5.0.1" + +mongodb-version-manager@christkv/mongodb-version-manager#master: + version "1.0.7" + resolved "https://codeload.github.com/christkv/mongodb-version-manager/tar.gz/3ea7c20925d6a0b3a9243d341d3c69abf95e66b6" + dependencies: + ampersand-state "^5.0.1" + async "~1.5.0" + chalk "^1.1.1" + debug "~2.2.0" + docopt "~0.6.2" + figures "^1.4.0" + fs-extra "~0.30.0" + get-mongodb-version "0.0.1" + lodash.defaults "^3.1.2" + lodash.difference "^4.1.1" + mongodb-download-url "^0.1.10" + mongodb-version-list "0.0.3" + nugget "^2.0.0" + semver "~5.1.0" + tar "~2.2.1" + tildify "~1.2.0" + untildify "~2.1.0" + unzip "^0.1.11" + +mongodb@^2.0.39: + version "2.2.12" + resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-2.2.12.tgz#2a86f10228f911e9d6fefdbd7d922188d7b730f9" + dependencies: + es6-promise "3.2.1" + mongodb-core "2.0.14" + readable-stream "2.1.5" + +ms@0.7.1: + version "0.7.1" + resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.1.tgz#9cd13c03adbff25b65effde7ce864ee952017098" + +ms@0.7.2: + version "0.7.2" + resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.2.tgz#ae25cf2512b3885a1d95d7f037868d8431124765" + +nan@~2.0: + version "2.0.9" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.0.9.tgz#d02a770f46778842cceb94e17cab31ffc7234a05" + +natives@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/natives/-/natives-1.1.0.tgz#e9ff841418a6b2ec7a495e939984f78f163e6e31" + +node-uuid@~1.4.7: + version "1.4.7" + resolved "https://registry.yarnpkg.com/node-uuid/-/node-uuid-1.4.7.tgz#6da5a17668c4b3dd59623bda11cf7fa4c1f60a6f" + +nopt@3.x: + version "3.0.6" + resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.6.tgz#c6465dbf08abcd4db359317f79ac68a646b28ff9" + dependencies: + abbrev "1" + +normalize-package-data@^2.3.2, normalize-package-data@^2.3.4: + version "2.3.5" + resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.3.5.tgz#8d924f142960e1777e7ffe170543631cc7cb02df" + dependencies: + hosted-git-info "^2.1.4" + is-builtin-module "^1.0.0" + semver "2 || 3 || 4 || 5" + validate-npm-package-license "^3.0.1" + +npmlog@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-1.0.0.tgz#ed2f290b60316887c39e0da9f09f8d13847cef0f" + dependencies: + ansi "~0.3.0" + are-we-there-yet "~1.0.0" + gauge "~1.0.2" + +nth-check@~1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-1.0.1.tgz#9929acdf628fc2c41098deab82ac580cf149aae4" + dependencies: + boolbase "~1.0.0" + +nugget@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/nugget/-/nugget-2.0.1.tgz#201095a487e1ad36081b3432fa3cada4f8d071b0" + dependencies: + debug "^2.1.3" + minimist "^1.1.0" + pretty-bytes "^1.0.2" + progress-stream "^1.1.0" + request "^2.45.0" + single-line-log "^1.1.2" + throttleit "0.0.2" + +number-is-nan@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" + +nyc@^5.5.0: + version "5.6.0" + resolved "https://registry.yarnpkg.com/nyc/-/nyc-5.6.0.tgz#0eb394d16f3ef9ff1b440fd93b1a7ab530092754" + dependencies: + append-transform "^0.2.0" + arrify "^1.0.1" + caching-transform "^1.0.0" + convert-source-map "^1.1.2" + find-cache-dir "^0.1.1" + foreground-child "^1.3.5" + glob "^6.0.2" + istanbul "^0.4.1" + md5-hex "^1.2.0" + micromatch "~2.1.6" + mkdirp "^0.5.0" + pkg-up "^1.0.0" + read-pkg "^1.1.0" + resolve-from "^2.0.0" + rimraf "^2.5.0" + signal-exit "^2.1.1" + source-map "^0.5.3" + spawn-wrap "^1.1.1" + strip-bom "^2.0.0" + yargs "^3.15.0" + +oauth-sign@~0.8.1: + version "0.8.2" + resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43" + +object-assign@^4.0.1, object-assign@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.0.tgz#7a3b3d0e98063d43f4c03f2e8ae6cd51a86883a0" + +object-keys@~0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-0.4.0.tgz#28a6aae7428dd2c3a92f3d95f21335dd204e0336" + +object.omit@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-0.2.1.tgz#ca9af6631df6883fe61bae74df82a4fbc9df2e92" + dependencies: + for-own "^0.1.1" + isobject "^0.2.0" + +once@^1.3.0, once@1.x: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + dependencies: + wrappy "1" + +optimist@^0.6.1, optimist@latest: + version "0.6.1" + resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" + dependencies: + minimist "~0.0.1" + wordwrap "~0.0.2" + +optimist@~0.3, optimist@~0.3.5: + version "0.3.7" + resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.3.7.tgz#c90941ad59e4273328923074d2cf2e7cbc6ec0d9" + dependencies: + wordwrap "~0.0.2" + +optionator@^0.8.1: + version "0.8.2" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64" + dependencies: + deep-is "~0.1.3" + fast-levenshtein "~2.0.4" + levn "~0.3.0" + prelude-ls "~1.1.2" + type-check "~0.3.2" + wordwrap "~1.0.0" + +os-homedir@^1.0.0, os-homedir@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" + +os-locale@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz#20f9f17ae29ed345e8bde583b13d2009803c14d9" + dependencies: + lcid "^1.0.0" + +os-tmpdir@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" + +"over@>= 0.0.5 < 1": + version "0.0.5" + resolved "https://registry.yarnpkg.com/over/-/over-0.0.5.tgz#f29852e70fd7e25f360e013a8ec44c82aedb5708" + +parse-glob@^3.0.0: + version "3.0.4" + resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c" + dependencies: + glob-base "^0.3.0" + is-dotfile "^1.0.0" + is-extglob "^1.0.0" + is-glob "^2.0.0" + +parse-json@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" + dependencies: + error-ex "^1.2.0" + +path-exists@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b" + dependencies: + pinkie-promise "^2.0.0" + +path-is-absolute@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + +path-type@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441" + dependencies: + graceful-fs "^4.1.2" + pify "^2.0.0" + pinkie-promise "^2.0.0" + +pify@^2.0.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" + +pinkie-promise@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" + dependencies: + pinkie "^2.0.0" + +pinkie@^2.0.0: + version "2.0.4" + resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" + +pkg-dir@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-1.0.0.tgz#7a4b508a8d5bb2d629d447056ff4e9c9314cf3d4" + dependencies: + find-up "^1.0.0" + +pkg-up@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/pkg-up/-/pkg-up-1.0.0.tgz#3e08fb461525c4421624a33b9f7e6d0af5b05a26" + dependencies: + find-up "^1.0.0" + +prelude-ls@~1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" + +preserve@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" + +pretty-bytes@^1.0.2: + version "1.0.4" + resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-1.0.4.tgz#0a22e8210609ad35542f8c8d5d2159aff0751c84" + dependencies: + get-stdin "^4.0.1" + meow "^3.1.0" + +private@^0.1.6: + version "0.1.6" + resolved "https://registry.yarnpkg.com/private/-/private-0.1.6.tgz#55c6a976d0f9bafb9924851350fe47b9b5fbb7c1" + +process-nextick-args@~1.0.6: + version "1.0.7" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3" + +progress-stream@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/progress-stream/-/progress-stream-1.2.0.tgz#2cd3cfea33ba3a89c9c121ec3347abe9ab125f77" + dependencies: + speedometer "~0.1.2" + through2 "~0.2.3" + +pseudomap@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" + +"pullstream@>= 0.4.1 < 1": + version "0.4.1" + resolved "https://registry.yarnpkg.com/pullstream/-/pullstream-0.4.1.tgz#d6fb3bf5aed697e831150eb1002c25a3f8ae1314" + dependencies: + over ">= 0.0.5 < 1" + readable-stream "~1.0.31" + setimmediate ">= 1.0.2 < 2" + slice-stream ">= 1.0.0 < 2" + +punycode@^1.4.1: + version "1.4.1" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" + +qs@~6.2.0: + version "6.2.1" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.2.1.tgz#ce03c5ff0935bc1d9d69a9f14cbd18e568d67625" + +qs@~6.3.0: + version "6.3.0" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.3.0.tgz#f403b264f23bc01228c74131b407f18d5ea5d442" + +randomatic@^1.1.3: + version "1.1.6" + resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-1.1.6.tgz#110dcabff397e9dcff7c0789ccc0a49adf1ec5bb" + dependencies: + is-number "^2.0.2" + kind-of "^3.0.2" + +read-pkg-up@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" + dependencies: + find-up "^1.0.0" + read-pkg "^1.0.0" + +read-pkg@^1.0.0, read-pkg@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28" + dependencies: + load-json-file "^1.0.0" + normalize-package-data "^2.3.2" + path-type "^1.0.0" + +"readable-stream@^2.0.0 || ^1.1.13": + version "2.2.2" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.2.2.tgz#a9e6fec3c7dda85f8bb1b3ba7028604556fc825e" + dependencies: + buffer-shims "^1.0.0" + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "~1.0.0" + process-nextick-args "~1.0.6" + string_decoder "~0.10.x" + util-deprecate "~1.0.1" + +"readable-stream@>=1.0.33-1 <1.1.0-0", readable-stream@~1.0.0, readable-stream@~1.0.31: + version "1.0.34" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + +readable-stream@~1.1.9: + version "1.1.14" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + +readable-stream@~2.0.5: + version "2.0.6" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.0.6.tgz#8f90341e68a53ccc928788dacfcd11b36eb9b78e" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "~1.0.0" + process-nextick-args "~1.0.6" + string_decoder "~0.10.x" + util-deprecate "~1.0.1" + +readable-stream@1.1: + version "1.1.13" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.13.tgz#f6eef764f514c89e2b9e23146a75ba106756d23e" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + +readable-stream@2.1.5: + version "2.1.5" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.1.5.tgz#66fa8b720e1438b364681f2ad1a63c618448c9d0" + dependencies: + buffer-shims "^1.0.0" + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "~1.0.0" + process-nextick-args "~1.0.6" + string_decoder "~0.10.x" + util-deprecate "~1.0.1" + +redent@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/redent/-/redent-1.0.0.tgz#cf916ab1fd5f1f16dfb20822dd6ec7f730c2afde" + dependencies: + indent-string "^2.1.0" + strip-indent "^1.0.1" + +regenerator-runtime@^0.9.5: + version "0.9.6" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.9.6.tgz#d33eb95d0d2001a4be39659707c51b0cb71ce029" + +regex-cache@^0.4.0: + version "0.4.3" + resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.3.tgz#9b1a6c35d4d0dfcef5711ae651e8e9d3d7114145" + dependencies: + is-equal-shallow "^0.1.3" + is-primitive "^2.0.0" + +repeat-element@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.2.tgz#ef089a178d1483baae4d93eb98b4f9e4e11d990a" + +repeat-string@^1.5.2: + version "1.6.1" + resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" + +repeating@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" + dependencies: + is-finite "^1.0.0" + +request@^2.34.0, request@^2.45.0, request@^2.65.0: + version "2.79.0" + resolved "https://registry.yarnpkg.com/request/-/request-2.79.0.tgz#4dfe5bf6be8b8cdc37fcf93e04b65577722710de" + dependencies: + aws-sign2 "~0.6.0" + aws4 "^1.2.1" + caseless "~0.11.0" + combined-stream "~1.0.5" + extend "~3.0.0" + forever-agent "~0.6.1" + form-data "~2.1.1" + har-validator "~2.0.6" + hawk "~3.1.3" + http-signature "~1.1.0" + is-typedarray "~1.0.0" + isstream "~0.1.2" + json-stringify-safe "~5.0.1" + mime-types "~2.1.7" + oauth-sign "~0.8.1" + qs "~6.3.0" + stringstream "~0.0.4" + tough-cookie "~2.3.0" + tunnel-agent "~0.4.1" + uuid "^3.0.0" + +request@2.75.0: + version "2.75.0" + resolved "https://registry.yarnpkg.com/request/-/request-2.75.0.tgz#d2b8268a286da13eaa5d01adf5d18cc90f657d93" + dependencies: + aws-sign2 "~0.6.0" + aws4 "^1.2.1" + bl "~1.1.2" + caseless "~0.11.0" + combined-stream "~1.0.5" + extend "~3.0.0" + forever-agent "~0.6.1" + form-data "~2.0.0" + har-validator "~2.0.6" + hawk "~3.1.3" + http-signature "~1.1.0" + is-typedarray "~1.0.0" + isstream "~0.1.2" + json-stringify-safe "~5.0.1" + mime-types "~2.1.7" + node-uuid "~1.4.7" + oauth-sign "~0.8.1" + qs "~6.2.0" + stringstream "~0.0.4" + tough-cookie "~2.3.0" + tunnel-agent "~0.4.1" + +require_optional@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/require_optional/-/require_optional-1.0.0.tgz#52a86137a849728eb60a55533617f8f914f59abf" + dependencies: + resolve-from "^2.0.0" + semver "^5.1.0" + +requizzle@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/requizzle/-/requizzle-0.1.1.tgz#bad811e66c59251fe97e084295c33bcdbcf8e0ba" + dependencies: + underscore "~1.6.0" + +resolve-from@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-2.0.0.tgz#9480ab20e94ffa1d9e80a804c7ea147611966b57" + +resolve@1.1.x: + version "1.1.7" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" + +right-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" + dependencies: + align-text "^0.1.1" + +rimraf@^2.2.8, rimraf@^2.3.3, rimraf@^2.4.3, rimraf@^2.5.0, rimraf@2: + version "2.5.4" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.5.4.tgz#96800093cbf1a0c86bd95b4625467535c29dfa04" + dependencies: + glob "^7.0.5" + +rimraf@2.2.6: + version "2.2.6" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.6.tgz#c59597569b14d956ad29cacc42bdddf5f0ea4f4c" + +semver@^5.0.1, semver@^5.0.3, semver@^5.1.0, "semver@2 || 3 || 4 || 5": + version "5.3.0" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f" + +semver@~5.1.0: + version "5.1.1" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.1.1.tgz#a3292a373e6f3e0798da0b20641b9a9c5bc47e19" + +semver@4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/semver/-/semver-4.1.0.tgz#bc80a9ff68532814362cc3cfda3c7b75ed9c321c" + +"setimmediate@>= 1.0.1 < 2", "setimmediate@>= 1.0.2 < 2": + version "1.0.5" + resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" + +signal-exit@^2.0.0, signal-exit@^2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-2.1.2.tgz#375879b1f92ebc3b334480d038dc546a6d558564" + +signal-exit@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.1.tgz#5a4c884992b63a7acd9badb7894c3ee9cfccad81" + +single-line-log@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/single-line-log/-/single-line-log-1.1.2.tgz#c2f83f273a3e1a16edb0995661da0ed5ef033364" + dependencies: + string-width "^1.0.1" + +slash@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/slash/-/slash-1.0.0.tgz#c41f2f6c39fc16d1cd17ad4b5d896114ae470d55" + +"slice-stream@>= 1.0.0 < 2": + version "1.0.0" + resolved "https://registry.yarnpkg.com/slice-stream/-/slice-stream-1.0.0.tgz#5b33bd66f013b1a7f86460b03d463dec39ad3ea0" + dependencies: + readable-stream "~1.0.31" + +slide@^1.1.5: + version "1.1.6" + resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707" + +sntp@1.x.x: + version "1.0.9" + resolved "https://registry.yarnpkg.com/sntp/-/sntp-1.0.9.tgz#6541184cc90aeea6c6e7b35e2659082443c66198" + dependencies: + hoek "2.x.x" + +source-map-support@^0.4.2: + version "0.4.6" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.4.6.tgz#32552aa64b458392a85eab3b0b5ee61527167aeb" + dependencies: + source-map "^0.5.3" + +source-map@^0.4.4: + version "0.4.4" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" + dependencies: + amdefine ">=0.0.4" + +source-map@^0.5.0, source-map@^0.5.3, source-map@~0.5.1: + version "0.5.6" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.6.tgz#75ce38f52bf0733c5a7f0c118d81334a2bb5f412" + +source-map@~0.1.30, source-map@~0.1.7: + version "0.1.43" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.1.43.tgz#c24bc146ca517c1471f5dacbe2571b2b7f9e3346" + dependencies: + amdefine ">=0.0.4" + +source-map@~0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.2.0.tgz#dab73fbcfc2ba819b4de03bd6f6eaa48164b3f9d" + dependencies: + amdefine ">=0.0.4" + +spawn-wrap@^1.1.1: + version "1.2.4" + resolved "https://registry.yarnpkg.com/spawn-wrap/-/spawn-wrap-1.2.4.tgz#920eb211a769c093eebfbd5b0e7a5d2e68ab2e40" + dependencies: + foreground-child "^1.3.3" + mkdirp "^0.5.0" + os-homedir "^1.0.1" + rimraf "^2.3.3" + signal-exit "^2.0.0" + which "^1.2.4" + +spdx-correct@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-1.0.2.tgz#4b3073d933ff51f3912f03ac5519498a4150db40" + dependencies: + spdx-license-ids "^1.0.2" + +spdx-expression-parse@~1.0.0: + version "1.0.4" + resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz#9bdf2f20e1f40ed447fbe273266191fced51626c" + +spdx-license-ids@^1.0.2: + version "1.2.2" + resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz#c9df7a3424594ade6bd11900d596696dc06bac57" + +speedometer@~0.1.2: + version "0.1.4" + resolved "https://registry.yarnpkg.com/speedometer/-/speedometer-0.1.4.tgz#9876dbd2a169d3115402d48e6ea6329c8816a50d" + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + +sshpk@^1.7.0: + version "1.10.1" + resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.10.1.tgz#30e1a5d329244974a1af61511339d595af6638b0" + dependencies: + asn1 "~0.2.3" + assert-plus "^1.0.0" + dashdash "^1.12.0" + getpass "^0.1.1" + optionalDependencies: + bcrypt-pbkdf "^1.0.0" + ecc-jsbn "~0.1.1" + jodid25519 "^1.0.0" + jsbn "~0.1.0" + tweetnacl "~0.14.0" + +string_decoder@~0.10.x: + version "0.10.31" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" + +string-width@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" + dependencies: + code-point-at "^1.0.0" + is-fullwidth-code-point "^1.0.0" + strip-ansi "^3.0.0" + +stringstream@~0.0.4: + version "0.0.5" + resolved "https://registry.yarnpkg.com/stringstream/-/stringstream-0.0.5.tgz#4e484cd4de5a0bbbee18e46307710a8a81621878" + +strip-ansi@^3.0.0, strip-ansi@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + dependencies: + ansi-regex "^2.0.0" + +strip-bom@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" + dependencies: + is-utf8 "^0.2.0" + +strip-indent@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-1.0.1.tgz#0c7962a6adefa7bbd4ac366460a638552ae1a0a2" + dependencies: + get-stdin "^4.0.1" + +strip-json-comments@~0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-0.1.3.tgz#164c64e370a8a3cc00c9e01b539e569823f0ee54" + +supports-color@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" + +supports-color@^3.1.0: + version "3.1.2" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.1.2.tgz#72a262894d9d408b956ca05ff37b2ed8a6e2a2d5" + dependencies: + has-flag "^1.0.0" + +"taffydb@https://github.com/hegemonic/taffydb/tarball/master": + version "2.6.2" + resolved "https://github.com/hegemonic/taffydb/tarball/master#a4ee71882143901531fc170f6d22af053565a0c5" + +tar@~2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.1.tgz#8e4d2a256c0e2185c6b18ad694aec968b83cb1d1" + dependencies: + block-stream "*" + fstream "^1.0.2" + inherits "2" + +throttleit@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/throttleit/-/throttleit-0.0.2.tgz#cfedf88e60c00dd9697b61fdd2a8343a9b680eaf" + +through2@^0.6.3: + version "0.6.5" + resolved "https://registry.yarnpkg.com/through2/-/through2-0.6.5.tgz#41ab9c67b29d57209071410e1d7a7a968cd3ad48" + dependencies: + readable-stream ">=1.0.33-1 <1.1.0-0" + xtend ">=4.0.0 <4.1.0-0" + +through2@~0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/through2/-/through2-0.2.3.tgz#eb3284da4ea311b6cc8ace3653748a52abf25a3f" + dependencies: + readable-stream "~1.1.9" + xtend "~2.1.1" + +tildify@~1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/tildify/-/tildify-1.2.0.tgz#dcec03f55dca9b7aa3e5b04f21817eb56e63588a" + dependencies: + os-homedir "^1.0.0" + +to-fast-properties@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.2.tgz#f3f5c0c3ba7299a7ef99427e44633257ade43320" + +tough-cookie@~2.3.0: + version "2.3.2" + resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.2.tgz#f081f76e4c85720e6c37a5faced737150d84072a" + dependencies: + punycode "^1.4.1" + +"traverse@>=0.3.0 <0.4": + version "0.3.9" + resolved "https://registry.yarnpkg.com/traverse/-/traverse-0.3.9.tgz#717b8f220cc0bb7b44e40514c22b2e8bbc70d8b9" + +trim-newlines@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613" + +tunnel-agent@~0.4.1: + version "0.4.3" + resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.4.3.tgz#6373db76909fe570e08d73583365ed828a74eeeb" + +tweetnacl@^0.14.3, tweetnacl@~0.14.0: + version "0.14.3" + resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.3.tgz#3da382f670f25ded78d7b3d1792119bca0b7132d" + +type-check@~0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" + dependencies: + prelude-ls "~1.1.2" + +uglify-js@^2.6: + version "2.7.5" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.7.5.tgz#4612c0c7baaee2ba7c487de4904ae122079f2ca8" + dependencies: + async "~0.2.6" + source-map "~0.5.1" + uglify-to-browserify "~1.0.0" + yargs "~3.10.0" + +uglify-js@~2.3: + version "2.3.6" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.3.6.tgz#fa0984770b428b7a9b2a8058f46355d14fef211a" + dependencies: + async "~0.2.6" + optimist "~0.3.5" + source-map "~0.1.7" + +uglify-to-browserify@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" + +underscore-contrib@~0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/underscore-contrib/-/underscore-contrib-0.3.0.tgz#665b66c24783f8fa2b18c9f8cbb0e2c7d48c26c7" + dependencies: + underscore "1.6.0" + +underscore@~1.6.0, underscore@1.6.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.6.0.tgz#8b38b10cacdef63337b8b24e4ff86d45aea529a8" + +untildify@~2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/untildify/-/untildify-2.1.0.tgz#17eb2807987f76952e9c0485fc311d06a826a2e0" + dependencies: + os-homedir "^1.0.0" + +unzip@^0.1.11: + version "0.1.11" + resolved "https://registry.yarnpkg.com/unzip/-/unzip-0.1.11.tgz#89749c63b058d7d90d619f86b98aa1535d3b97f0" + dependencies: + binary ">= 0.3.0 < 1" + fstream ">= 0.1.30 < 1" + match-stream ">= 0.0.2 < 1" + pullstream ">= 0.4.1 < 1" + readable-stream "~1.0.31" + setimmediate ">= 1.0.1 < 2" + +util-deprecate@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + +uuid@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.0.1.tgz#6544bba2dfda8c1cf17e629a3a305e2bb1fee6c1" + +validate-npm-package-license@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz#2804babe712ad3379459acfbe24746ab2c303fbc" + dependencies: + spdx-correct "~1.0.0" + spdx-expression-parse "~1.0.0" + +verror@1.3.6: + version "1.3.6" + resolved "https://registry.yarnpkg.com/verror/-/verror-1.3.6.tgz#cff5df12946d297d2baaefaa2689e25be01c005c" + dependencies: + extsprintf "1.0.2" + +which@^1.1.1, which@^1.2.4, which@^1.2.9: + version "1.2.12" + resolved "https://registry.yarnpkg.com/which/-/which-1.2.12.tgz#de67b5e450269f194909ef23ece4ebe416fa1192" + dependencies: + isexe "^1.1.1" + +window-size@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.4.tgz#f8e1aa1ee5a53ec5bf151ffa09742a6ad7697876" + +window-size@0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" + +wordwrap@^1.0.0, wordwrap@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" + +wordwrap@~0.0.2: + version "0.0.3" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" + +wordwrap@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" + +wrap-ansi@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85" + dependencies: + string-width "^1.0.1" + strip-ansi "^3.0.1" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + +wrench@~1.3.9: + version "1.3.9" + resolved "https://registry.yarnpkg.com/wrench/-/wrench-1.3.9.tgz#6f13ec35145317eb292ca5f6531391b244111411" + +write-file-atomic@^1.1.4: + version "1.2.0" + resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-1.2.0.tgz#14c66d4e4cb3ca0565c28cf3b7a6f3e4d5938fab" + dependencies: + graceful-fs "^4.1.2" + imurmurhash "^0.1.4" + slide "^1.1.5" + +xtend@^4.0.0, "xtend@>=4.0.0 <4.1.0-0": + version "4.0.1" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af" + +xtend@~2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-2.1.2.tgz#6efecc2a4dad8e6962c4901b337ce7ba87b5d28b" + dependencies: + object-keys "~0.4.0" + +y18n@^3.2.0: + version "3.2.1" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41" + +yallist@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.0.0.tgz#306c543835f09ee1a4cb23b7bce9ab341c91cdd4" + +yargs@^3.15.0: + version "3.32.0" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.32.0.tgz#03088e9ebf9e756b69751611d2a5ef591482c995" + dependencies: + camelcase "^2.0.1" + cliui "^3.0.3" + decamelize "^1.1.1" + os-locale "^1.4.0" + string-width "^1.0.1" + window-size "^0.1.4" + y18n "^3.2.0" + +yargs@~3.10.0: + version "3.10.0" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" + dependencies: + camelcase "^1.0.2" + cliui "^2.1.0" + decamelize "^1.0.0" + window-size "0.1.0" + diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/.npmignore b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/.npmignore new file mode 100644 index 00000000..265ff739 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/.npmignore @@ -0,0 +1,8 @@ +build/ +test/ +examples/ +fs.js +zlib.js +.zuul.yml +.nyc_output +coverage diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/.travis.yml b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/.travis.yml new file mode 100644 index 00000000..84504c98 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/.travis.yml @@ -0,0 +1,49 @@ +sudo: false +language: node_js +before_install: + - npm install -g npm@2 + - npm install -g npm +notifications: + email: false +matrix: + fast_finish: true + include: + - node_js: '0.8' + env: TASK=test + - node_js: '0.10' + env: TASK=test + - node_js: '0.11' + env: TASK=test + - node_js: '0.12' + env: TASK=test + - node_js: 1 + env: TASK=test + - node_js: 2 + env: TASK=test + - node_js: 3 + env: TASK=test + - node_js: 4 + env: TASK=test + - node_js: 5 + env: TASK=test + - node_js: 6 + env: TASK=test + - node_js: 5 + env: TASK=browser BROWSER_NAME=android BROWSER_VERSION="4.0..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=ie BROWSER_VERSION="9..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=opera BROWSER_VERSION="11..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=chrome BROWSER_VERSION="-3..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=firefox BROWSER_VERSION="-3..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=safari BROWSER_VERSION="5..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=microsoftedge BROWSER_VERSION=latest +script: "npm run $TASK" +env: + global: + - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc= + - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI= diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/LICENSE new file mode 100644 index 00000000..e3d4e695 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/README.md new file mode 100644 index 00000000..9fb4feaa --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/README.md @@ -0,0 +1,36 @@ +# readable-stream + +***Node-core v6.3.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) + +```bash +npm install --save readable-stream +``` + +***Node-core streams for userland*** + +This package is a mirror of the Streams2 and Streams3 implementations in +Node-core, including [documentation](doc/stream.md). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +# Streams WG Team Members + +* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) <christopher.s.dickinson@gmail.com> + - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org> + - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D +* **Sam Newman** ([@sonewman](https://github.com/sonewman)) <newmansam@outlook.com> +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me> diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/doc/stream.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/doc/stream.md new file mode 100644 index 00000000..fc269c8e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/doc/stream.md @@ -0,0 +1,2015 @@ +# Stream + + Stability: 2 - Stable + +A stream is an abstract interface for working with streaming data in Node.js. +The `stream` module provides a base API that makes it easy to build objects +that implement the stream interface. + +There are many stream objects provided by Node.js. For instance, a +[request to an HTTP server][http-incoming-message] and [`process.stdout`][] +are both stream instances. + +Streams can be readable, writable, or both. All streams are instances of +[`EventEmitter`][]. + +The `stream` module can be accessed using: + +```js +const stream = require('stream'); +``` + +While it is important for all Node.js users to understand how streams works, +the `stream` module itself is most useful for developer's that are creating new +types of stream instances. Developer's who are primarily *consuming* stream +objects will rarely (if ever) have need to use the `stream` module directly. + +## Organization of this document + +This document is divided into two primary sections and third section for +additional notes. The first section explains the elements of the stream API that +are required to *use* streams within an application. The second section explains +the elements of the API that are required to *implement* new types of streams. + +## Types of Streams + +There are four fundamental stream types within Node.js: + +* [Readable][] - streams from which data can be read (for example + [`fs.createReadStream()`][]). +* [Writable][] - streams to which data can be written (for example + [`fs.createWriteStream()`][]). +* [Duplex][] - streams that are both Readable and Writable (for example + [`net.Socket`][]). +* [Transform][] - Duplex streams that can modify or transform the data as it + is written and read (for example [`zlib.createDeflate()`][]). + +### Object Mode + +All streams created by Node.js APIs operate exclusively on strings and `Buffer` +objects. It is possible, however, for stream implementations to work with other +types of JavaScript values (with the exception of `null` which serves a special +purpose within streams). Such streams are considered to operate in "object +mode". + +Stream instances are switched into object mode using the `objectMode` option +when the stream is created. Attempting to switch an existing stream into +object mode is not safe. + +### Buffering + +<!--type=misc--> + +Both [Writable][] and [Readable][] streams will store data in an internal +buffer that can be retrieved using `writable._writableState.getBuffer()` or +`readable._readableState.buffer`, respectively. + +The amount of data potentially buffered depends on the `highWaterMark` option +passed into the streams constructor. For normal streams, the `highWaterMark` +option specifies a total number of bytes. For streams operating in object mode, +the `highWaterMark` specifies a total number of objects. + +Data is buffered in Readable streams when the implementation calls +[`stream.push(chunk)`][stream-push]. If the consumer of the Stream does not +call [`stream.read()`][stream-read], the data will sit in the internal +queue until it is consumed. + +Once the total size of the internal read buffer reaches the threshold specified +by `highWaterMark`, the stream will temporarily stop reading data from the +underlying resource until the data currently buffered can be consumed (that is, +the stream will stop calling the internal `readable._read()` method that is +used to fill the read buffer). + +Data is buffered in Writable streams when the +[`writable.write(chunk)`][stream-write] method is called repeatedly. While the +total size of the internal write buffer is below the threshold set by +`highWaterMark`, calls to `writable.write()` will return `true`. Once the +the size of the internal buffer reaches or exceeds the `highWaterMark`, `false` +will be returned. + +A key goal of the `stream` API, and in particular the [`stream.pipe()`] method, +is to limit the buffering of data to acceptable levels such that sources and +destinations of differing speeds will not overwhelm the available memory. + +Because [Duplex][] and [Transform][] streams are both Readable and Writable, +each maintain *two* separate internal buffers used for reading and writing, +allowing each side to operate independently of the other while maintaining an +appropriate and efficient flow of data. For example, [`net.Socket`][] instances +are [Duplex][] streams whose Readable side allows consumption of data received +*from* the socket and whose Writable side allows writing data *to* the socket. +Because data may be written to the socket at a faster or slower rate than data +is received, it is important each side operate (and buffer) independently of +the other. + +## API for Stream Consumers + +<!--type=misc--> + +Almost all Node.js applications, no matter how simple, use streams in some +manner. The following is an example of using streams in a Node.js application +that implements an HTTP server: + +```js +const http = require('http'); + +const server = http.createServer( (req, res) => { + // req is an http.IncomingMessage, which is a Readable Stream + // res is an http.ServerResponse, which is a Writable Stream + + let body = ''; + // Get the data as utf8 strings. + // If an encoding is not set, Buffer objects will be received. + req.setEncoding('utf8'); + + // Readable streams emit 'data' events once a listener is added + req.on('data', (chunk) => { + body += chunk; + }); + + // the end event indicates that the entire body has been received + req.on('end', () => { + try { + const data = JSON.parse(body); + } catch (er) { + // uh oh! bad json! + res.statusCode = 400; + return res.end(`error: ${er.message}`); + } + + // write back something interesting to the user: + res.write(typeof data); + res.end(); + }); +}); + +server.listen(1337); + +// $ curl localhost:1337 -d '{}' +// object +// $ curl localhost:1337 -d '"foo"' +// string +// $ curl localhost:1337 -d 'not json' +// error: Unexpected token o +``` + +[Writable][] streams (such as `res` in the example) expose methods such as +`write()` and `end()` that are used to write data onto the stream. + +[Readable][] streams use the [`EventEmitter`][] API for notifying application +code when data is available to be read off the stream. That available data can +be read from the stream in multiple ways. + +Both [Writable][] and [Readable][] streams use the [`EventEmitter`][] API in +various ways to communicate the current state of the stream. + +[Duplex][] and [Transform][] streams are both [Writable][] and [Readable][]. + +Applications that are either writing data to or consuming data from a stream +are not required to implement the stream interfaces directly and will generally +have no reason to call `require('stream')`. + +Developers wishing to implement new types of streams should refer to the +section [API for Stream Implementers][]. + +### Writable Streams + +Writable streams are an abstraction for a *destination* to which data is +written. + +Examples of [Writable][] streams include: + +* [HTTP requests, on the client][] +* [HTTP responses, on the server][] +* [fs write streams][] +* [zlib streams][zlib] +* [crypto streams][crypto] +* [TCP sockets][] +* [child process stdin][] +* [`process.stdout`][], [`process.stderr`][] + +*Note*: Some of these examples are actually [Duplex][] streams that implement +the [Writable][] interface. + +All [Writable][] streams implement the interface defined by the +`stream.Writable` class. + +While specific instances of [Writable][] streams may differ in various ways, +all Writable streams follow the same fundamental usage pattern as illustrated +in the example below: + +```js +const myStream = getWritableStreamSomehow(); +myStream.write('some data'); +myStream.write('some more data'); +myStream.end('done writing data'); +``` + +#### Class: stream.Writable +<!-- YAML +added: v0.9.4 +--> + +<!--type=class--> + +##### Event: 'close' +<!-- YAML +added: v0.9.4 +--> + +The `'close'` event is emitted when the stream and any of its underlying +resources (a file descriptor, for example) have been closed. The event indicates +that no more events will be emitted, and no further computation will occur. + +Not all Writable streams will emit the `'close'` event. + +##### Event: 'drain' +<!-- YAML +added: v0.9.4 +--> + +If a call to [`stream.write(chunk)`][stream-write] returns `false`, the +`'drain'` event will be emitted when it is appropriate to resume writing data +to the stream. + +```js +// Write the data to the supplied writable stream one million times. +// Be attentive to back-pressure. +function writeOneMillionTimes(writer, data, encoding, callback) { + let i = 1000000; + write(); + function write() { + var ok = true; + do { + i--; + if (i === 0) { + // last time! + writer.write(data, encoding, callback); + } else { + // see if we should continue, or wait + // don't pass the callback, because we're not done yet. + ok = writer.write(data, encoding); + } + } while (i > 0 && ok); + if (i > 0) { + // had to stop early! + // write some more once it drains + writer.once('drain', write); + } + } +} +``` + +##### Event: 'error' +<!-- YAML +added: v0.9.4 +--> + +* {Error} + +The `'error'` event is emitted if an error occurred while writing or piping +data. The listener callback is passed a single `Error` argument when called. + +*Note*: The stream is not closed when the `'error'` event is emitted. + +##### Event: 'finish' +<!-- YAML +added: v0.9.4 +--> + +The `'finish'` event is emitted after the [`stream.end()`][stream-end] method +has been called, and all data has been flushed to the underlying system. + +```js +const writer = getWritableStreamSomehow(); +for (var i = 0; i < 100; i ++) { + writer.write('hello, #${i}!\n'); +} +writer.end('This is the end\n'); +writer.on('finish', () => { + console.error('All writes are now complete.'); +}); +``` + +##### Event: 'pipe' +<!-- YAML +added: v0.9.4 +--> + +* `src` {stream.Readable} source stream that is piping to this writable + +The `'pipe'` event is emitted when the [`stream.pipe()`][] method is called on +a readable stream, adding this writable to its set of destinations. + +```js +const writer = getWritableStreamSomehow(); +const reader = getReadableStreamSomehow(); +writer.on('pipe', (src) => { + console.error('something is piping into the writer'); + assert.equal(src, reader); +}); +reader.pipe(writer); +``` + +##### Event: 'unpipe' +<!-- YAML +added: v0.9.4 +--> + +* `src` {[Readable][] Stream} The source stream that + [unpiped][`stream.unpipe()`] this writable + +The `'unpipe'` event is emitted when the [`stream.unpipe()`][] method is called +on a [Readable][] stream, removing this [Writable][] from its set of +destinations. + +```js +const writer = getWritableStreamSomehow(); +const reader = getReadableStreamSomehow(); +writer.on('unpipe', (src) => { + console.error('Something has stopped piping into the writer.'); + assert.equal(src, reader); +}); +reader.pipe(writer); +reader.unpipe(writer); +``` + +##### writable.cork() +<!-- YAML +added: v0.11.2 +--> + +The `writable.cork()` method forces all written data to be buffered in memory. +The buffered data will be flushed when either the [`stream.uncork()`][] or +[`stream.end()`][stream-end] methods are called. + +The primary intent of `writable.cork()` is to avoid a situation where writing +many small chunks of data to a stream do not cause an backup in the internal +buffer that would have an adverse impact on performance. In such situations, +implementations that implement the `writable._writev()` method can perform +buffered writes in a more optimized manner. + +##### writable.end([chunk][, encoding][, callback]) +<!-- YAML +added: v0.9.4 +--> + +* `chunk` {String|Buffer|any} Optional data to write. For streams not operating + in object mode, `chunk` must be a string or a `Buffer`. For object mode + streams, `chunk` may be any JavaScript value other than `null`. +* `encoding` {String} The encoding, if `chunk` is a String +* `callback` {Function} Optional callback for when the stream is finished + +Calling the `writable.end()` method signals that no more data will be written +to the [Writable][]. The optional `chunk` and `encoding` arguments allow one +final additional chunk of data to be written immediately before closing the +stream. If provided, the optional `callback` function is attached as a listener +for the [`'finish'`][] event. + +Calling the [`stream.write()`][stream-write] method after calling +[`stream.end()`][stream-end] will raise an error. + +```js +// write 'hello, ' and then end with 'world!' +const file = fs.createWriteStream('example.txt'); +file.write('hello, '); +file.end('world!'); +// writing more now is not allowed! +``` + +##### writable.setDefaultEncoding(encoding) +<!-- YAML +added: v0.11.15 +--> + +* `encoding` {String} The new default encoding +* Return: `this` + +The `writable.setDefaultEncoding()` method sets the default `encoding` for a +[Writable][] stream. + +##### writable.uncork() +<!-- YAML +added: v0.11.2 +--> + +The `writable.uncork()` method flushes all data buffered since +[`stream.cork()`][] was called. + +When using `writable.cork()` and `writable.uncork()` to manage the buffering +of writes to a stream, it is recommended that calls to `writable.uncork()` be +deferred using `process.nextTick()`. Doing so allows batching of all +`writable.write()` calls that occur within a given Node.js event loop phase. + +```js +stream.cork(); +stream.write('some '); +stream.write('data '); +process.nextTick(() => stream.uncork()); +``` + +If the `writable.cork()` method is called multiple times on a stream, the same +number of calls to `writable.uncork()` must be called to flush the buffered +data. + +``` +stream.cork(); +stream.write('some '); +stream.cork(); +stream.write('data '); +process.nextTick(() => { + stream.uncork(); + // The data will not be flushed until uncork() is called a second time. + stream.uncork(); +}); +``` + +##### writable.write(chunk[, encoding][, callback]) +<!-- YAML +added: v0.9.4 +--> + +* `chunk` {String|Buffer} The data to write +* `encoding` {String} The encoding, if `chunk` is a String +* `callback` {Function} Callback for when this chunk of data is flushed +* Returns: {Boolean} `false` if the stream wishes for the calling code to + wait for the `'drain'` event to be emitted before continuing to write + additional data; otherwise `true`. + +The `writable.write()` method writes some data to the stream, and calls the +supplied `callback` once the data has been fully handled. If an error +occurs, the `callback` *may or may not* be called with the error as its +first argument. To reliably detect write errors, add a listener for the +`'error'` event. + +The return value indicates whether the written `chunk` was buffered internally +and the buffer has exceeded the `highWaterMark` configured when the stream was +created. If `false` is returned, further attempts to write data to the stream +should be paused until the `'drain'` event is emitted. + +A Writable stream in object mode will always ignore the `encoding` argument. + +### Readable Streams + +Readable streams are an abstraction for a *source* from which data is +consumed. + +Examples of Readable streams include: + +* [HTTP responses, on the client][http-incoming-message] +* [HTTP requests, on the server][http-incoming-message] +* [fs read streams][] +* [zlib streams][zlib] +* [crypto streams][crypto] +* [TCP sockets][] +* [child process stdout and stderr][] +* [`process.stdin`][] + +All [Readable][] streams implement the interface defined by the +`stream.Readable` class. + +#### Two Modes + +Readable streams effectively operate in one of two modes: flowing and paused. + +When in flowing mode, data is read from the underlying system automatically +and provided to an application as quickly as possible using events via the +[`EventEmitter`][] interface. + +In paused mode, the [`stream.read()`][stream-read] method must be called +explicitly to read chunks of data from the stream. + +All [Readable][] streams begin in paused mode but can be switched to flowing +mode in one of the following ways: + +* Adding a [`'data'`][] event handler. +* Calling the [`stream.resume()`][stream-resume] method. +* Calling the [`stream.pipe()`][] method to send the data to a [Writable][]. + +The Readable can switch back to paused mode using one of the following: + +* If there are no pipe destinations, by calling the + [`stream.pause()`][stream-pause] method. +* If there are pipe destinations, by removing any [`'data'`][] event + handlers, and removing all pipe destinations by calling the + [`stream.unpipe()`][] method. + +The important concept to remember is that a Readable will not generate data +until a mechanism for either consuming or ignoring that data is provided. If +the consuming mechanism is disabled or taken away, the Readable will *attempt* +to stop generating the data. + +*Note*: For backwards compatibility reasons, removing [`'data'`][] event +handlers will **not** automatically pause the stream. Also, if there are piped +destinations, then calling [`stream.pause()`][stream-pause] will not guarantee +that the stream will *remain* paused once those destinations drain and ask for +more data. + +*Note*: If a [Readable][] is switched into flowing mode and there are no +consumers available handle the data, that data will be lost. This can occur, +for instance, when the `readable.resume()` method is called without a listener +attached to the `'data'` event, or when a `'data'` event handler is removed +from the stream. + +#### Three States + +The "two modes" of operation for a Readable stream are a simplified abstraction +for the more complicated internal state management that is happening within the +Readable stream implementation. + +Specifically, at any given point in time, every Readable is in one of three +possible states: + +* `readable._readableState.flowing = null` +* `readable._readableState.flowing = false` +* `readable._readableState.flowing = true` + +When `readable._readableState.flowing` is `null`, no mechanism for consuming the +streams data is provided so the stream will not generate its data. + +Attaching a listener for the `'data'` event, calling the `readable.pipe()` +method, or calling the `readable.resume()` method will switch +`readable._readableState.flowing` to `true`, causing the Readable to begin +actively emitting events as data is generated. + +Calling `readable.pause()`, `readable.unpipe()`, or receiving "back pressure" +will cause the `readable._readableState.flowing` to be set as `false`, +temporarily halting the flowing of events but *not* halting the generation of +data. + +While `readable._readableState.flowing` is `false`, data may be accumulating +within the streams internal buffer. + +#### Choose One + +The Readable stream API evolved across multiple Node.js versions and provides +multiple methods of consuming stream data. In general, developers should choose +*one* of the methods of consuming data and *should never* use multiple methods +to consume data from a single stream. + +Use of the `readable.pipe()` method is recommended for most users as it has been +implemented to provide the easiest way of consuming stream data. Developers that +require more fine-grained control over the transfer and generation of data can +use the [`EventEmitter`][] and `readable.pause()`/`readable.resume()` APIs. + +#### Class: stream.Readable +<!-- YAML +added: v0.9.4 +--> + +<!--type=class--> + +##### Event: 'close' +<!-- YAML +added: v0.9.4 +--> + +The `'close'` event is emitted when the stream and any of its underlying +resources (a file descriptor, for example) have been closed. The event indicates +that no more events will be emitted, and no further computation will occur. + +Not all [Readable][] streams will emit the `'close'` event. + +##### Event: 'data' +<!-- YAML +added: v0.9.4 +--> + +* `chunk` {Buffer|String|any} The chunk of data. For streams that are not + operating in object mode, the chunk will be either a string or `Buffer`. + For streams that are in object mode, the chunk can be any JavaScript value + other than `null`. + +The `'data'` event is emitted whenever the stream is relinquishing ownership of +a chunk of data to a consumer. This may occur whenever the stream is switched +in flowing mode by calling `readable.pipe()`, `readable.resume()`, or by +attaching a listener callback to the `'data'` event. The `'data'` event will +also be emitted whenever the `readable.read()` method is called and a chunk of +data is available to be returned. + +Attaching a `'data'` event listener to a stream that has not been explicitly +paused will switch the stream into flowing mode. Data will then be passed as +soon as it is available. + +The listener callback will be passed the chunk of data as a string if a default +encoding has been specified for the stream using the +`readable.setEncoding()` method; otherwise the data will be passed as a +`Buffer`. + +```js +const readable = getReadableStreamSomehow(); +readable.on('data', (chunk) => { + console.log(`Received ${chunk.length} bytes of data.`); +}); +``` + +##### Event: 'end' +<!-- YAML +added: v0.9.4 +--> + +The `'end'` event is emitted when there is no more data to be consumed from +the stream. + +*Note*: The `'end'` event **will not be emitted** unless the data is +completely consumed. This can be accomplished by switching the stream into +flowing mode, or by calling [`stream.read()`][stream-read] repeatedly until +all data has been consumed. + +```js +const readable = getReadableStreamSomehow(); +readable.on('data', (chunk) => { + console.log(`Received ${chunk.length} bytes of data.`); +}); +readable.on('end', () => { + console.log('There will be no more data.'); +}); +``` + +##### Event: 'error' +<!-- YAML +added: v0.9.4 +--> + +* {Error} + +The `'error'` event may be emitted by a Readable implementation at any time. +Typically, this may occur if the underlying stream in unable to generate data +due to an underlying internal failure, or when a stream implementation attempts +to push an invalid chunk of data. + +The listener callback will be passed a single `Error` object. + +##### Event: 'readable' +<!-- YAML +added: v0.9.4 +--> + +The `'readable'` event is emitted when there is data available to be read from +the stream. In some cases, attaching a listener for the `'readable'` event will +cause some amount of data to be read into an internal buffer. + +```javascript +const readable = getReadableStreamSomehow(); +readable.on('readable', () => { + // there is some data to read now +}); +``` +The `'readable'` event will also be emitted once the end of the stream data +has been reached but before the `'end'` event is emitted. + +Effectively, the `'readable'` event indicates that the stream has new +information: either new data is available or the end of the stream has been +reached. In the former case, [`stream.read()`][stream-read] will return the +available data. In the latter case, [`stream.read()`][stream-read] will return +`null`. For instance, in the following example, `foo.txt` is an empty file: + +```js +const fs = require('fs'); +const rr = fs.createReadStream('foo.txt'); +rr.on('readable', () => { + console.log('readable:', rr.read()); +}); +rr.on('end', () => { + console.log('end'); +}); +``` + +The output of running this script is: + +``` +$ node test.js +readable: null +end +``` + +*Note*: In general, the `readable.pipe()` and `'data'` event mechanisms are +preferred over the use of the `'readable'` event. + +##### readable.isPaused() +<!-- +added: v0.11.14 +--> + +* Return: {Boolean} + +The `readable.isPaused()` method returns the current operating state of the +Readable. This is used primarily by the mechanism that underlies the +`readable.pipe()` method. In most typical cases, there will be no reason to +use this method directly. + +```js +const readable = new stream.Readable + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +##### readable.pause() +<!-- YAML +added: v0.9.4 +--> + +* Return: `this` + +The `readable.pause()` method will cause a stream in flowing mode to stop +emitting [`'data'`][] events, switching out of flowing mode. Any data that +becomes available will remain in the internal buffer. + +```js +const readable = getReadableStreamSomehow(); +readable.on('data', (chunk) => { + console.log(`Received ${chunk.length} bytes of data.`); + readable.pause(); + console.log('There will be no additional data for 1 second.'); + setTimeout(() => { + console.log('Now data will start flowing again.'); + readable.resume(); + }, 1000); +}); +``` + +##### readable.pipe(destination[, options]) +<!-- YAML +added: v0.9.4 +--> + +* `destination` {stream.Writable} The destination for writing data +* `options` {Object} Pipe options + * `end` {Boolean} End the writer when the reader ends. Defaults to `true`. + +The `readable.pipe()` method attaches a [Writable][] stream to the `readable`, +causing it to switch automatically into flowing mode and push all of its data +to the attached [Writable][]. The flow of data will be automatically managed so +that the destination Writable stream is not overwhelmed by a faster Readable +stream. + +The following example pipes all of the data from the `readable` into a file +named `file.txt`: + +```js +const readable = getReadableStreamSomehow(); +const writable = fs.createWriteStream('file.txt'); +// All the data from readable goes into 'file.txt' +readable.pipe(writable); +``` +It is possible to attach multiple Writable streams to a single Readable stream. + +The `readable.pipe()` method returns a reference to the *destination* stream +making it possible to set up chains of piped streams: + +```js +const r = fs.createReadStream('file.txt'); +const z = zlib.createGzip(); +const w = fs.createWriteStream('file.txt.gz'); +r.pipe(z).pipe(w); +``` + +By default, [`stream.end()`][stream-end] is called on the destination Writable +stream when the source Readable stream emits [`'end'`][], so that the +destination is no longer writable. To disable this default behavior, the `end` +option can be passed as `false`, causing the destination stream to remain open, +as illustrated in the following example: + +```js +reader.pipe(writer, { end: false }); +reader.on('end', () => { + writer.end('Goodbye\n'); +}); +``` + +One important caveat is that if the Readable stream emits an error during +processing, the Writable destination *is not closed* automatically. If an +error occurs, it will be necessary to *manually* close each stream in order +to prevent memory leaks. + +*Note*: The [`process.stderr`][] and [`process.stdout`][] Writable streams are +never closed until the Node.js process exits, regardless of the specified +options. + +##### readable.read([size]) +<!-- YAML +added: v0.9.4 +--> + +* `size` {Number} Optional argument to specify how much data to read. +* Return {String|Buffer|Null} + +The `readable.read()` method pulls some data out of the internal buffer and +returns it. If no data available to be read, `null` is returned. By default, +the data will be returned as a `Buffer` object unless an encoding has been +specified using the `readable.setEncoding()` method or the stream is operating +in object mode. + +The optional `size` argument specifies a specific number of bytes to read. If +`size` bytes are not available to be read, `null` will be returned *unless* +the stream has ended, in which case all of the data remaining in the internal +buffer will be returned (*even if it exceeds `size` bytes*). + +If the `size` argument is not specified, all of the data contained in the +internal buffer will be returned. + +The `readable.read()` method should only be called on Readable streams operating +in paused mode. In flowing mode, `readable.read()` is called automatically until +the internal buffer is fully drained. + +```js +const readable = getReadableStreamSomehow(); +readable.on('readable', () => { + var chunk; + while (null !== (chunk = readable.read())) { + console.log(`Received ${chunk.length} bytes of data.`); + } +}); +``` + +In general, it is recommended that developers avoid the use of the `'readable'` +event and the `readable.read()` method in favor of using either +`readable.pipe()` or the `'data'` event. + +A Readable stream in object mode will always return a single item from +a call to [`readable.read(size)`][stream-read], regardless of the value of the +`size` argument. + +*Note:* If the `readable.read()` method returns a chunk of data, a `'data'` +event will also be emitted. + +*Note*: Calling [`stream.read([size])`][stream-read] after the [`'end'`][] +event has been emitted will return `null`. No runtime error will be raised. + +##### readable.resume() +<!-- YAML +added: v0.9.4 +--> + +* Return: `this` + +The `readable.resume()` method causes an explicitly paused Readable stream to +resume emitting [`'data'`][] events, switching the stream into flowing mode. + +The `readable.resume()` method can be used to fully consume the data from a +stream without actually processing any of that data as illustrated in the +following example: + +```js +getReadableStreamSomehow() + .resume() + .on('end', () => { + console.log('Reached the end, but did not read anything.'); + }); +``` + +##### readable.setEncoding(encoding) +<!-- YAML +added: v0.9.4 +--> + +* `encoding` {String} The encoding to use. +* Return: `this` + +The `readable.setEncoding()` method sets the default character encoding for +data read from the Readable stream. + +Setting an encoding causes the stream data +to be returned as string of the specified encoding rather than as `Buffer` +objects. For instance, calling `readable.setEncoding('utf8')` will cause the +output data will be interpreted as UTF-8 data, and passed as strings. Calling +`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal +string format. + +The Readable stream will properly handle multi-byte characters delivered through +the stream that would otherwise become improperly decoded if simply pulled from +the stream as `Buffer` objects. + +Encoding can be disabled by calling `readable.setEncoding(null)`. This approach +is useful when working with binary data or with large multi-byte strings spread +out over multiple chunks. + +```js +const readable = getReadableStreamSomehow(); +readable.setEncoding('utf8'); +readable.on('data', (chunk) => { + assert.equal(typeof chunk, 'string'); + console.log('got %d characters of string data', chunk.length); +}); +``` + +##### readable.unpipe([destination]) +<!-- YAML +added: v0.9.4 +--> + +* `destination` {stream.Writable} Optional specific stream to unpipe + +The `readable.unpipe()` method detaches a Writable stream previously attached +using the [`stream.pipe()`][] method. + +If the `destination` is not specified, then *all* pipes are detached. + +If the `destination` is specified, but no pipe is set up for it, then +the method does nothing. + +```js +const readable = getReadableStreamSomehow(); +const writable = fs.createWriteStream('file.txt'); +// All the data from readable goes into 'file.txt', +// but only for the first second +readable.pipe(writable); +setTimeout(() => { + console.log('Stop writing to file.txt'); + readable.unpipe(writable); + console.log('Manually close the file stream'); + writable.end(); +}, 1000); +``` + +##### readable.unshift(chunk) +<!-- YAML +added: v0.9.11 +--> + +* `chunk` {Buffer|String} Chunk of data to unshift onto the read queue + +The `readable.unshift()` method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party. + +*Note*: The `stream.unshift(chunk)` method cannot be called after the +[`'end'`][] event has been emitted or a runtime error will be thrown. + +Developers using `stream.unshift()` often should consider switching to +use of a [Transform][] stream instead. See the [API for Stream Implementers][] +section for more information. + +```js +// Pull off a header delimited by \n\n +// use unshift() if we get too much +// Call the callback with (error, header, stream) +const StringDecoder = require('string_decoder').StringDecoder; +function parseHeader(stream, callback) { + stream.on('error', callback); + stream.on('readable', onReadable); + const decoder = new StringDecoder('utf8'); + var header = ''; + function onReadable() { + var chunk; + while (null !== (chunk = stream.read())) { + var str = decoder.write(chunk); + if (str.match(/\n\n/)) { + // found the header boundary + var split = str.split(/\n\n/); + header += split.shift(); + const remaining = split.join('\n\n'); + const buf = Buffer.from(remaining, 'utf8'); + if (buf.length) + stream.unshift(buf); + stream.removeListener('error', callback); + stream.removeListener('readable', onReadable); + // now the body of the message can be read from the stream. + callback(null, header, stream); + } else { + // still reading the header. + header += str; + } + } + } +} +``` + +*Note*: Unlike [`stream.push(chunk)`][stream-push], `stream.unshift(chunk)` +will not end the reading process by resetting the internal reading state of the +stream. This can cause unexpected results if `readable.unshift()` is called +during a read (i.e. from within a [`stream._read()`][stream-_read] +implementation on a custom stream). Following the call to `readable.unshift()` +with an immediate [`stream.push('')`][stream-push] will reset the reading state +appropriately, however it is best to simply avoid calling `readable.unshift()` +while in the process of performing a read. + +##### readable.wrap(stream) +<!-- YAML +added: v0.9.4 +--> + +* `stream` {Stream} An "old style" readable stream + +Versions of Node.js prior to v0.10 had streams that did not implement the +entire `stream` module API as it is currently defined. (See [Compatibility][] +for more information.) + +When using an older Node.js library that emits [`'data'`][] events and has a +[`stream.pause()`][stream-pause] method that is advisory only, the +`readable.wrap()` method can be used to create a [Readable][] stream that uses +the old stream as its data source. + +It will rarely be necessary to use `readable.wrap()` but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries. + +For example: + +```js +const OldReader = require('./old-api-module.js').OldReader; +const Readable = require('stream').Readable; +const oreader = new OldReader; +const myReader = new Readable().wrap(oreader); + +myReader.on('readable', () => { + myReader.read(); // etc. +}); +``` + +### Duplex and Transform Streams + +#### Class: stream.Duplex +<!-- YAML +added: v0.9.4 +--> + +<!--type=class--> + +Duplex streams are streams that implement both the [Readable][] and +[Writable][] interfaces. + +Examples of Duplex streams include: + +* [TCP sockets][] +* [zlib streams][zlib] +* [crypto streams][crypto] + +#### Class: stream.Transform +<!-- YAML +added: v0.9.4 +--> + +<!--type=class--> + +Transform streams are [Duplex][] streams where the output is in some way +related to the input. Like all [Duplex][] streams, Transform streams +implement both the [Readable][] and [Writable][] interfaces. + +Examples of Transform streams include: + +* [zlib streams][zlib] +* [crypto streams][crypto] + + +## API for Stream Implementers + +<!--type=misc--> + +The `stream` module API has been designed to make it possible to easily +implement streams using JavaScript's prototypical inheritance model. + +First, a stream developer would declare a new JavaScript class that extends one +of the four basic stream classes (`stream.Writable`, `stream.Readable`, +`stream.Duplex`, or `stream.Transform`), making sure the call the appropriate +parent class constructor: + +```js +const Writable = require('stream').Writable; + +class MyWritable extends Writable { + constructor(options) { + super(options); + } +} +``` + +The new stream class must then implement one or more specific methods, depending +on the type of stream being created, as detailed in the chart below: + +<table> + <thead> + <tr> + <th> + <p>Use-case</p> + </th> + <th> + <p>Class</p> + </th> + <th> + <p>Method(s) to implement</p> + </th> + </tr> + </thead> + <tr> + <td> + <p>Reading only</p> + </td> + <td> + <p>[Readable](#stream_class_stream_readable)</p> + </td> + <td> + <p><code>[_read][stream-_read]</code></p> + </td> + </tr> + <tr> + <td> + <p>Writing only</p> + </td> + <td> + <p>[Writable](#stream_class_stream_writable)</p> + </td> + <td> + <p><code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code></p> + </td> + </tr> + <tr> + <td> + <p>Reading and writing</p> + </td> + <td> + <p>[Duplex](#stream_class_stream_duplex)</p> + </td> + <td> + <p><code>[_read][stream-_read]</code>, <code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code></p> + </td> + </tr> + <tr> + <td> + <p>Operate on written data, then read the result</p> + </td> + <td> + <p>[Transform](#stream_class_stream_transform)</p> + </td> + <td> + <p><code>[_transform][stream-_transform]</code>, <code>[_flush][stream-_flush]</code></p> + </td> + </tr> +</table> + +*Note*: The implementation code for a stream should *never* call the "public" +methods of a stream that are intended for use by consumers (as described in +the [API for Stream Consumers][] section). Doing so may lead to adverse +side effects in application code consuming the stream. + +### Simplified Construction + +For many simple cases, it is possible to construct a stream without relying on +inheritance. This can be accomplished by directly creating instances of the +`stream.Writable`, `stream.Readable`, `stream.Duplex` or `stream.Transform` +objects and passing appropriate methods as constructor options. + +For example: + +```js +const Writable = require('stream').Writable; + +const myWritable = new Writable({ + write(chunk, encoding, callback) { + // ... + } +}); +``` + +### Implementing a Writable Stream + +The `stream.Writable` class is extended to implement a [Writable][] stream. + +Custom Writable streams *must* call the `new stream.Writable([options])` +constructor and implement the `writable._write()` method. The +`writable._writev()` method *may* also be implemented. + +#### Constructor: new stream.Writable([options]) + +* `options` {Object} + * `highWaterMark` {Number} Buffer level when + [`stream.write()`][stream-write] starts returning `false`. Defaults to + `16384` (16kb), or `16` for `objectMode` streams. + * `decodeStrings` {Boolean} Whether or not to decode strings into + Buffers before passing them to [`stream._write()`][stream-_write]. + Defaults to `true` + * `objectMode` {Boolean} Whether or not the + [`stream.write(anyObj)`][stream-write] is a valid operation. When set, + it becomes possible to write JavaScript values other than string or + `Buffer` if supported by the stream implementation. Defaults to `false` + * `write` {Function} Implementation for the + [`stream._write()`][stream-_write] method. + * `writev` {Function} Implementation for the + [`stream._writev()`][stream-_writev] method. + +For example: + +```js +const Writable = require('stream').Writable; + +class MyWritable extends Writable { + constructor(options) { + // Calls the stream.Writable() constructor + super(options); + } +} +``` + +Or, when using pre-ES6 style constructors: + +```js +const Writable = require('stream').Writable; +const util = require('util'); + +function MyWritable(options) { + if (!(this instanceof MyWritable)) + return new MyWritable(options); + Writable.call(this, options); +} +util.inherits(MyWritable, Writable); +``` + +Or, using the Simplified Constructor approach: + +```js +const Writable = require('stream').Writable; + +const myWritable = new Writable({ + write(chunk, encoding, callback) { + // ... + }, + writev(chunks, callback) { + // ... + } +}); +``` + +#### writable.\_write(chunk, encoding, callback) + +* `chunk` {Buffer|String} The chunk to be written. Will **always** + be a buffer unless the `decodeStrings` option was set to `false`. +* `encoding` {String} If the chunk is a string, then `encoding` is the + character encoding of that string. If chunk is a `Buffer`, or if the + stream is operating in object mode, `encoding` may be ignored. +* `callback` {Function} Call this function (optionally with an error + argument) when processing is complete for the supplied chunk. + +All Writable stream implementations must provide a +[`writable._write()`][stream-_write] method to send data to the underlying +resource. + +*Note*: [Transform][] streams provide their own implementation of the +[`writable._write()`][stream-_write]. + +*Note*: **This function MUST NOT be called by application code directly.** It +should be implemented by child classes, and called only by the internal Writable +class methods only. + +The `callback` method must be called to signal either that the write completed +successfully or failed with an error. The first argument passed to the +`callback` must be the `Error` object if the call failed or `null` if the +write succeeded. + +It is important to note that all calls to `writable.write()` that occur between +the time `writable._write()` is called and the `callback` is called will cause +the written data to be buffered. Once the `callback` is invoked, the stream will +emit a `'drain'` event. If a stream implementation is capable of processing +multiple chunks of data at once, the `writable._writev()` method should be +implemented. + +If the `decodeStrings` property is set in the constructor options, then +`chunk` may be a string rather than a Buffer, and `encoding` will +indicate the character encoding of the string. This is to support +implementations that have an optimized handling for certain string +data encodings. If the `decodeStrings` property is explicitly set to `false`, +the `encoding` argument can be safely ignored, and `chunk` will always be a +`Buffer`. + +The `writable._write()` method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs. + +#### writable.\_writev(chunks, callback) + +* `chunks` {Array} The chunks to be written. Each chunk has following + format: `{ chunk: ..., encoding: ... }`. +* `callback` {Function} A callback function (optionally with an error + argument) to be invoked when processing is complete for the supplied chunks. + +*Note*: **This function MUST NOT be called by application code directly.** It +should be implemented by child classes, and called only by the internal Writable +class methods only. + +The `writable._writev()` method may be implemented in addition to +`writable._write()` in stream implementations that are capable of processing +multiple chunks of data at once. If implemented, the method will be called with +all chunks of data currently buffered in the write queue. + +The `writable._writev()` method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs. + +#### Errors While Writing + +It is recommended that errors occurring during the processing of the +`writable._write()` and `writable._writev()` methods are reported by invoking +the callback and passing the error as the first argument. This will cause an +`'error'` event to be emitted by the Writable. Throwing an Error from within +`writable._write()` can result in expected and inconsistent behavior depending +on how the stream is being used. Using the callback ensures consistent and +predictable handling of errors. + +```js +const Writable = require('stream').Writable; + +const myWritable = new Writable({ + write(chunk, encoding, callback) { + if (chunk.toString().indexOf('a') >= 0) { + callback(new Error('chunk is invalid')); + } else { + callback(); + } + } +}); +``` + +#### An Example Writable Stream + +The following illustrates a rather simplistic (and somewhat pointless) custom +Writable stream implementation. While this specific Writable stream instance +is not of any real particular usefulness, the example illustrates each of the +required elements of a custom [Writable][] stream instance: + +```js +const Writable = require('stream').Writable; + +class MyWritable extends Writable { + constructor(options) { + super(options); + } + + _write(chunk, encoding, callback) { + if (chunk.toString().indexOf('a') >= 0) { + callback(new Error('chunk is invalid')); + } else { + callback(); + } + } +} +``` + +### Implementing a Readable Stream + +The `stream.Readable` class is extended to implement a [Readable][] stream. + +Custom Readable streams *must* call the `new stream.Readable([options])` +constructor and implement the `readable._read()` method. + +#### new stream.Readable([options]) + +* `options` {Object} + * `highWaterMark` {Number} The maximum number of bytes to store in + the internal buffer before ceasing to read from the underlying + resource. Defaults to `16384` (16kb), or `16` for `objectMode` streams + * `encoding` {String} If specified, then buffers will be decoded to + strings using the specified encoding. Defaults to `null` + * `objectMode` {Boolean} Whether this stream should behave + as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns + a single value instead of a Buffer of size n. Defaults to `false` + * `read` {Function} Implementation for the [`stream._read()`][stream-_read] + method. + +For example: + +```js +const Readable = require('stream').Readable; + +class MyReadable extends Readable { + constructor(options) { + // Calls the stream.Readable(options) constructor + super(options); + } +} +``` + +Or, when using pre-ES6 style constructors: + +```js +const Readable = require('stream').Readable; +const util = require('util'); + +function MyReadable(options) { + if (!(this instanceof MyReadable)) + return new MyReadable(options); + Readable.call(this, options); +} +util.inherits(MyReadable, Readable); +``` + +Or, using the Simplified Constructor approach: + +```js +const Readable = require('stream').Readable; + +const myReadable = new Readable({ + read(size) { + // ... + } +}); +``` + +#### readable.\_read(size) + +* `size` {Number} Number of bytes to read asynchronously + +*Note*: **This function MUST NOT be called by application code directly.** It +should be implemented by child classes, and called only by the internal Readable +class methods only. + +All Readable stream implementations must provide an implementation of the +`readable._read()` method to fetch data from the underlying resource. + +When `readable._read()` is called, if data is available from the resource, the +implementation should begin pushing that data into the read queue using the +[`this.push(dataChunk)`][stream-push] method. `_read()` should continue reading +from the resource and pushing data until `readable.push()` returns `false`. Only +when `_read()` is called again after it has stopped should it resume pushing +additional data onto the queue. + +*Note*: Once the `readable._read()` method has been called, it will not be +called again until the [`readable.push()`][stream-push] method is called. + +The `size` argument is advisory. For implementations where a "read" is a +single operation that returns data can use the `size` argument to determine how +much data to fetch. Other implementations may ignore this argument and simply +provide data whenever it becomes available. There is no need to "wait" until +`size` bytes are available before calling [`stream.push(chunk)`][stream-push]. + +The `readable._read()` method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs. + +#### readable.push(chunk[, encoding]) + +* `chunk` {Buffer|Null|String} Chunk of data to push into the read queue +* `encoding` {String} Encoding of String chunks. Must be a valid + Buffer encoding, such as `'utf8'` or `'ascii'` +* Returns {Boolean} `true` if additional chunks of data may continued to be + pushed; `false` otherwise. + +When `chunk` is a `Buffer` or `string`, the `chunk` of data will be added to the +internal queue for users of the stream to consume. Passing `chunk` as `null` +signals the end of the stream (EOF), after which no more data can be written. + +When the Readable is operating in paused mode, the data added with +`readable.push()` can be read out by calling the +[`readable.read()`][stream-read] method when the [`'readable'`][] event is +emitted. + +When the Readable is operating in flowing mode, the data added with +`readable.push()` will be delivered by emitting a `'data'` event. + +The `readable.push()` method is designed to be as flexible as possible. For +example, when wrapping a lower-level source that provides some form of +pause/resume mechanism, and a data callback, the low-level source can be wrapped +by the custom Readable instance as illustrated in the following example: + +```js +// source is an object with readStop() and readStart() methods, +// and an `ondata` member that gets called when it has data, and +// an `onend` member that gets called when the data is over. + +class SourceWrapper extends Readable { + constructor(options) { + super(options); + + this._source = getLowlevelSourceObject(); + + // Every time there's data, push it into the internal buffer. + this._source.ondata = (chunk) => { + // if push() returns false, then stop reading from source + if (!this.push(chunk)) + this._source.readStop(); + }; + + // When the source ends, push the EOF-signaling `null` chunk + this._source.onend = () => { + this.push(null); + }; + } + // _read will be called when the stream wants to pull more data in + // the advisory size argument is ignored in this case. + _read(size) { + this._source.readStart(); + } +} +``` +*Note*: The `readable.push()` method is intended be called only by Readable +Implementers, and only from within the `readable._read()` method. + +#### Errors While Reading + +It is recommended that errors occurring during the processing of the +`readable._read()` method are emitted using the `'error'` event rather than +being thrown. Throwing an Error from within `readable._read()` can result in +expected and inconsistent behavior depending on whether the stream is operating +in flowing or paused mode. Using the `'error'` event ensures consistent and +predictable handling of errors. + +```js +const Readable = require('stream').Readable; + +const myReadable = new Readable({ + read(size) { + if (checkSomeErrorCondition()) { + process.nextTick(() => this.emit('error', err)); + return; + } + // do some work + } +}); +``` + +#### An Example Counting Stream + +<!--type=example--> + +The following is a basic example of a Readable stream that emits the numerals +from 1 to 1,000,000 in ascending order, and then ends. + +```js +const Readable = require('stream').Readable; + +class Counter extends Readable { + constructor(opt) { + super(opt); + this._max = 1000000; + this._index = 1; + } + + _read() { + var i = this._index++; + if (i > this._max) + this.push(null); + else { + var str = '' + i; + var buf = Buffer.from(str, 'ascii'); + this.push(buf); + } + } +} +``` + +### Implementing a Duplex Stream + +A [Duplex][] stream is one that implements both [Readable][] and [Writable][], +such as a TCP socket connection. + +Because Javascript does not have support for multiple inheritance, the +`stream.Duplex` class is extended to implement a [Duplex][] stream (as opposed +to extending the `stream.Readable` *and* `stream.Writable` classes). + +*Note*: The `stream.Duplex` class prototypically inherits from `stream.Readable` +and parasitically from `stream.Writable`. + +Custom Duplex streams *must* call the `new stream.Duplex([options])` +constructor and implement *both* the `readable._read()` and +`writable._write()` methods. + +#### new stream.Duplex(options) + +* `options` {Object} Passed to both Writable and Readable + constructors. Also has the following fields: + * `allowHalfOpen` {Boolean} Defaults to `true`. If set to `false`, then + the stream will automatically end the readable side when the + writable side ends and vice versa. + * `readableObjectMode` {Boolean} Defaults to `false`. Sets `objectMode` + for readable side of the stream. Has no effect if `objectMode` + is `true`. + * `writableObjectMode` {Boolean} Defaults to `false`. Sets `objectMode` + for writable side of the stream. Has no effect if `objectMode` + is `true`. + +For example: + +```js +const Duplex = require('stream').Duplex; + +class MyDuplex extends Duplex { + constructor(options) { + super(options); + } +} +``` + +Or, when using pre-ES6 style constructors: + +```js +const Duplex = require('stream').Duplex; +const util = require('util'); + +function MyDuplex(options) { + if (!(this instanceof MyDuplex)) + return new MyDuplex(options); + Duplex.call(this, options); +} +util.inherits(MyDuplex, Duplex); +``` + +Or, using the Simplified Constructor approach: + +```js +const Duplex = require('stream').Duplex; + +const myDuplex = new Duplex({ + read(size) { + // ... + }, + write(chunk, encoding, callback) { + // ... + } +}); +``` + +#### An Example Duplex Stream + +The following illustrates a simple example of a Duplex stream that wraps a +hypothetical lower-level source object to which data can be written, and +from which data can be read, albeit using an API that is not compatible with +Node.js streams. +The following illustrates a simple example of a Duplex stream that buffers +incoming written data via the [Writable][] interface that is read back out +via the [Readable][] interface. + +```js +const Duplex = require('stream').Duplex; +const kSource = Symbol('source'); + +class MyDuplex extends Duplex { + constructor(source, options) { + super(options); + this[kSource] = source; + } + + _write(chunk, encoding, callback) { + // The underlying source only deals with strings + if (Buffer.isBuffer(chunk)) + chunk = chunk.toString(encoding); + this[kSource].writeSomeData(chunk, encoding); + callback(); + } + + _read(size) { + this[kSource].fetchSomeData(size, (data, encoding) => { + this.push(Buffer.from(data, encoding)); + }); + } +} +``` + +The most important aspect of a Duplex stream is that the Readable and Writable +sides operate independently of one another despite co-existing within a single +object instance. + +#### Object Mode Duplex Streams + +For Duplex streams, `objectMode` can be set exclusively for either the Readable +or Writable side using the `readableObjectMode` and `writableObjectMode` options +respectively. + +In the following example, for instance, a new Transform stream (which is a +type of [Duplex][] stream) is created that has an object mode Writable side +that accepts JavaScript numbers that are converted to hexidecimal strings on +the Readable side. + +```js +const Transform = require('stream').Transform; + +// All Transform streams are also Duplex Streams +const myTransform = new Transform({ + writableObjectMode: true, + + transform(chunk, encoding, callback) { + // Coerce the chunk to a number if necessary + chunk |= 0; + + // Transform the chunk into something else. + const data = chunk.toString(16); + + // Push the data onto the readable queue. + callback(null, '0'.repeat(data.length % 2) + data); + } +}); + +myTransform.setEncoding('ascii'); +myTransform.on('data', (chunk) => console.log(chunk)); + +myTransform.write(1); + // Prints: 01 +myTransform.write(10); + // Prints: 0a +myTransform.write(100); + // Prints: 64 +``` + +### Implementing a Transform Stream + +A [Transform][] stream is a [Duplex][] stream where the output is computed +in some way from the input. Examples include [zlib][] streams or [crypto][] +streams that compress, encrypt, or decrypt data. + +*Note*: There is no requirement that the output be the same size as the input, +the same number of chunks, or arrive at the same time. For example, a +Hash stream will only ever have a single chunk of output which is +provided when the input is ended. A `zlib` stream will produce output +that is either much smaller or much larger than its input. + +The `stream.Transform` class is extended to implement a [Transform][] stream. + +The `stream.Transform` class prototypically inherits from `stream.Duplex` and +implements its own versions of the `writable._write()` and `readable._read()` +methods. Custom Transform implementations *must* implement the +[`transform._transform()`][stream-_transform] method and *may* also implement +the [`transform._flush()`][stream-_flush] method. + +*Note*: Care must be taken when using Transform streams in that data written +to the stream can cause the Writable side of the stream to become paused if +the output on the Readable side is not consumed. + +#### new stream.Transform([options]) + +* `options` {Object} Passed to both Writable and Readable + constructors. Also has the following fields: + * `transform` {Function} Implementation for the + [`stream._transform()`][stream-_transform] method. + * `flush` {Function} Implementation for the [`stream._flush()`][stream-_flush] + method. + +For example: + +```js +const Transform = require('stream').Transform; + +class MyTransform extends Transform { + constructor(options) { + super(options); + } +} +``` + +Or, when using pre-ES6 style constructors: + +```js +const Transform = require('stream').Transform; +const util = require('util'); + +function MyTransform(options) { + if (!(this instanceof MyTransform)) + return new MyTransform(options); + Transform.call(this, options); +} +util.inherits(MyTransform, Transform); +``` + +Or, using the Simplified Constructor approach: + +```js +const Transform = require('stream').Transform; + +const myTransform = new Transform({ + transform(chunk, encoding, callback) { + // ... + } +}); +``` + +#### Events: 'finish' and 'end' + +The [`'finish'`][] and [`'end'`][] events are from the `stream.Writable` +and `stream.Readable` classes, respectively. The `'finish'` event is emitted +after [`stream.end()`][stream-end] is called and all chunks have been processed +by [`stream._transform()`][stream-_transform]. The `'end'` event is emitted +after all data has been output, which occurs after the callback in +[`transform._flush()`][stream-_flush] has been called. + +#### transform.\_flush(callback) + +* `callback` {Function} A callback function (optionally with an error + argument) to be called when remaining data has been flushed. + +*Note*: **This function MUST NOT be called by application code directly.** It +should be implemented by child classes, and called only by the internal Readable +class methods only. + +In some cases, a transform operation may need to emit an additional bit of +data at the end of the stream. For example, a `zlib` compression stream will +store an amount of internal state used to optimally compress the output. When +the stream ends, however, that additional data needs to be flushed so that the +compressed data will be complete. + +Custom [Transform][] implementations *may* implement the `transform._flush()` +method. This will be called when there is no more written data to be consumed, +but before the [`'end'`][] event is emitted signaling the end of the +[Readable][] stream. + +Within the `transform._flush()` implementation, the `readable.push()` method +may be called zero or more times, as appropriate. The `callback` function must +be called when the flush operation is complete. + +The `transform._flush()` method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs. + +#### transform.\_transform(chunk, encoding, callback) + +* `chunk` {Buffer|String} The chunk to be transformed. Will **always** + be a buffer unless the `decodeStrings` option was set to `false`. +* `encoding` {String} If the chunk is a string, then this is the + encoding type. If chunk is a buffer, then this is the special + value - 'buffer', ignore it in this case. +* `callback` {Function} A callback function (optionally with an error + argument and data) to be called after the supplied `chunk` has been + processed. + +*Note*: **This function MUST NOT be called by application code directly.** It +should be implemented by child classes, and called only by the internal Readable +class methods only. + +All Transform stream implementations must provide a `_transform()` +method to accept input and produce output. The `transform._transform()` +implementation handles the bytes being written, computes an output, then passes +that output off to the readable portion using the `readable.push()` method. + +The `transform.push()` method may be called zero or more times to generate +output from a single input chunk, depending on how much is to be output +as a result of the chunk. + +It is possible that no output is generated from any given chunk of input data. + +The `callback` function must be called only when the current chunk is completely +consumed. The first argument passed to the `callback` must be an `Error` object +if an error occurred while processing the input or `null` otherwise. If a second +argument is passed to the `callback`, it will be forwarded on to the +`readable.push()` method. In other words the following are equivalent: + +```js +transform.prototype._transform = function (data, encoding, callback) { + this.push(data); + callback(); +}; + +transform.prototype._transform = function (data, encoding, callback) { + callback(null, data); +}; +``` + +The `transform._transform()` method is prefixed with an underscore because it +is internal to the class that defines it, and should never be called directly by +user programs. + +#### Class: stream.PassThrough + +The `stream.PassThrough` class is a trivial implementation of a [Transform][] +stream that simply passes the input bytes across to the output. Its purpose is +primarily for examples and testing, but there are some use cases where +`stream.PassThrough` is useful as a building block for novel sorts of streams. + +## Additional Notes + +<!--type=misc--> + +### Compatibility with Older Node.js Versions + +<!--type=misc--> + +In versions of Node.js prior to v0.10, the Readable stream interface was +simpler, but also less powerful and less useful. + +* Rather than waiting for calls the [`stream.read()`][stream-read] method, + [`'data'`][] events would begin emitting immediately. Applications that + would need to perform some amount of work to decide how to handle data + were required to store read data into buffers so the data would not be lost. +* The [`stream.pause()`][stream-pause] method was advisory, rather than + guaranteed. This meant that it was still necessary to be prepared to receive + [`'data'`][] events *even when the stream was in a paused state*. + +In Node.js v0.10, the [Readable][] class was added. For backwards compatibility +with older Node.js programs, Readable streams switch into "flowing mode" when a +[`'data'`][] event handler is added, or when the +[`stream.resume()`][stream-resume] method is called. The effect is that, even +when not using the new [`stream.read()`][stream-read] method and +[`'readable'`][] event, it is no longer necessary to worry about losing +[`'data'`][] chunks. + +While most applications will continue to function normally, this introduces an +edge case in the following conditions: + +* No [`'data'`][] event listener is added. +* The [`stream.resume()`][stream-resume] method is never called. +* The stream is not piped to any writable destination. + +For example, consider the following code: + +```js +// WARNING! BROKEN! +net.createServer((socket) => { + + // we add an 'end' method, but never consume the data + socket.on('end', () => { + // It will never get here. + socket.end('The message was received but was not processed.\n'); + }); + +}).listen(1337); +``` + +In versions of Node.js prior to v0.10, the incoming message data would be +simply discarded. However, in Node.js v0.10 and beyond, the socket remains +paused forever. + +The workaround in this situation is to call the +[`stream.resume()`][stream-resume] method to begin the flow of data: + +```js +// Workaround +net.createServer((socket) => { + + socket.on('end', () => { + socket.end('The message was received but was not processed.\n'); + }); + + // start the flow of data, discarding it. + socket.resume(); + +}).listen(1337); +``` + +In addition to new Readable streams switching into flowing mode, +pre-v0.10 style streams can be wrapped in a Readable class using the +[`readable.wrap()`][`stream.wrap()`] method. + + +### `readable.read(0)` + +There are some cases where it is necessary to trigger a refresh of the +underlying readable stream mechanisms, without actually consuming any +data. In such cases, it is possible to call `readable.read(0)`, which will +always return `null`. + +If the internal read buffer is below the `highWaterMark`, and the +stream is not currently reading, then calling `stream.read(0)` will trigger +a low-level [`stream._read()`][stream-_read] call. + +While most applications will almost never need to do this, there are +situations within Node.js where this is done, particularly in the +Readable stream class internals. + +### `readable.push('')` + +Use of `readable.push('')` is not recommended. + +Pushing a zero-byte string or `Buffer` to a stream that is not in object mode +has an interesting side effect. Because it *is* a call to +[`readable.push()`][stream-push], the call will end the reading process. +However, because the argument is an empty string, no data is added to the +readable buffer so there is nothing for a user to consume. + +[`'data'`]: #stream_event_data +[`'drain'`]: #stream_event_drain +[`'end'`]: #stream_event_end +[`'finish'`]: #stream_event_finish +[`'readable'`]: #stream_event_readable +[`buf.toString(encoding)`]: https://nodejs.org/docs/v6.3.1/api/buffer.html#buffer_buf_tostring_encoding_start_end +[`EventEmitter`]: https://nodejs.org/docs/v6.3.1/api/events.html#events_class_eventemitter +[`process.stderr`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stderr +[`process.stdin`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stdin +[`process.stdout`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stdout +[`stream.cork()`]: #stream_writable_cork +[`stream.pipe()`]: #stream_readable_pipe_destination_options +[`stream.uncork()`]: #stream_writable_uncork +[`stream.unpipe()`]: #stream_readable_unpipe_destination +[`stream.wrap()`]: #stream_readable_wrap_stream +[`tls.CryptoStream`]: https://nodejs.org/docs/v6.3.1/api/tls.html#tls_class_cryptostream +[API for Stream Consumers]: #stream_api_for_stream_consumers +[API for Stream Implementers]: #stream_api_for_stream_implementers +[child process stdin]: https://nodejs.org/docs/v6.3.1/api/child_process.html#child_process_child_stdin +[child process stdout and stderr]: https://nodejs.org/docs/v6.3.1/api/child_process.html#child_process_child_stdout +[Compatibility]: #stream_compatibility_with_older_node_js_versions +[crypto]: crypto.html +[Duplex]: #stream_class_stream_duplex +[fs read streams]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_class_fs_readstream +[fs write streams]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_class_fs_writestream +[`fs.createReadStream()`]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_fs_createreadstream_path_options +[`fs.createWriteStream()`]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_fs_createwritestream_path_options +[`net.Socket`]: https://nodejs.org/docs/v6.3.1/api/net.html#net_class_net_socket +[`zlib.createDeflate()`]: https://nodejs.org/docs/v6.3.1/api/zlib.html#zlib_zlib_createdeflate_options +[HTTP requests, on the client]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_clientrequest +[HTTP responses, on the server]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_serverresponse +[http-incoming-message]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_incomingmessage +[Object mode]: #stream_object_mode +[Readable]: #stream_class_stream_readable +[SimpleProtocol v2]: #stream_example_simpleprotocol_parser_v2 +[stream-_flush]: #stream_transform_flush_callback +[stream-_read]: #stream_readable_read_size_1 +[stream-_transform]: #stream_transform_transform_chunk_encoding_callback +[stream-_write]: #stream_writable_write_chunk_encoding_callback_1 +[stream-_writev]: #stream_writable_writev_chunks_callback +[stream-end]: #stream_writable_end_chunk_encoding_callback +[stream-pause]: #stream_readable_pause +[stream-push]: #stream_readable_push_chunk_encoding +[stream-read]: #stream_readable_read_size +[stream-resume]: #stream_readable_resume +[stream-write]: #stream_writable_write_chunk_encoding_callback +[TCP sockets]: https://nodejs.org/docs/v6.3.1/api/net.html#net_class_net_socket +[Transform]: #stream_class_stream_transform +[Writable]: #stream_class_stream_writable +[zlib]: zlib.html diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md new file mode 100644 index 00000000..83275f19 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md @@ -0,0 +1,60 @@ +# streams WG Meeting 2015-01-30 + +## Links + +* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg +* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106 +* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/ + +## Agenda + +Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting. + +* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105) +* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101) +* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102) +* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99) + +## Minutes + +### adopt a charter + +* group: +1's all around + +### What versioning scheme should be adopted? +* group: +1’s 3.0.0 +* domenic+group: pulling in patches from other sources where appropriate +* mikeal: version independently, suggesting versions for io.js +* mikeal+domenic: work with TC to notify in advance of changes +simpler stream creation + +### streamline creation of streams +* sam: streamline creation of streams +* domenic: nice simple solution posted + but, we lose the opportunity to change the model + may not be backwards incompatible (double check keys) + + **action item:** domenic will check + +### remove implicit flowing of streams on(‘data’) +* add isFlowing / isPaused +* mikeal: worrying that we’re documenting polyfill methods – confuses users +* domenic: more reflective API is probably good, with warning labels for users +* new section for mad scientists (reflective stream access) +* calvin: name the “third state” +* mikeal: maybe borrow the name from whatwg? +* domenic: we’re missing the “third state” +* consensus: kind of difficult to name the third state +* mikeal: figure out differences in states / compat +* mathias: always flow on data – eliminates third state + * explore what it breaks + +**action items:** +* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream) +* ask rod/build for infrastructure +* **chris**: explore the “flow on data” approach +* add isPaused/isFlowing +* add new docs section +* move isPaused to that section + + diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/duplex.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/duplex.js new file mode 100644 index 00000000..ca807af8 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 00000000..736693b8 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,75 @@ +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/*<replacement>*/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/*</replacement>*/ + +module.exports = Duplex; + +/*<replacement>*/ +var processNextTick = require('process-nextick-args'); +/*</replacement>*/ + +/*<replacement>*/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/*</replacement>*/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +}
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 00000000..d06f71f1 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,26 @@ +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/*<replacement>*/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/*</replacement>*/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +};
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 00000000..208cc65f --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,937 @@ +'use strict'; + +module.exports = Readable; + +/*<replacement>*/ +var processNextTick = require('process-nextick-args'); +/*</replacement>*/ + +/*<replacement>*/ +var isArray = require('isarray'); +/*</replacement>*/ + +Readable.ReadableState = ReadableState; + +/*<replacement>*/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/*</replacement>*/ + +/*<replacement>*/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/*</replacement>*/ + +var Buffer = require('buffer').Buffer; +/*<replacement>*/ +var bufferShim = require('buffer-shims'); +/*</replacement>*/ + +/*<replacement>*/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/*</replacement>*/ + +/*<replacement>*/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/*</replacement>*/ + +var BufferList = require('./internal/streams/BufferList'); +var StringDecoder; + +util.inherits(Readable, Stream); + +function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } +} + +var Duplex; +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +var Duplex; +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = bufferShim.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = bufferShim.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +}
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 00000000..dbc996ed --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,180 @@ +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/*<replacement>*/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/*</replacement>*/ + +util.inherits(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +}
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 00000000..ed5efcbd --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,526 @@ +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/*<replacement>*/ +var processNextTick = require('process-nextick-args'); +/*</replacement>*/ + +/*<replacement>*/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/*</replacement>*/ + +Writable.WritableState = WritableState; + +/*<replacement>*/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/*</replacement>*/ + +/*<replacement>*/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/*</replacement>*/ + +/*<replacement>*/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/*</replacement>*/ + +var Buffer = require('buffer').Buffer; +/*<replacement>*/ +var bufferShim = require('buffer-shims'); +/*</replacement>*/ + +util.inherits(Writable, Stream); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +var Duplex; +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + } catch (_) {} +})(); + +var Duplex; +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = bufferShim.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /*<replacement>*/ + asyncWrite(afterWrite, stream, state, finished, cb); + /*</replacement>*/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +}
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/internal/streams/BufferList.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/internal/streams/BufferList.js new file mode 100644 index 00000000..e4bfcf02 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/lib/internal/streams/BufferList.js @@ -0,0 +1,64 @@ +'use strict'; + +var Buffer = require('buffer').Buffer; +/*<replacement>*/ +var bufferShim = require('buffer-shims'); +/*</replacement>*/ + +module.exports = BufferList; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return bufferShim.alloc(0); + if (this.length === 1) return this.head.data; + var ret = bufferShim.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +};
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/index.js new file mode 100644 index 00000000..1cab4c05 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/index.js @@ -0,0 +1,108 @@ +'use strict'; + +var buffer = require('buffer'); +var Buffer = buffer.Buffer; +var SlowBuffer = buffer.SlowBuffer; +var MAX_LEN = buffer.kMaxLength || 2147483647; +exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === 'function') { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === 'number') { + throw new TypeError('encoding must not be number'); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === 'string') { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; +} +exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === 'function') { + return Buffer.allocUnsafe(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + return new Buffer(size); +} +exports.from = function from(value, encodingOrOffset, length) { + if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === 'string') { + return new Buffer(value, encodingOrOffset); + } + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === 'undefined') { + offset = 0; + } + var len = length; + if (typeof len === 'undefined') { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError('\'offset\' is out of bounds'); + } + if (len > value.byteLength - offset) { + throw new RangeError('\'length\' is out of bounds'); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { + return new Buffer(value); + } + if (value.type === 'Buffer' && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } + + throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); +} +exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === 'function') { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size >= MAX_LEN) { + throw new RangeError('size is too large'); + } + return new SlowBuffer(size); +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/license.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/license.md new file mode 100644 index 00000000..01cfaefe --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/license.md @@ -0,0 +1,19 @@ +# Copyright (c) 2016 Calvin Metcalf + +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.** diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/package.json new file mode 100644 index 00000000..fe079c96 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/package.json @@ -0,0 +1,51 @@ +{ + "name": "buffer-shims", + "version": "1.0.0", + "description": "some shims for node buffers", + "main": "index.js", + "scripts": { + "test": "tape test/*.js" + }, + "files": [ + "index.js" + ], + "license": "MIT", + "devDependencies": { + "tape": "^4.5.1" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/calvinmetcalf/buffer-shims.git" + }, + "gitHead": "ea89b3857ab5b8203957922a84e9a48cf4c47e0a", + "bugs": { + "url": "https://github.com/calvinmetcalf/buffer-shims/issues" + }, + "_id": "buffer-shims@1.0.0", + "_shasum": "9978ce317388c649ad8793028c3477ef044a8b51", + "_from": "buffer-shims@>=1.0.0 <2.0.0", + "_npmVersion": "3.8.6", + "_nodeVersion": "5.11.0", + "_npmUser": { + "name": "cwmma", + "email": "calvin.metcalf@gmail.com" + }, + "dist": { + "shasum": "9978ce317388c649ad8793028c3477ef044a8b51", + "tarball": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz" + }, + "maintainers": [ + { + "name": "cwmma", + "email": "calvin.metcalf@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-16-east.internal.npmjs.com", + "tmp": "tmp/buffer-shims-1.0.0.tgz_1462560889323_0.8640750856138766" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/calvinmetcalf/buffer-shims#readme" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/readme.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/readme.md new file mode 100644 index 00000000..7ea6475e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/buffer-shims/readme.md @@ -0,0 +1,21 @@ +buffer-shims +=== + +functions to make sure the new buffer methods work in older browsers. + +```js +var bufferShim = require('buffer-shims'); +bufferShim.from('foo'); +bufferShim.alloc(9, 'cafeface', 'hex'); +bufferShim.allocUnsafe(15); +bufferShim.allocUnsafeSlow(21); +``` + +should just use the original in newer nodes and on older nodes uses fallbacks. + +Known Issues +=== +- this does not patch the buffer object, only the constructor stuff +- it's actually a polyfill + +![](https://i.imgur.com/zxII3jJ.gif) diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE new file mode 100644 index 00000000..d8d7f943 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 00000000..5a76b414 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 00000000..a06d5c05 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++}
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 00000000..ff4c851c --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 00000000..19fb8592 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,60 @@ +{ + "name": "core-util-is", + "version": "1.0.2", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "scripts": { + "test": "tap test.js" + }, + "devDependencies": { + "tap": "^2.3.0" + }, + "gitHead": "a177da234df5638b363ddc15fa324619a38577c8", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "_id": "core-util-is@1.0.2", + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "_from": "core-util-is@>=1.0.0 <1.1.0", + "_npmVersion": "3.3.2", + "_nodeVersion": "4.0.0", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "dist": { + "shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "tarball": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js new file mode 100644 index 00000000..1a490c65 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js @@ -0,0 +1,68 @@ +var assert = require('tap'); + +var t = require('./lib/util'); + +assert.equal(t.isArray([]), true); +assert.equal(t.isArray({}), false); + +assert.equal(t.isBoolean(null), false); +assert.equal(t.isBoolean(true), true); +assert.equal(t.isBoolean(false), true); + +assert.equal(t.isNull(null), true); +assert.equal(t.isNull(undefined), false); +assert.equal(t.isNull(false), false); +assert.equal(t.isNull(), false); + +assert.equal(t.isNullOrUndefined(null), true); +assert.equal(t.isNullOrUndefined(undefined), true); +assert.equal(t.isNullOrUndefined(false), false); +assert.equal(t.isNullOrUndefined(), true); + +assert.equal(t.isNumber(null), false); +assert.equal(t.isNumber('1'), false); +assert.equal(t.isNumber(1), true); + +assert.equal(t.isString(null), false); +assert.equal(t.isString('1'), true); +assert.equal(t.isString(1), false); + +assert.equal(t.isSymbol(null), false); +assert.equal(t.isSymbol('1'), false); +assert.equal(t.isSymbol(1), false); +assert.equal(t.isSymbol(Symbol()), true); + +assert.equal(t.isUndefined(null), false); +assert.equal(t.isUndefined(undefined), true); +assert.equal(t.isUndefined(false), false); +assert.equal(t.isUndefined(), true); + +assert.equal(t.isRegExp(null), false); +assert.equal(t.isRegExp('1'), false); +assert.equal(t.isRegExp(new RegExp()), true); + +assert.equal(t.isObject({}), true); +assert.equal(t.isObject([]), true); +assert.equal(t.isObject(new RegExp()), true); +assert.equal(t.isObject(new Date()), true); + +assert.equal(t.isDate(null), false); +assert.equal(t.isDate('1'), false); +assert.equal(t.isDate(new Date()), true); + +assert.equal(t.isError(null), false); +assert.equal(t.isError({ err: true }), false); +assert.equal(t.isError(new Error()), true); + +assert.equal(t.isFunction(null), false); +assert.equal(t.isFunction({ }), false); +assert.equal(t.isFunction(function() {}), true); + +assert.equal(t.isPrimitive(null), true); +assert.equal(t.isPrimitive(''), true); +assert.equal(t.isPrimitive(0), true); +assert.equal(t.isPrimitive(new Date()), false); + +assert.equal(t.isBuffer(null), false); +assert.equal(t.isBuffer({}), false); +assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 00000000..dea3013d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 00000000..b1c56658 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 00000000..3b94763a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1,7 @@ +try { + var util = require('util'); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = require('./inherits_browser.js'); +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 00000000..c1e78a75 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 00000000..9146e757 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,63 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.3", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "devDependencies": { + "tap": "^7.1.0" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ], + "gitHead": "e05d0fb27c61a3ec687214f0476386b765364d5f", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.3", + "_shasum": "633c2c83e3da42a502f52466022480f4208261de", + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "3.10.7", + "_nodeVersion": "6.5.0", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "dist": { + "shasum": "633c2c83e3da42a502f52466022480f4208261de", + "tarball": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "_npmOperationalInternal": { + "host": "packages-16-east.internal.npmjs.com", + "tmp": "tmp/inherits-2.0.3.tgz_1473295776489_0.08142363070510328" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/.npmignore b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/.npmignore new file mode 100644 index 00000000..3c3629e6 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/.travis.yml b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/.travis.yml new file mode 100644 index 00000000..cc4dba29 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/Makefile b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/Makefile new file mode 100644 index 00000000..787d56e1 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test.js + +.PHONY: test + diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 00000000..16d2c59c --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,60 @@ + +# isarray + +`Array#isArray` for older browsers. + +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) + +[![browser support](https://ci.testling.com/juliangruber/isarray.png) +](https://ci.testling.com/juliangruber/isarray) + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +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. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 00000000..9e31b683 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 00000000..a57f6349 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,5 @@ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 00000000..e86d232e --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,71 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.4" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "scripts": { + "test": "tape test.js" + }, + "gitHead": "2a23a281f369e9ae06394c0fb4d2381355a6ba33", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "_id": "isarray@1.0.0", + "_shasum": "bb935d48582cba168c06834957a54a3e07124f11", + "_from": "isarray@>=1.0.0 <1.1.0", + "_npmVersion": "3.3.12", + "_nodeVersion": "5.1.0", + "_npmUser": { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + "dist": { + "shasum": "bb935d48582cba168c06834957a54a3e07124f11", + "tarball": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz" + }, + "maintainers": [ + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/test.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/test.js new file mode 100644 index 00000000..e0c3444d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/test.js @@ -0,0 +1,20 @@ +var isArray = require('./'); +var test = require('tape'); + +test('is array', function(t){ + t.ok(isArray([])); + t.notOk(isArray({})); + t.notOk(isArray(null)); + t.notOk(isArray(false)); + + var obj = {}; + obj[0] = true; + t.notOk(isArray(obj)); + + var arr = []; + arr.foo = 'bar'; + t.ok(isArray(arr)); + + t.end(); +}); + diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/.travis.yml b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/.travis.yml new file mode 100644 index 00000000..36201b10 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/.travis.yml @@ -0,0 +1,12 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" + - "0.12" + - "1.7.1" + - 1 + - 2 + - 3 + - 4 + - 5 diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/index.js new file mode 100644 index 00000000..a4f40f84 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/index.js @@ -0,0 +1,43 @@ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/license.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/license.md new file mode 100644 index 00000000..c67e3532 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/license.md @@ -0,0 +1,19 @@ +# Copyright (c) 2015 Calvin Metcalf + +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.** diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/package.json new file mode 100644 index 00000000..211b098d --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/package.json @@ -0,0 +1,49 @@ +{ + "name": "process-nextick-args", + "version": "1.0.7", + "description": "process.nextTick but always with args", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/calvinmetcalf/process-nextick-args.git" + }, + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/calvinmetcalf/process-nextick-args/issues" + }, + "homepage": "https://github.com/calvinmetcalf/process-nextick-args", + "devDependencies": { + "tap": "~0.2.6" + }, + "gitHead": "5c00899ab01dd32f93ad4b5743da33da91404f39", + "_id": "process-nextick-args@1.0.7", + "_shasum": "150e20b756590ad3f91093f25a4f2ad8bff30ba3", + "_from": "process-nextick-args@>=1.0.6 <1.1.0", + "_npmVersion": "3.8.6", + "_nodeVersion": "5.11.0", + "_npmUser": { + "name": "cwmma", + "email": "calvin.metcalf@gmail.com" + }, + "dist": { + "shasum": "150e20b756590ad3f91093f25a4f2ad8bff30ba3", + "tarball": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz" + }, + "maintainers": [ + { + "name": "cwmma", + "email": "calvin.metcalf@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/process-nextick-args-1.0.7.tgz_1462394251778_0.36989671061746776" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/readme.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/readme.md new file mode 100644 index 00000000..78e7cfae --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/readme.md @@ -0,0 +1,18 @@ +process-nextick-args +===== + +[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args) + +```bash +npm install --save process-nextick-args +``` + +Always be able to pass arguments to process.nextTick, no matter the platform + +```js +var nextTick = require('process-nextick-args'); + +nextTick(function (a, b, c) { + console.log(a, b, c); +}, 'step', 3, 'profit'); +``` diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/test.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/test.js new file mode 100644 index 00000000..ef157215 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/process-nextick-args/test.js @@ -0,0 +1,24 @@ +var test = require("tap").test; +var nextTick = require('./'); + +test('should work', function (t) { + t.plan(5); + nextTick(function (a) { + t.ok(a); + nextTick(function (thing) { + t.equals(thing, 7); + }, 7); + }, true); + nextTick(function (a, b, c) { + t.equals(a, 'step'); + t.equals(b, 3); + t.equals(c, 'profit'); + }, 'step', 3, 'profit'); +}); + +test('correct number of arguments', function (t) { + t.plan(1); + nextTick(function () { + t.equals(2, arguments.length, 'correct number'); + }, 1, 2); +}); diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 00000000..206320cc --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 00000000..6de584a4 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 00000000..4d2aa001 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version.
\ No newline at end of file diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 00000000..b00e54fb --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 00000000..8e8b77db --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,54 @@ +{ + "name": "string_decoder", + "version": "0.10.31", + "description": "The string_decoder module from Node core", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "gitHead": "d46d4fd87cf1d06e031c23f1ba170ca7d4ade9a0", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_from": "string_decoder@>=0.10.0 <0.11.0", + "_npmVersion": "1.4.23", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "tarball": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/History.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/History.md new file mode 100644 index 00000000..acc86753 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/LICENSE b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/LICENSE new file mode 100644 index 00000000..6a60e8c2 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net> + +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. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/README.md b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/README.md new file mode 100644 index 00000000..75622fa7 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net> + +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. diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/browser.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/browser.js new file mode 100644 index 00000000..549ae2f0 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/node.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/node.js new file mode 100644 index 00000000..5e6fcff5 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/package.json new file mode 100644 index 00000000..a0181354 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/node_modules/util-deprecate/package.json @@ -0,0 +1,54 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate", + "gitHead": "475fb6857cd23fafff20c1be846c1350abf8e6d4", + "_id": "util-deprecate@1.0.2", + "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf", + "_from": "util-deprecate@>=1.0.1 <1.1.0", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf", + "tarball": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/package.json new file mode 100644 index 00000000..89875483 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/package.json @@ -0,0 +1,92 @@ +{ + "name": "readable-stream", + "version": "2.1.5", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "dependencies": { + "buffer-shims": "^1.0.0", + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~0.10.x", + "util-deprecate": "~1.0.1" + }, + "devDependencies": { + "assert": "~1.4.0", + "babel-polyfill": "^6.9.1", + "nyc": "^6.4.0", + "tap": "~0.7.1", + "tape": "~4.5.1", + "zuul": "~3.10.0" + }, + "scripts": { + "test": "tap test/parallel/*.js test/ours/*.js", + "browser": "npm run write-zuul && zuul --browser-retries 2 -- test/browser.js", + "write-zuul": "printf \"ui: tape\nbrowsers:\n - name: $BROWSER_NAME\n version: $BROWSER_VERSION\n\">.zuul.yml", + "local": "zuul --local 3000 --no-coverage -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT", + "gitHead": "758c8b3845af855fde736b6a7f58a15fba00d1e7", + "bugs": { + "url": "https://github.com/nodejs/readable-stream/issues" + }, + "_id": "readable-stream@2.1.5", + "_shasum": "66fa8b720e1438b364681f2ad1a63c618448c9d0", + "_from": "readable-stream@2.1.5", + "_npmVersion": "3.8.6", + "_nodeVersion": "5.12.0", + "_npmUser": { + "name": "cwmma", + "email": "calvin.metcalf@gmail.com" + }, + "dist": { + "shasum": "66fa8b720e1438b364681f2ad1a63c618448c9d0", + "tarball": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.1.5.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + }, + { + "name": "cwmma", + "email": "calvin.metcalf@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-16-east.internal.npmjs.com", + "tmp": "tmp/readable-stream-2.1.5.tgz_1471463532993_0.15824943827465177" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.1.5.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/nodejs/readable-stream#readme" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/passthrough.js new file mode 100644 index 00000000..27e8d8a5 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/readable.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/readable.js new file mode 100644 index 00000000..be2688a0 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = (function (){ + try { + return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify + } catch(_){} +}()); +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream || exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/transform.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/transform.js new file mode 100644 index 00000000..5d482f07 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/writable.js b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/writable.js new file mode 100644 index 00000000..e1e9efdf --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/package.json b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/package.json new file mode 100644 index 00000000..0531da6a --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/package.json @@ -0,0 +1,92 @@ +{ + "name": "mongodb", + "version": "2.2.16", + "description": "The official MongoDB driver for Node.js", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "official" + ], + "dependencies": { + "es6-promise": "3.2.1", + "mongodb-core": "2.1.2", + "readable-stream": "2.1.5" + }, + "devDependencies": { + "JSONStream": "^1.0.7", + "betterbenchmarks": "^0.1.0", + "bluebird": "3.4.6", + "bson": "1.0.0", + "cli-table": "^0.3.1", + "co": "4.6.0", + "colors": "^1.1.2", + "coveralls": "^2.11.6", + "eslint": "^3.8.1", + "event-stream": "^3.3.2", + "gleak": "0.5.0", + "integra": "0.1.8", + "jsdoc": "3.4.0", + "ldjson-stream": "^1.2.1", + "mongodb-extended-json": "1.7.1", + "mongodb-topology-manager": "1.0.x", + "mongodb-version-manager": "github:christkv/mongodb-version-manager#master", + "nyc": "^8.1.0", + "optimist": "0.6.1", + "rimraf": "2.5.4", + "semver": "5.3.0", + "worker-farm": "^1.3.1" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.3" + }, + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "scripts": { + "test": "node test/runner.js -t functional -l", + "coverage": "nyc node test/runner.js -t functional && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls", + "lint": "eslint lib" + }, + "nyc": { + "include": [ + "lib/**/*.js" + ] + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "gitHead": "28da548dc2a1729a23e07418134dea88bf1e1c68", + "_id": "mongodb@2.2.16", + "_shasum": "e32ba91cf9e29f371fb38ba0c4a71c3b1f5fae77", + "_from": "mongodb@latest", + "_npmVersion": "3.10.8", + "_nodeVersion": "6.9.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "dist": { + "shasum": "e32ba91cf9e29f371fb38ba0c4a71c3b1f5fae77", + "tarball": "https://registry.npmjs.org/mongodb/-/mongodb-2.2.16.tgz" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/mongodb-2.2.16.tgz_1481656381868_0.36485050874762237" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.2.16.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/yarn.lock b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/yarn.lock new file mode 100644 index 00000000..d9f5a708 --- /dev/null +++ b/common/src/main/webapp/usageguide/appserver/node_modules/mongodb/yarn.lock @@ -0,0 +1,3184 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 +acorn-jsx@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-3.0.1.tgz#afdf9488fb1ecefc8348f6fb22f464e32a58b36b" + dependencies: + acorn "^3.0.4" + +acorn@^3.0.4: + version "3.3.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-3.3.0.tgz#45e37fb39e8da3f25baee3ff5369e2bb5f22017a" + +acorn@^4.0.1: + version "4.0.3" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-4.0.3.tgz#1a3e850b428e73ba6b09d1cc527f5aaad4d03ef1" + +ajv-keywords@^1.0.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-1.1.1.tgz#02550bc605a3e576041565628af972e06c549d50" + +ajv@^4.7.0: + version "4.9.0" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-4.9.0.tgz#5a358085747b134eb567d6d15e015f1d7802f45c" + dependencies: + co "^4.6.0" + json-stable-stringify "^1.0.1" + +align-text@^0.1.1, align-text@^0.1.3: + version "0.1.4" + resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" + dependencies: + kind-of "^3.0.2" + longest "^1.0.1" + repeat-string "^1.5.2" + +amdefine@>=0.0.4: + version "1.0.1" + resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" + +ampersand-events@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/ampersand-events/-/ampersand-events-2.0.2.tgz#f402bc2e18305fabd995dbdcd3b7057bbdd7d347" + dependencies: + ampersand-version "^1.0.2" + lodash "^4.6.1" + +ampersand-state@^5.0.1: + version "5.0.2" + resolved "https://registry.yarnpkg.com/ampersand-state/-/ampersand-state-5.0.2.tgz#16830def866c644ecd21da8c8ba8717aa2b8d23c" + dependencies: + ampersand-events "^2.0.1" + ampersand-version "^1.0.0" + array-next "~0.0.1" + key-tree-store "^1.3.0" + lodash "^4.11.1" + +ampersand-version@^1.0.0, ampersand-version@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/ampersand-version/-/ampersand-version-1.0.2.tgz#ff8f3d4ceac4d32ccd83f6bd6697397f7b59e2c0" + dependencies: + find-root "^0.1.1" + through2 "^0.6.3" + +ansi-escapes@^1.1.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-1.4.0.tgz#d3a8a83b319aa67793662b13e761c7911422306e" + +ansi-regex@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.0.0.tgz#c5061b6e0ef8a81775e50f5d66151bf6bf371107" + +ansi-styles@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" + +ansi@^0.3.0, ansi@~0.3.0: + version "0.3.1" + resolved "https://registry.yarnpkg.com/ansi/-/ansi-0.3.1.tgz#0c42d4fb17160d5a9af1e484bace1c66922c1b21" + +append-transform@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/append-transform/-/append-transform-0.3.0.tgz#d6933ce4a85f09445d9ccc4cc119051b7381a813" + +archy@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz#f9c8c13757cc1dd7bc379ac77b2c62a5c2868c40" + +are-we-there-yet@~1.0.0: + version "1.0.6" + resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.0.6.tgz#a2d28c93102aa6cc96245a26cb954de06ec53f0c" + dependencies: + delegates "^1.0.0" + readable-stream "^2.0.0 || ^1.1.13" + +argparse@^1.0.7: + version "1.0.9" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.9.tgz#73d83bc263f86e97f8cc4f6bae1b0e90a7d22c86" + dependencies: + sprintf-js "~1.0.2" + +arr-diff@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-2.0.0.tgz#8f3b827f955a8bd669697e4a4256ac3ceae356cf" + dependencies: + arr-flatten "^1.0.1" + +arr-flatten@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.0.1.tgz#e5ffe54d45e19f32f216e91eb99c8ce892bb604b" + +array-find-index@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/array-find-index/-/array-find-index-1.0.2.tgz#df010aa1287e164bbda6f9723b0a96a1ec4187a1" + +array-next@~0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/array-next/-/array-next-0.0.1.tgz#e5e4660a4c27fda8151ff7764275d00900062be1" + +array-union@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" + dependencies: + array-uniq "^1.0.1" + +array-uniq@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" + +array-unique@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53" + +arrify@^1.0.0, arrify@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" + +asn1@~0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86" + +assert-plus@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-0.2.0.tgz#d74e1b87e7affc0db8aadb7021f3fe48101ab234" + +assert-plus@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" + +async@^1.4.0, async@^1.4.2, async@^1.5.0, async@~1.5.0: + version "1.5.2" + resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" + +async@~0.2.6: + version "0.2.10" + resolved "https://registry.yarnpkg.com/async/-/async-0.2.10.tgz#b6bbe0b0674b9d719708ca38de8c237cb526c3d1" + +async@~1.4.0: + version "1.4.2" + resolved "https://registry.yarnpkg.com/async/-/async-1.4.2.tgz#6c9edcb11ced4f0dd2f2d40db0d49a109c088aab" + +asynckit@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" + +aws-sign2@~0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.6.0.tgz#14342dd38dbcc94d0e5b87d763cd63612c0e794f" + +aws4@^1.2.1: + version "1.5.0" + resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.5.0.tgz#0a29ffb79c31c9e712eeb087e8e7a64b4a56d755" + +babel-code-frame@^6.16.0: + version "6.16.0" + resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.16.0.tgz#f90e60da0862909d3ce098733b5d3987c97cb8de" + dependencies: + chalk "^1.1.0" + esutils "^2.0.2" + js-tokens "^2.0.0" + +babel-core@^6.10.4, babel-core@^6.18.0, babel-core@^6.2.1: + version "6.18.2" + resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.18.2.tgz#d8bb14dd6986fa4f3566a26ceda3964fa0e04e5b" + dependencies: + babel-code-frame "^6.16.0" + babel-generator "^6.18.0" + babel-helpers "^6.16.0" + babel-messages "^6.8.0" + babel-register "^6.18.0" + babel-runtime "^6.9.1" + babel-template "^6.16.0" + babel-traverse "^6.18.0" + babel-types "^6.18.0" + babylon "^6.11.0" + convert-source-map "^1.1.0" + debug "^2.1.1" + json5 "^0.5.0" + lodash "^4.2.0" + minimatch "^3.0.2" + path-is-absolute "^1.0.0" + private "^0.1.6" + slash "^1.0.0" + source-map "^0.5.0" + +babel-generator@^6.18.0: + version "6.19.0" + resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.19.0.tgz#9b2f244204777a3d6810ec127c673c87b349fac5" + dependencies: + babel-messages "^6.8.0" + babel-runtime "^6.9.0" + babel-types "^6.19.0" + detect-indent "^4.0.0" + jsesc "^1.3.0" + lodash "^4.2.0" + source-map "^0.5.0" + +babel-helpers@^6.16.0: + version "6.16.0" + resolved "https://registry.yarnpkg.com/babel-helpers/-/babel-helpers-6.16.0.tgz#1095ec10d99279460553e67eb3eee9973d3867e3" + dependencies: + babel-runtime "^6.0.0" + babel-template "^6.16.0" + +babel-messages@^6.8.0: + version "6.8.0" + resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.8.0.tgz#bf504736ca967e6d65ef0adb5a2a5f947c8e0eb9" + dependencies: + babel-runtime "^6.0.0" + +babel-polyfill@^6.2.0, babel-polyfill@^6.9.1: + version "6.16.0" + resolved "https://registry.yarnpkg.com/babel-polyfill/-/babel-polyfill-6.16.0.tgz#2d45021df87e26a374b6d4d1a9c65964d17f2422" + dependencies: + babel-runtime "^6.9.1" + core-js "^2.4.0" + regenerator-runtime "^0.9.5" + +babel-register@^6.18.0: + version "6.18.0" + resolved "https://registry.yarnpkg.com/babel-register/-/babel-register-6.18.0.tgz#892e2e03865078dd90ad2c715111ec4449b32a68" + dependencies: + babel-core "^6.18.0" + babel-runtime "^6.11.6" + core-js "^2.4.0" + home-or-tmp "^2.0.0" + lodash "^4.2.0" + mkdirp "^0.5.1" + source-map-support "^0.4.2" + +babel-runtime@^6.0.0, babel-runtime@^6.11.6, babel-runtime@^6.9.0, babel-runtime@^6.9.1: + version "6.18.0" + resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.18.0.tgz#0f4177ffd98492ef13b9f823e9994a02584c9078" + dependencies: + core-js "^2.4.0" + regenerator-runtime "^0.9.5" + +babel-template@^6.16.0: + version "6.16.0" + resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.16.0.tgz#e149dd1a9f03a35f817ddbc4d0481988e7ebc8ca" + dependencies: + babel-runtime "^6.9.0" + babel-traverse "^6.16.0" + babel-types "^6.16.0" + babylon "^6.11.0" + lodash "^4.2.0" + +babel-traverse@^6.16.0, babel-traverse@^6.18.0: + version "6.19.0" + resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.19.0.tgz#68363fb821e26247d52a519a84b2ceab8df4f55a" + dependencies: + babel-code-frame "^6.16.0" + babel-messages "^6.8.0" + babel-runtime "^6.9.0" + babel-types "^6.19.0" + babylon "^6.11.0" + debug "^2.2.0" + globals "^9.0.0" + invariant "^2.2.0" + lodash "^4.2.0" + +babel-types@^6.16.0, babel-types@^6.18.0, babel-types@^6.19.0: + version "6.19.0" + resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.19.0.tgz#8db2972dbed01f1192a8b602ba1e1e4c516240b9" + dependencies: + babel-runtime "^6.9.1" + esutils "^2.0.2" + lodash "^4.2.0" + to-fast-properties "^1.0.1" + +babylon@^6.11.0, babylon@^6.13.0: + version "6.14.1" + resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.14.1.tgz#956275fab72753ad9b3435d7afe58f8bf0a29815" + +balanced-match@^0.4.1: + version "0.4.2" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-0.4.2.tgz#cb3f3e3c732dc0f01ee70b403f302e61d7709838" + +bcrypt-pbkdf@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.0.tgz#3ca76b85241c7170bf7d9703e7b9aa74630040d4" + dependencies: + tweetnacl "^0.14.3" + +betterbenchmarks@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/betterbenchmarks/-/betterbenchmarks-0.1.0.tgz#c07ac937e215d3d7a91a460eefb039b7c9002e43" + dependencies: + babel-core "^6.2.1" + babel-polyfill "^6.2.0" + cli-table "^0.3.1" + co "^4.6.0" + colors "^1.1.2" + fast-stats "0.0.3" + table "^3.7.4" + +"binary@>= 0.3.0 < 1": + version "0.3.0" + resolved "https://registry.yarnpkg.com/binary/-/binary-0.3.0.tgz#9f60553bc5ce8c3386f3b553cff47462adecaa79" + dependencies: + buffers "~0.1.1" + chainsaw "~0.1.0" + +bl@~1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/bl/-/bl-1.1.2.tgz#fdca871a99713aa00d19e3bbba41c44787a65398" + dependencies: + readable-stream "~2.0.5" + +block-stream@*: + version "0.0.9" + resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" + dependencies: + inherits "~2.0.0" + +bluebird@^3.4.1, bluebird@3.4.6: + version "3.4.6" + resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.4.6.tgz#01da8d821d87813d158967e743d5fe6c62cf8c0f" + +bluebird@~2.9.34: + version "2.9.34" + resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-2.9.34.tgz#2f7b4ec80216328a9fddebdf69c8d4942feff7d8" + +boolbase@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" + +boom@2.x.x: + version "2.10.1" + resolved "https://registry.yarnpkg.com/boom/-/boom-2.10.1.tgz#39c8918ceff5799f83f9492a848f625add0c766f" + dependencies: + hoek "2.x.x" + +brace-expansion@^1.0.0: + version "1.1.6" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.6.tgz#7197d7eaa9b87e648390ea61fc66c84427420df9" + dependencies: + balanced-match "^0.4.1" + concat-map "0.0.1" + +braces@^1.8.2: + version "1.8.5" + resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7" + dependencies: + expand-range "^1.8.1" + preserve "^0.2.0" + repeat-element "^1.1.2" + +bson@^0.5.2, bson@~0.5.6: + version "0.5.7" + resolved "https://registry.yarnpkg.com/bson/-/bson-0.5.7.tgz#0d11fe0936c1fee029e11f7063f5d0ab2422ea3e" + +bson@~0.4.23: + version "0.4.23" + resolved "https://registry.yarnpkg.com/bson/-/bson-0.4.23.tgz#e65a2e3c7507ffade4109bc7575a76e50f8da915" + +bson@~1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/bson/-/bson-1.0.1.tgz#3a5addb0f2ff88bc3436e708e4bdb8637602d72d" + +bson@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/bson/-/bson-1.0.0.tgz#4d95affb53990c863b8fc9f5ba1fa8f478e7ebab" + +buffer-shims@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/buffer-shims/-/buffer-shims-1.0.0.tgz#9978ce317388c649ad8793028c3477ef044a8b51" + +buffers@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/buffers/-/buffers-0.1.1.tgz#b24579c3bed4d6d396aeee6d9a8ae7f5482ab7bb" + +builtin-modules@^1.0.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" + +caching-transform@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/caching-transform/-/caching-transform-1.0.1.tgz#6dbdb2f20f8d8fbce79f3e94e9d1742dcdf5c0a1" + dependencies: + md5-hex "^1.2.0" + mkdirp "^0.5.1" + write-file-atomic "^1.1.4" + +caller-path@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/caller-path/-/caller-path-0.1.0.tgz#94085ef63581ecd3daa92444a8fe94e82577751f" + dependencies: + callsites "^0.2.0" + +callsites@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/callsites/-/callsites-0.2.0.tgz#afab96262910a7f33c19a5775825c69f34e350ca" + +camelcase-keys@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-2.1.0.tgz#308beeaffdf28119051efa1d932213c91b8f92e7" + dependencies: + camelcase "^2.0.0" + map-obj "^1.0.0" + +camelcase@^1.0.2: + version "1.2.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" + +camelcase@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-2.1.1.tgz#7c1d16d679a1bbe59ca02cacecfb011e201f5a1f" + +camelcase@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz#32fc4b9fcdaf845fcdf7e73bb97cac2261f0ab0a" + +caseless@~0.11.0: + version "0.11.0" + resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.11.0.tgz#715b96ea9841593cc33067923f5ec60ebda4f7d7" + +catharsis@~0.8.7: + version "0.8.8" + resolved "https://registry.yarnpkg.com/catharsis/-/catharsis-0.8.8.tgz#693479f43aac549d806bd73e924cd0d944951a06" + dependencies: + underscore-contrib "~0.3.0" + +center-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" + dependencies: + align-text "^0.1.3" + lazy-cache "^1.0.3" + +chainsaw@~0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/chainsaw/-/chainsaw-0.1.0.tgz#5eab50b28afe58074d0d58291388828b5e5fbc98" + dependencies: + traverse ">=0.3.0 <0.4" + +chalk@^1.0.0, chalk@^1.1.0, chalk@^1.1.1, chalk@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" + dependencies: + ansi-styles "^2.2.1" + escape-string-regexp "^1.0.2" + has-ansi "^2.0.0" + strip-ansi "^3.0.0" + supports-color "^2.0.0" + +cheerio@^0.19.0: + version "0.19.0" + resolved "https://registry.yarnpkg.com/cheerio/-/cheerio-0.19.0.tgz#772e7015f2ee29965096d71ea4175b75ab354925" + dependencies: + css-select "~1.0.0" + dom-serializer "~0.1.0" + entities "~1.1.1" + htmlparser2 "~3.8.1" + lodash "^3.2.0" + +circular-json@^0.3.0: + version "0.3.1" + resolved "https://registry.yarnpkg.com/circular-json/-/circular-json-0.3.1.tgz#be8b36aefccde8b3ca7aa2d6afc07a37242c0d2d" + +cli-cursor@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-1.0.2.tgz#64da3f7d56a54412e59794bd62dc35295e8f2987" + dependencies: + restore-cursor "^1.0.1" + +cli-table@^0.3.1: + version "0.3.1" + resolved "https://registry.yarnpkg.com/cli-table/-/cli-table-0.3.1.tgz#f53b05266a8b1a0b934b3d0821e6e2dc5914ae23" + dependencies: + colors "1.0.3" + +cli-width@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.1.0.tgz#b234ca209b29ef66fc518d9b98d5847b00edf00a" + +cliui@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" + dependencies: + center-align "^0.1.1" + right-align "^0.1.1" + wordwrap "0.0.2" + +cliui@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz#120601537a916d29940f934da3b48d585a39213d" + dependencies: + string-width "^1.0.1" + strip-ansi "^3.0.1" + wrap-ansi "^2.0.0" + +co@^4.6.0, co@4.6.0: + version "4.6.0" + resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" + +code-point-at@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" + +colors@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63" + +colors@1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/colors/-/colors-1.0.3.tgz#0433f44d809680fdeb60ed260f1b0c262e82a40b" + +combined-stream@^1.0.5, combined-stream@~1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.5.tgz#938370a57b4a51dea2c77c15d5c5fdf895164009" + dependencies: + delayed-stream "~1.0.0" + +commander@^2.9.0: + version "2.9.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-2.9.0.tgz#9c99094176e12240cb22d6c5146098400fe0f7d4" + dependencies: + graceful-readlink ">= 1.0.0" + +commondir@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b" + +concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + +concat-stream@^1.4.6: + version "1.5.2" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.5.2.tgz#708978624d856af41a5a741defdd261da752c266" + dependencies: + inherits "~2.0.1" + readable-stream "~2.0.0" + typedarray "~0.0.5" + +convert-source-map@^1.1.0, convert-source-map@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.3.0.tgz#e9f3e9c6e2728efc2676696a70eb382f73106a67" + +core-js@^2.4.0: + version "2.4.1" + resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.4.1.tgz#4de911e667b0eae9124e34254b53aea6fc618d3e" + +core-util-is@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + +coveralls@^2.11.6: + version "2.11.15" + resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-2.11.15.tgz#37d3474369d66c14f33fa73a9d25cee6e099fca0" + dependencies: + js-yaml "3.6.1" + lcov-parse "0.0.10" + log-driver "1.2.5" + minimist "1.2.0" + request "2.75.0" + +cross-spawn@^4: + version "4.0.2" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-4.0.2.tgz#7b9247621c23adfdd3856004a823cbe397424d41" + dependencies: + lru-cache "^4.0.1" + which "^1.2.9" + +cryptiles@2.x.x: + version "2.0.5" + resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-2.0.5.tgz#3bdfecdc608147c1c67202fa291e7dca59eaa3b8" + dependencies: + boom "2.x.x" + +css-select@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/css-select/-/css-select-1.0.0.tgz#b1121ca51848dd264e2244d058cee254deeb44b0" + dependencies: + boolbase "~1.0.0" + css-what "1.0" + domutils "1.4" + nth-check "~1.0.0" + +css-what@1.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/css-what/-/css-what-1.0.0.tgz#d7cc2df45180666f99d2b14462639469e00f736c" + +currently-unhandled@^0.4.1: + version "0.4.1" + resolved "https://registry.yarnpkg.com/currently-unhandled/-/currently-unhandled-0.4.1.tgz#988df33feab191ef799a61369dd76c17adf957ea" + dependencies: + array-find-index "^1.0.1" + +d@^0.1.1, d@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/d/-/d-0.1.1.tgz#da184c535d18d8ee7ba2aa229b914009fae11309" + dependencies: + es5-ext "~0.10.2" + +dashdash@^1.12.0: + version "1.14.0" + resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.0.tgz#29e486c5418bf0f356034a993d51686a33e84141" + dependencies: + assert-plus "^1.0.0" + +debug@^2.1.1, debug@^2.1.3, debug@^2.2.0: + version "2.3.2" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.3.2.tgz#94cb466ef7d6d2c7e5245cdd6e4104f2d0d70d30" + dependencies: + ms "0.7.2" + +debug@~2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.2.0.tgz#f87057e995b1a1f6ae6a4960664137bc56f039da" + dependencies: + ms "0.7.1" + +decamelize@^1.0.0, decamelize@^1.1.1, decamelize@^1.1.2: + version "1.2.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" + +deep-is@~0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" + +default-require-extensions@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/default-require-extensions/-/default-require-extensions-1.0.0.tgz#f37ea15d3e13ffd9b437d33e1a75b5fb97874cb8" + dependencies: + strip-bom "^2.0.0" + +del@^2.0.2: + version "2.2.2" + resolved "https://registry.yarnpkg.com/del/-/del-2.2.2.tgz#c12c981d067846c84bcaf862cff930d907ffd1a8" + dependencies: + globby "^5.0.0" + is-path-cwd "^1.0.0" + is-path-in-cwd "^1.0.0" + object-assign "^4.0.1" + pify "^2.0.0" + pinkie-promise "^2.0.0" + rimraf "^2.2.8" + +delayed-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" + +delegates@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" + +detect-indent@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-4.0.0.tgz#f76d064352cdf43a1cb6ce619c4ee3a9475de208" + dependencies: + repeating "^2.0.0" + +docopt@~0.6.2: + version "0.6.2" + resolved "https://registry.yarnpkg.com/docopt/-/docopt-0.6.2.tgz#b28e9e2220da5ec49f7ea5bb24a47787405eeb11" + +doctrine@^1.2.2: + version "1.5.0" + resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-1.5.0.tgz#379dce730f6166f76cefa4e6707a159b02c5a6fa" + dependencies: + esutils "^2.0.2" + isarray "^1.0.0" + +dom-serializer@~0.1.0, dom-serializer@0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-0.1.0.tgz#073c697546ce0780ce23be4a28e293e40bc30c82" + dependencies: + domelementtype "~1.1.1" + entities "~1.1.1" + +domelementtype@~1.1.1: + version "1.1.3" + resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-1.1.3.tgz#bd28773e2642881aec51544924299c5cd822185b" + +domelementtype@1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-1.3.0.tgz#b17aed82e8ab59e52dd9c19b1756e0fc187204c2" + +domhandler@2.3: + version "2.3.0" + resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-2.3.0.tgz#2de59a0822d5027fabff6f032c2b25a2a8abe738" + dependencies: + domelementtype "1" + +domutils@1.4: + version "1.4.3" + resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.4.3.tgz#0865513796c6b306031850e175516baf80b72a6f" + dependencies: + domelementtype "1" + +domutils@1.5: + version "1.5.1" + resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.5.1.tgz#dcd8488a26f563d61079e48c9f7b7e32373682cf" + dependencies: + dom-serializer "0" + domelementtype "1" + +downcache@0.0.8: + version "0.0.8" + resolved "https://registry.yarnpkg.com/downcache/-/downcache-0.0.8.tgz#332320dde5806ea55d2e6d2ea674990bda4e8b75" + dependencies: + extend "2.0.x" + graceful-fs "2.0.3" + limiter "1.0.x" + mkdirp "~0.3.5" + npmlog "1.0.0" + request "^2.34.0" + +duplexer@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" + +ecc-jsbn@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505" + dependencies: + jsbn "~0.1.0" + +entities@~1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/entities/-/entities-1.1.1.tgz#6e5c2d0a5621b5dadaecef80b90edfb5cd7772f0" + +entities@1.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/entities/-/entities-1.0.0.tgz#b2987aa3821347fcde642b24fdfc9e4fb712bf26" + +"errno@>=0.1.1 <0.2.0-0": + version "0.1.4" + resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.4.tgz#b896e23a9e5e8ba33871fc996abd3635fc9a1c7d" + dependencies: + prr "~0.0.0" + +error-ex@^1.2.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.0.tgz#e67b43f3e82c96ea3a584ffee0b9fc3325d802d9" + dependencies: + is-arrayish "^0.2.1" + +es5-ext@^0.10.7, es5-ext@^0.10.8, es5-ext@~0.10.11, es5-ext@~0.10.2, es5-ext@~0.10.7: + version "0.10.12" + resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.12.tgz#aa84641d4db76b62abba5e45fd805ecbab140047" + dependencies: + es6-iterator "2" + es6-symbol "~3.1" + +es6-iterator@2: + version "2.0.0" + resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.0.tgz#bd968567d61635e33c0b80727613c9cb4b096bac" + dependencies: + d "^0.1.1" + es5-ext "^0.10.7" + es6-symbol "3" + +es6-map@^0.1.3: + version "0.1.4" + resolved "https://registry.yarnpkg.com/es6-map/-/es6-map-0.1.4.tgz#a34b147be224773a4d7da8072794cefa3632b897" + dependencies: + d "~0.1.1" + es5-ext "~0.10.11" + es6-iterator "2" + es6-set "~0.1.3" + es6-symbol "~3.1.0" + event-emitter "~0.3.4" + +es6-promise@^3.2.1: + version "3.3.1" + resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.3.1.tgz#a08cdde84ccdbf34d027a1451bc91d4bcd28a613" + +es6-promise@3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.2.1.tgz#ec56233868032909207170c39448e24449dd1fc4" + +es6-set@~0.1.3: + version "0.1.4" + resolved "https://registry.yarnpkg.com/es6-set/-/es6-set-0.1.4.tgz#9516b6761c2964b92ff479456233a247dc707ce8" + dependencies: + d "~0.1.1" + es5-ext "~0.10.11" + es6-iterator "2" + es6-symbol "3" + event-emitter "~0.3.4" + +es6-symbol@~3.1, es6-symbol@~3.1.0, es6-symbol@3: + version "3.1.0" + resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.0.tgz#94481c655e7a7cad82eba832d97d5433496d7ffa" + dependencies: + d "~0.1.1" + es5-ext "~0.10.11" + +es6-weak-map@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-2.0.1.tgz#0d2bbd8827eb5fb4ba8f97fbfea50d43db21ea81" + dependencies: + d "^0.1.1" + es5-ext "^0.10.8" + es6-iterator "2" + es6-symbol "3" + +escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5, escape-string-regexp@~1.0.3: + version "1.0.5" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + +escodegen@1.1.x: + version "1.1.0" + resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.1.0.tgz#c663923f6e20aad48d0c0fa49f31c6d4f49360cf" + dependencies: + esprima "~1.0.4" + estraverse "~1.5.0" + esutils "~1.0.0" + optionalDependencies: + source-map "~0.1.30" + +escope@^3.6.0: + version "3.6.0" + resolved "https://registry.yarnpkg.com/escope/-/escope-3.6.0.tgz#e01975e812781a163a6dadfdd80398dc64c889c3" + dependencies: + es6-map "^0.1.3" + es6-weak-map "^2.0.1" + esrecurse "^4.1.0" + estraverse "^4.1.1" + +eslint@^3.8.1: + version "3.10.2" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-3.10.2.tgz#c9a10e8bf6e9d65651204778c503341f1eac3ce7" + dependencies: + babel-code-frame "^6.16.0" + chalk "^1.1.3" + concat-stream "^1.4.6" + debug "^2.1.1" + doctrine "^1.2.2" + escope "^3.6.0" + espree "^3.3.1" + estraverse "^4.2.0" + esutils "^2.0.2" + file-entry-cache "^2.0.0" + glob "^7.0.3" + globals "^9.2.0" + ignore "^3.2.0" + imurmurhash "^0.1.4" + inquirer "^0.12.0" + is-my-json-valid "^2.10.0" + is-resolvable "^1.0.0" + js-yaml "^3.5.1" + json-stable-stringify "^1.0.0" + levn "^0.3.0" + lodash "^4.0.0" + mkdirp "^0.5.0" + natural-compare "^1.4.0" + optionator "^0.8.2" + path-is-inside "^1.0.1" + pluralize "^1.2.1" + progress "^1.1.8" + require-uncached "^1.0.2" + shelljs "^0.7.5" + strip-bom "^3.0.0" + strip-json-comments "~1.0.1" + table "^3.7.8" + text-table "~0.2.0" + user-home "^2.0.0" + +espree@^3.3.1: + version "3.3.2" + resolved "https://registry.yarnpkg.com/espree/-/espree-3.3.2.tgz#dbf3fadeb4ecb4d4778303e50103b3d36c88b89c" + dependencies: + acorn "^4.0.1" + acorn-jsx "^3.0.0" + +espree@~2.2.3: + version "2.2.5" + resolved "https://registry.yarnpkg.com/espree/-/espree-2.2.5.tgz#df691b9310889402aeb29cc066708c56690b854b" + +esprima@^2.6.0: + version "2.7.3" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.7.3.tgz#96e3b70d5779f6ad49cd032673d1c312767ba581" + +esprima@~1.0.4, esprima@1.0.x: + version "1.0.4" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-1.0.4.tgz#9f557e08fc3b4d26ece9dd34f8fbf476b62585ad" + +esrecurse@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.1.0.tgz#4713b6536adf7f2ac4f327d559e7756bff648220" + dependencies: + estraverse "~4.1.0" + object-assign "^4.0.1" + +estraverse@^4.1.1, estraverse@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13" + +estraverse@~1.5.0: + version "1.5.1" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.5.1.tgz#867a3e8e58a9f84618afb6c2ddbcd916b7cbaf71" + +estraverse@~4.1.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.1.1.tgz#f6caca728933a850ef90661d0e17982ba47111a2" + +esutils@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" + +esutils@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-1.0.0.tgz#8151d358e20c8acc7fb745e7472c0025fe496570" + +event-emitter@~0.3.4: + version "0.3.4" + resolved "https://registry.yarnpkg.com/event-emitter/-/event-emitter-0.3.4.tgz#8d63ddfb4cfe1fae3b32ca265c4c720222080bb5" + dependencies: + d "~0.1.1" + es5-ext "~0.10.7" + +event-stream@^3.3.1, event-stream@^3.3.2: + version "3.3.4" + resolved "https://registry.yarnpkg.com/event-stream/-/event-stream-3.3.4.tgz#4ab4c9a0f5a54db9338b4c34d86bfce8f4b35571" + dependencies: + duplexer "~0.1.1" + from "~0" + map-stream "~0.1.0" + pause-stream "0.0.11" + split "0.3" + stream-combiner "~0.0.4" + through "~2.3.1" + +exit-hook@^1.0.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/exit-hook/-/exit-hook-1.1.1.tgz#f05ca233b48c05d54fff07765df8507e95c02ff8" + +expand-brackets@^0.1.4: + version "0.1.5" + resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b" + dependencies: + is-posix-bracket "^0.1.0" + +expand-range@^1.8.1: + version "1.8.2" + resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337" + dependencies: + fill-range "^2.1.0" + +extend@~3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.0.tgz#5a474353b9f3353ddd8176dfd37b91c83a46f1d4" + +extend@2.0.x: + version "2.0.1" + resolved "https://registry.yarnpkg.com/extend/-/extend-2.0.1.tgz#1ee8010689e7395ff9448241c98652bc759a8260" + +extglob@^0.3.1: + version "0.3.2" + resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1" + dependencies: + is-extglob "^1.0.0" + +extsprintf@1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.0.2.tgz#e1080e0658e300b06294990cc70e1502235fd550" + +fast-levenshtein@~2.0.4: + version "2.0.5" + resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.5.tgz#bd33145744519ab1c36c3ee9f31f08e9079b67f2" + +fast-stats@0.0.3: + version "0.0.3" + resolved "https://registry.yarnpkg.com/fast-stats/-/fast-stats-0.0.3.tgz#650af963c3ff85c496a3610f20d40cd4c164594d" + +figures@^1.3.5, figures@^1.4.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/figures/-/figures-1.7.0.tgz#cbe1e3affcf1cd44b80cadfed28dc793a9701d2e" + dependencies: + escape-string-regexp "^1.0.5" + object-assign "^4.1.0" + +file-entry-cache@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-2.0.0.tgz#c392990c3e684783d838b8c84a45d8a048458361" + dependencies: + flat-cache "^1.2.1" + object-assign "^4.0.1" + +filename-regex@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.0.tgz#996e3e80479b98b9897f15a8a58b3d084e926775" + +fill-range@^2.1.0: + version "2.2.3" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.3.tgz#50b77dfd7e469bc7492470963699fe7a8485a723" + dependencies: + is-number "^2.1.0" + isobject "^2.0.0" + randomatic "^1.1.3" + repeat-element "^1.1.2" + repeat-string "^1.5.2" + +find-cache-dir@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-0.1.1.tgz#c8defae57c8a52a8a784f9e31c57c742e993a0b9" + dependencies: + commondir "^1.0.1" + mkdirp "^0.5.1" + pkg-dir "^1.0.0" + +find-root@^0.1.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/find-root/-/find-root-0.1.2.tgz#98d2267cff1916ccaf2743b3a0eea81d79d7dcd1" + +find-up@^1.0.0, find-up@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f" + dependencies: + path-exists "^2.0.0" + pinkie-promise "^2.0.0" + +flat-cache@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-1.2.1.tgz#6c837d6225a7de5659323740b36d5361f71691ff" + dependencies: + circular-json "^0.3.0" + del "^2.0.2" + graceful-fs "^4.1.2" + write "^0.2.1" + +for-in@^0.1.5: + version "0.1.6" + resolved "https://registry.yarnpkg.com/for-in/-/for-in-0.1.6.tgz#c9f96e89bfad18a545af5ec3ed352a1d9e5b4dc8" + +for-own@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.4.tgz#0149b41a39088c7515f51ebe1c1386d45f935072" + dependencies: + for-in "^0.1.5" + +foreground-child@^1.3.3, foreground-child@^1.5.3: + version "1.5.3" + resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-1.5.3.tgz#94dd6aba671389867de8e57e99f1c2ecfb15c01a" + dependencies: + cross-spawn "^4" + signal-exit "^3.0.0" + +forever-agent@~0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" + +form-data@~2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.0.0.tgz#6f0aebadcc5da16c13e1ecc11137d85f9b883b25" + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.5" + mime-types "^2.1.11" + +form-data@~2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.1.2.tgz#89c3534008b97eada4cbb157d58f6f5df025eae4" + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.5" + mime-types "^2.1.12" + +from@~0: + version "0.1.3" + resolved "https://registry.yarnpkg.com/from/-/from-0.1.3.tgz#ef63ac2062ac32acf7862e0d40b44b896f22f3bc" + +fs-extra@^0.22.1: + version "0.22.1" + resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-0.22.1.tgz#5fd6f8049dc976ca19eb2355d658173cabcce056" + dependencies: + graceful-fs "^4.1.2" + jsonfile "^2.1.0" + rimraf "^2.2.8" + +fs-extra@~0.30.0: + version "0.30.0" + resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-0.30.0.tgz#f233ffcc08d4da7d432daa449776989db1df93f0" + dependencies: + graceful-fs "^4.1.2" + jsonfile "^2.1.0" + klaw "^1.0.0" + path-is-absolute "^1.0.0" + rimraf "^2.2.8" + +fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + +fstream@^1.0.2: + version "1.0.10" + resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.10.tgz#604e8a92fe26ffd9f6fae30399d4984e1ab22822" + dependencies: + graceful-fs "^4.1.2" + inherits "~2.0.0" + mkdirp ">=0.5 0" + rimraf "2" + +"fstream@>= 0.1.30 < 1": + version "0.1.31" + resolved "https://registry.yarnpkg.com/fstream/-/fstream-0.1.31.tgz#7337f058fbbbbefa8c9f561a28cab0849202c988" + dependencies: + graceful-fs "~3.0.2" + inherits "~2.0.0" + mkdirp "0.5" + rimraf "2" + +gauge@~1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/gauge/-/gauge-1.0.2.tgz#53e25965dfaf1c85be3a2a0633306a24a67dc2f9" + dependencies: + ansi "^0.3.0" + has-unicode "^1.0.0" + +generate-function@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/generate-function/-/generate-function-2.0.0.tgz#6858fe7c0969b7d4e9093337647ac79f60dfbe74" + +generate-object-property@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/generate-object-property/-/generate-object-property-1.2.0.tgz#9c0e1c40308ce804f4783618b937fa88f99d50d0" + dependencies: + is-property "^1.0.0" + +get-caller-file@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.2.tgz#f702e63127e7e231c160a80c1554acb70d5047e5" + +get-mongodb-version@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/get-mongodb-version/-/get-mongodb-version-0.0.1.tgz#bc8aa433ba2fdd57fa33312dcf89f06f3a908caa" + dependencies: + debug "^2.2.0" + lodash.startswith "^3.0.1" + minimist "^1.1.1" + mongodb "^2.0.39" + which "^1.1.1" + +get-stdin@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe" + +getpass@^0.1.1: + version "0.1.6" + resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.6.tgz#283ffd9fc1256840875311c1b60e8c40187110e6" + dependencies: + assert-plus "^1.0.0" + +gleak@0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/gleak/-/gleak-0.5.0.tgz#9cd7694be50d6dbeb842021ed8160814c51faddf" + +glob-base@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4" + dependencies: + glob-parent "^2.0.0" + is-glob "^2.0.0" + +glob-parent@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28" + dependencies: + is-glob "^2.0.0" + +glob@^7.0.0, glob@^7.0.3, glob@^7.0.5, glob@^7.0.6: + version "7.1.1" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.1.tgz#805211df04faaf1c63a3600306cdf5ade50b2ec8" + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.2" + once "^1.3.0" + path-is-absolute "^1.0.0" + +globals@^9.0.0, globals@^9.2.0: + version "9.13.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-9.13.0.tgz#d97706b61600d8dbe94708c367d3fdcf48470b8f" + +globby@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/globby/-/globby-5.0.0.tgz#ebd84667ca0dbb330b99bcfc68eac2bc54370e0d" + dependencies: + array-union "^1.0.1" + arrify "^1.0.0" + glob "^7.0.3" + object-assign "^4.0.1" + pify "^2.0.0" + pinkie-promise "^2.0.0" + +graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9: + version "4.1.10" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.10.tgz#f2d720c22092f743228775c75e3612632501f131" + +graceful-fs@~3.0.2: + version "3.0.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-3.0.11.tgz#7613c778a1afea62f25c630a086d7f3acbbdd818" + dependencies: + natives "^1.1.0" + +graceful-fs@2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-2.0.3.tgz#7cd2cdb228a4a3f36e95efa6cc142de7d1a136d0" + +"graceful-readlink@>= 1.0.0": + version "1.0.1" + resolved "https://registry.yarnpkg.com/graceful-readlink/-/graceful-readlink-1.0.1.tgz#4cafad76bc62f02fa039b2f94e9a3dd3a391a725" + +handlebars@^4.0.3: + version "4.0.6" + resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.6.tgz#2ce4484850537f9c97a8026d5399b935c4ed4ed7" + dependencies: + async "^1.4.0" + optimist "^0.6.1" + source-map "^0.4.4" + optionalDependencies: + uglify-js "^2.6" + +handlebars@2.0.0-alpha.1: + version v2.0.0-alpha.1 + resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-2.0.0-alpha.1.tgz#c4d149068c713de0afa7f45bbb88a2ca73715afd" + dependencies: + optimist "~0.3" + optionalDependencies: + uglify-js "~2.3" + +har-validator@~2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-2.0.6.tgz#cdcbc08188265ad119b6a5a7c8ab70eecfb5d27d" + dependencies: + chalk "^1.1.1" + commander "^2.9.0" + is-my-json-valid "^2.12.4" + pinkie-promise "^2.0.0" + +has-ansi@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" + dependencies: + ansi-regex "^2.0.0" + +has-flag@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" + +has-unicode@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-1.0.1.tgz#c46fceea053eb8ec789bffbba25fca52dfdcf38e" + +hawk@~3.1.3: + version "3.1.3" + resolved "https://registry.yarnpkg.com/hawk/-/hawk-3.1.3.tgz#078444bd7c1640b0fe540d2c9b73d59678e8e1c4" + dependencies: + boom "2.x.x" + cryptiles "2.x.x" + hoek "2.x.x" + sntp "1.x.x" + +hoek@2.x.x: + version "2.16.3" + resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed" + +home-or-tmp@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8" + dependencies: + os-homedir "^1.0.0" + os-tmpdir "^1.0.1" + +hosted-git-info@^2.1.4: + version "2.1.5" + resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.1.5.tgz#0ba81d90da2e25ab34a332e6ec77936e1598118b" + +htmlparser2@~3.8.1: + version "3.8.3" + resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-3.8.3.tgz#996c28b191516a8be86501a7d79757e5c70c1068" + dependencies: + domelementtype "1" + domhandler "2.3" + domutils "1.5" + entities "1.0" + readable-stream "1.1" + +http-signature@~1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.1.1.tgz#df72e267066cd0ac67fb76adf8e134a8fbcf91bf" + dependencies: + assert-plus "^0.2.0" + jsprim "^1.2.2" + sshpk "^1.7.0" + +ignore@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.2.0.tgz#8d88f03c3002a0ac52114db25d2c673b0bf1e435" + +imurmurhash@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" + +indent-string@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-2.1.0.tgz#8e2d48348742121b4a8218b7a137e9a52049dc80" + dependencies: + repeating "^2.0.0" + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@~2.0.0, inherits@~2.0.1, inherits@2: + version "2.0.3" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" + +inquirer@^0.12.0: + version "0.12.0" + resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-0.12.0.tgz#1ef2bfd63504df0bc75785fff8c2c41df12f077e" + dependencies: + ansi-escapes "^1.1.0" + ansi-regex "^2.0.0" + chalk "^1.0.0" + cli-cursor "^1.0.1" + cli-width "^2.0.0" + figures "^1.3.5" + lodash "^4.3.0" + readline2 "^1.0.1" + run-async "^0.1.0" + rx-lite "^3.1.2" + string-width "^1.0.1" + strip-ansi "^3.0.0" + through "^2.3.6" + +integra@0.1.8: + version "0.1.8" + resolved "https://registry.yarnpkg.com/integra/-/integra-0.1.8.tgz#8d5b8019f87ea3704e6c97da2c912e14ec3bece7" + dependencies: + escodegen "1.1.x" + esprima "1.0.x" + handlebars "2.0.0-alpha.1" + mkdirp latest + rimraf "2.2.6" + +interpret@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.0.1.tgz#d579fb7f693b858004947af39fa0db49f795602c" + +invariant@^2.2.0: + version "2.2.2" + resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.2.tgz#9e1f56ac0acdb6bf303306f338be3b204ae60360" + dependencies: + loose-envify "^1.0.0" + +invert-kv@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6" + +is-arrayish@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" + +is-buffer@^1.0.2: + version "1.1.4" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.4.tgz#cfc86ccd5dc5a52fa80489111c6920c457e2d98b" + +is-builtin-module@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-builtin-module/-/is-builtin-module-1.0.0.tgz#540572d34f7ac3119f8f76c30cbc1b1e037affbe" + dependencies: + builtin-modules "^1.0.0" + +is-dotfile@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.2.tgz#2c132383f39199f8edc268ca01b9b007d205cc4d" + +is-equal-shallow@^0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534" + dependencies: + is-primitive "^2.0.0" + +is-extendable@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" + +is-extglob@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0" + +is-finite@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.0.2.tgz#cc6677695602be550ef11e8b4aa6305342b6d0aa" + dependencies: + number-is-nan "^1.0.0" + +is-fullwidth-code-point@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" + dependencies: + number-is-nan "^1.0.0" + +is-fullwidth-code-point@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" + +is-glob@^2.0.0, is-glob@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" + dependencies: + is-extglob "^1.0.0" + +is-my-json-valid@^2.10.0, is-my-json-valid@^2.12.4: + version "2.15.0" + resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.15.0.tgz#936edda3ca3c211fd98f3b2d3e08da43f7b2915b" + dependencies: + generate-function "^2.0.0" + generate-object-property "^1.1.0" + jsonpointer "^4.0.0" + xtend "^4.0.0" + +is-number@^2.0.2, is-number@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f" + dependencies: + kind-of "^3.0.2" + +is-path-cwd@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-1.0.0.tgz#d225ec23132e89edd38fda767472e62e65f1106d" + +is-path-in-cwd@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-1.0.0.tgz#6477582b8214d602346094567003be8a9eac04dc" + dependencies: + is-path-inside "^1.0.0" + +is-path-inside@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-1.0.0.tgz#fc06e5a1683fbda13de667aff717bbc10a48f37f" + dependencies: + path-is-inside "^1.0.1" + +is-posix-bracket@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" + +is-primitive@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575" + +is-property@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-property/-/is-property-1.0.2.tgz#57fe1c4e48474edd65b09911f26b1cd4095dda84" + +is-resolvable@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-resolvable/-/is-resolvable-1.0.0.tgz#8df57c61ea2e3c501408d100fb013cf8d6e0cc62" + dependencies: + tryit "^1.0.1" + +is-typedarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" + +is-utf8@^0.2.0: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" + +isarray@^1.0.0, isarray@~1.0.0, isarray@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + +isarray@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" + +isexe@^1.1.1: + version "1.1.2" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-1.1.2.tgz#36f3e22e60750920f5e7241a476a8c6a42275ad0" + +isobject@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" + dependencies: + isarray "1.0.0" + +isstream@~0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" + +istanbul-lib-coverage@^1.0.0, istanbul-lib-coverage@^1.0.0-alpha, istanbul-lib-coverage@^1.0.0-alpha.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-1.0.0.tgz#c3f9b6d226da12424064cce87fce0fb57fdfa7a2" + +istanbul-lib-hook@^1.0.0-alpha.4: + version "1.0.0-alpha.4" + resolved "https://registry.yarnpkg.com/istanbul-lib-hook/-/istanbul-lib-hook-1.0.0-alpha.4.tgz#8c5bb9f6fbd8526e0ae6cf639af28266906b938f" + dependencies: + append-transform "^0.3.0" + +istanbul-lib-instrument@^1.2.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-1.3.0.tgz#19f0a973397454989b98330333063a5b56df0e58" + dependencies: + babel-generator "^6.18.0" + babel-template "^6.16.0" + babel-traverse "^6.18.0" + babel-types "^6.18.0" + babylon "^6.13.0" + istanbul-lib-coverage "^1.0.0" + semver "^5.3.0" + +istanbul-lib-report@^1.0.0-alpha.3: + version "1.0.0-alpha.3" + resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-1.0.0-alpha.3.tgz#32d5f6ec7f33ca3a602209e278b2e6ff143498af" + dependencies: + async "^1.4.2" + istanbul-lib-coverage "^1.0.0-alpha" + mkdirp "^0.5.1" + path-parse "^1.0.5" + rimraf "^2.4.3" + supports-color "^3.1.2" + +istanbul-lib-source-maps@^1.0.2: + version "1.1.0" + resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-1.1.0.tgz#9d429218f35b823560ea300a96ff0c3bbdab785f" + dependencies: + istanbul-lib-coverage "^1.0.0-alpha.0" + mkdirp "^0.5.1" + rimraf "^2.4.4" + source-map "^0.5.3" + +istanbul-reports@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-1.0.0.tgz#24b4eb2b1d29d50f103b369bd422f6e640aa0777" + dependencies: + handlebars "^4.0.3" + +jodid25519@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/jodid25519/-/jodid25519-1.0.2.tgz#06d4912255093419477d425633606e0e90782967" + dependencies: + jsbn "~0.1.0" + +js-tokens@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-2.0.0.tgz#79903f5563ee778cc1162e6dcf1a0027c97f9cb5" + +js-yaml@^3.5.1: + version "3.7.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.7.0.tgz#5c967ddd837a9bfdca5f2de84253abe8a1c03b80" + dependencies: + argparse "^1.0.7" + esprima "^2.6.0" + +js-yaml@3.6.1: + version "3.6.1" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.6.1.tgz#6e5fe67d8b205ce4d22fad05b7781e8dadcc4b30" + dependencies: + argparse "^1.0.7" + esprima "^2.6.0" + +js2xmlparser@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/js2xmlparser/-/js2xmlparser-1.0.0.tgz#5a170f2e8d6476ce45405e04823242513782fe30" + +jsbn@~0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.0.tgz#650987da0dd74f4ebf5a11377a2aa2d273e97dfd" + +jsdoc@3.4.0: + version "3.4.0" + resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.4.0.tgz#341cdb06e44a113d9541efd212c95a488064e9ee" + dependencies: + async "~1.4.0" + bluebird "~2.9.34" + catharsis "~0.8.7" + escape-string-regexp "~1.0.3" + espree "~2.2.3" + js2xmlparser "~1.0.0" + marked "~0.3.4" + requizzle "~0.2.0" + strip-json-comments "~1.0.2" + taffydb "https://github.com/hegemonic/taffydb/tarball/7d100bcee0e997ee4977e273cdce60bd8933050e" + underscore "~1.8.3" + wrench "~1.5.8" + +jsesc@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-1.3.0.tgz#46c3fec8c1892b12b0833db9bc7622176dbab34b" + +json-schema@0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" + +json-stable-stringify@^1.0.0, json-stable-stringify@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz#9a759d39c5f2ff503fd5300646ed445f88c4f9af" + dependencies: + jsonify "~0.0.0" + +json-stringify-safe@~5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" + +json5@^0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.0.tgz#9b20715b026cbe3778fd769edccd822d8332a5b2" + +jsonfile@^2.1.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-2.4.0.tgz#3736a2b428b87bbda0cc83b53fa3d633a35c2ae8" + optionalDependencies: + graceful-fs "^4.1.6" + +jsonify@~0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" + +jsonparse@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/jsonparse/-/jsonparse-1.2.0.tgz#5c0c5685107160e72fe7489bddea0b44c2bc67bd" + +jsonpointer@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/jsonpointer/-/jsonpointer-4.0.0.tgz#6661e161d2fc445f19f98430231343722e1fcbd5" + +JSONStream@^1.0.7, JSONStream@^1.1.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-1.2.1.tgz#32aa5790e799481083b49b4b7fa94e23bae69bf9" + dependencies: + jsonparse "^1.2.0" + through ">=2.2.7 <3" + +jsprim@^1.2.2: + version "1.3.1" + resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.3.1.tgz#2a7256f70412a29ee3670aaca625994c4dcff252" + dependencies: + extsprintf "1.0.2" + json-schema "0.2.3" + verror "1.3.6" + +kerberos@0.0.17: + version "0.0.17" + resolved "https://registry.yarnpkg.com/kerberos/-/kerberos-0.0.17.tgz#29a67c0b127bfa52bdd3b53b7b8c8659a9a084f8" + dependencies: + nan "~2.0" + +key-tree-store@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/key-tree-store/-/key-tree-store-1.3.0.tgz#5ea29afc2529a425938437d6955b714ce6a9791f" + +kind-of@^3.0.2: + version "3.0.4" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.0.4.tgz#7b8ecf18a4e17f8269d73b501c9f232c96887a74" + dependencies: + is-buffer "^1.0.2" + +klaw@^1.0.0: + version "1.3.1" + resolved "https://registry.yarnpkg.com/klaw/-/klaw-1.3.1.tgz#4088433b46b3b1ba259d78785d8e96f73ba02439" + optionalDependencies: + graceful-fs "^4.1.9" + +lazy-cache@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" + +lcid@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835" + dependencies: + invert-kv "^1.0.0" + +lcov-parse@0.0.10: + version "0.0.10" + resolved "https://registry.yarnpkg.com/lcov-parse/-/lcov-parse-0.0.10.tgz#1b0b8ff9ac9c7889250582b70b71315d9da6d9a3" + +ldjson-stream@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/ldjson-stream/-/ldjson-stream-1.2.1.tgz#91beceda5ac4ed2b17e649fb777e7abfa0189c2b" + dependencies: + split2 "^0.2.1" + through2 "^0.6.1" + +levn@^0.3.0, levn@~0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" + dependencies: + prelude-ls "~1.1.2" + type-check "~0.3.2" + +limiter@1.0.x: + version "1.0.5" + resolved "https://registry.yarnpkg.com/limiter/-/limiter-1.0.5.tgz#9630b2a0d3bad63203f96e3d96f32f83d442dfc8" + +load-json-file@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" + dependencies: + graceful-fs "^4.1.2" + parse-json "^2.2.0" + pify "^2.0.0" + pinkie-promise "^2.0.0" + strip-bom "^2.0.0" + +lodash._arrayeach@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/lodash._arrayeach/-/lodash._arrayeach-3.0.0.tgz#bab156b2a90d3f1bbd5c653403349e5e5933ef9e" + +lodash._baseassign@^3.0.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz#8c38a099500f215ad09e59f1722fd0c52bfe0a4e" + dependencies: + lodash._basecopy "^3.0.0" + lodash.keys "^3.0.0" + +lodash._basecallback@^3.0.0: + version "3.3.1" + resolved "https://registry.yarnpkg.com/lodash._basecallback/-/lodash._basecallback-3.3.1.tgz#b7b2bb43dc2160424a21ccf26c57e443772a8e27" + dependencies: + lodash._baseisequal "^3.0.0" + lodash._bindcallback "^3.0.0" + lodash.isarray "^3.0.0" + lodash.pairs "^3.0.0" + +lodash._basecopy@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz#8da0e6a876cf344c0ad8a54882111dd3c5c7ca36" + +lodash._basecreate@^3.0.0: + version "3.0.3" + resolved "https://registry.yarnpkg.com/lodash._basecreate/-/lodash._basecreate-3.0.3.tgz#1bc661614daa7fc311b7d03bf16806a0213cf821" + +lodash._basefor@^3.0.0: + version "3.0.3" + resolved "https://registry.yarnpkg.com/lodash._basefor/-/lodash._basefor-3.0.3.tgz#7550b4e9218ef09fad24343b612021c79b4c20c2" + +lodash._baseisequal@^3.0.0: + version "3.0.7" + resolved "https://registry.yarnpkg.com/lodash._baseisequal/-/lodash._baseisequal-3.0.7.tgz#d8025f76339d29342767dcc887ce5cb95a5b51f1" + dependencies: + lodash.isarray "^3.0.0" + lodash.istypedarray "^3.0.0" + lodash.keys "^3.0.0" + +lodash._bindcallback@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz#e531c27644cf8b57a99e17ed95b35c748789392e" + +lodash._createassigner@^3.0.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/lodash._createassigner/-/lodash._createassigner-3.1.1.tgz#838a5bae2fdaca63ac22dee8e19fa4e6d6970b11" + dependencies: + lodash._bindcallback "^3.0.0" + lodash._isiterateecall "^3.0.0" + lodash.restparam "^3.0.0" + +lodash._getnative@^3.0.0: + version "3.9.1" + resolved "https://registry.yarnpkg.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz#570bc7dede46d61cdcde687d65d3eecbaa3aaff5" + +lodash._isiterateecall@^3.0.0: + version "3.0.9" + resolved "https://registry.yarnpkg.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz#5203ad7ba425fae842460e696db9cf3e6aac057c" + +lodash._root@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/lodash._root/-/lodash._root-3.0.1.tgz#fba1c4524c19ee9a5f8136b4609f017cf4ded692" + +lodash.assign@^3.0.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/lodash.assign/-/lodash.assign-3.2.0.tgz#3ce9f0234b4b2223e296b8fa0ac1fee8ebca64fa" + dependencies: + lodash._baseassign "^3.0.0" + lodash._createassigner "^3.0.0" + lodash.keys "^3.0.0" + +lodash.defaults@^3.1.2: + version "3.1.2" + resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-3.1.2.tgz#c7308b18dbf8bc9372d701a73493c61192bd2e2c" + dependencies: + lodash.assign "^3.0.0" + lodash.restparam "^3.0.0" + +lodash.defaults@^4.0.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-4.2.0.tgz#d09178716ffea4dde9e5fb7b37f6f0802274580c" + +lodash.difference@^4.1.1: + version "4.5.0" + resolved "https://registry.yarnpkg.com/lodash.difference/-/lodash.difference-4.5.0.tgz#9ccb4e505d486b91651345772885a2df27fd017c" + +lodash.isarguments@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a" + +lodash.isarray@^3.0.0: + version "3.0.4" + resolved "https://registry.yarnpkg.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz#79e4eb88c36a8122af86f844aa9bcd851b5fbb55" + +lodash.isfunction@^3.0.0, lodash.isfunction@^3.0.6: + version "3.0.8" + resolved "https://registry.yarnpkg.com/lodash.isfunction/-/lodash.isfunction-3.0.8.tgz#4db709fc81bc4a8fd7127a458a5346c5cdce2c6b" + +lodash.istypedarray@^3.0.0: + version "3.0.6" + resolved "https://registry.yarnpkg.com/lodash.istypedarray/-/lodash.istypedarray-3.0.6.tgz#c9a477498607501d8e8494d283b87c39281cef62" + +lodash.keys@^3.0.0: + version "3.1.2" + resolved "https://registry.yarnpkg.com/lodash.keys/-/lodash.keys-3.1.2.tgz#4dbc0472b156be50a0b286855d1bd0b0c656098a" + dependencies: + lodash._getnative "^3.0.0" + lodash.isarguments "^3.0.0" + lodash.isarray "^3.0.0" + +lodash.pairs@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/lodash.pairs/-/lodash.pairs-3.0.1.tgz#bbe08d5786eeeaa09a15c91ebf0dcb7d2be326a9" + dependencies: + lodash.keys "^3.0.0" + +lodash.restparam@^3.0.0: + version "3.6.1" + resolved "https://registry.yarnpkg.com/lodash.restparam/-/lodash.restparam-3.6.1.tgz#936a4e309ef330a7645ed4145986c85ae5b20805" + +lodash.startswith@^3.0.1: + version "3.2.0" + resolved "https://registry.yarnpkg.com/lodash.startswith/-/lodash.startswith-3.2.0.tgz#fc2e1ed2c6df8c777117632e87fe4a9181d483fb" + dependencies: + lodash._root "^3.0.0" + +lodash.transform@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/lodash.transform/-/lodash.transform-3.0.4.tgz#8ebe53fbae15857ade36eca67fc559b78bb3ebe9" + dependencies: + lodash._arrayeach "^3.0.0" + lodash._basecallback "^3.0.0" + lodash._basecreate "^3.0.0" + lodash._basefor "^3.0.0" + lodash.isarray "^3.0.0" + lodash.isfunction "^3.0.0" + lodash.istypedarray "^3.0.0" + lodash.keys "^3.0.0" + +lodash@^3.2.0: + version "3.10.1" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6" + +lodash@^4.0.0, lodash@^4.11.1, lodash@^4.2.0, lodash@^4.3.0, lodash@^4.6.1: + version "4.17.2" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.2.tgz#34a3055babe04ce42467b607d700072c7ff6bf42" + +log-driver@1.2.5: + version "1.2.5" + resolved "https://registry.yarnpkg.com/log-driver/-/log-driver-1.2.5.tgz#7ae4ec257302fd790d557cb10c97100d857b0056" + +longest@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" + +loose-envify@^1.0.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.3.0.tgz#6b26248c42f6d4fa4b0d8542f78edfcde35642a8" + dependencies: + js-tokens "^2.0.0" + +loud-rejection@^1.0.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/loud-rejection/-/loud-rejection-1.6.0.tgz#5b46f80147edee578870f086d04821cf998e551f" + dependencies: + currently-unhandled "^0.4.1" + signal-exit "^3.0.0" + +lru-cache@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.0.1.tgz#1343955edaf2e37d9b9e7ee7241e27c4b9fb72be" + dependencies: + pseudomap "^1.0.1" + yallist "^2.0.0" + +map-obj@^1.0.0, map-obj@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-1.0.1.tgz#d933ceb9205d82bdcf4886f6742bdc2b4dea146d" + +map-stream@~0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/map-stream/-/map-stream-0.1.0.tgz#e56aa94c4c8055a16404a0674b78f215f7c8e194" + +marked@~0.3.4: + version "0.3.6" + resolved "https://registry.yarnpkg.com/marked/-/marked-0.3.6.tgz#b2c6c618fccece4ef86c4fc6cb8a7cbf5aeda8d7" + +"match-stream@>= 0.0.2 < 1": + version "0.0.2" + resolved "https://registry.yarnpkg.com/match-stream/-/match-stream-0.0.2.tgz#99eb050093b34dffade421b9ac0b410a9cfa17cf" + dependencies: + buffers "~0.1.1" + readable-stream "~1.0.0" + +md5-hex@^1.2.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/md5-hex/-/md5-hex-1.3.0.tgz#d2c4afe983c4370662179b8cad145219135046c4" + dependencies: + md5-o-matic "^0.1.1" + +md5-o-matic@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/md5-o-matic/-/md5-o-matic-0.1.1.tgz#822bccd65e117c514fab176b25945d54100a03c3" + +meow@^3.1.0: + version "3.7.0" + resolved "https://registry.yarnpkg.com/meow/-/meow-3.7.0.tgz#72cb668b425228290abbfa856892587308a801fb" + dependencies: + camelcase-keys "^2.0.0" + decamelize "^1.1.2" + loud-rejection "^1.0.0" + map-obj "^1.0.1" + minimist "^1.1.3" + normalize-package-data "^2.3.4" + object-assign "^4.0.1" + read-pkg-up "^1.0.1" + redent "^1.0.0" + trim-newlines "^1.0.0" + +micromatch@^2.3.11: + version "2.3.11" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.3.11.tgz#86677c97d1720b363431d04d0d15293bd38c1565" + dependencies: + arr-diff "^2.0.0" + array-unique "^0.2.1" + braces "^1.8.2" + expand-brackets "^0.1.4" + extglob "^0.3.1" + filename-regex "^2.0.0" + is-extglob "^1.0.0" + is-glob "^2.0.1" + kind-of "^3.0.2" + normalize-path "^2.0.1" + object.omit "^2.0.0" + parse-glob "^3.0.4" + regex-cache "^0.4.2" + +mime-db@~1.24.0: + version "1.24.0" + resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.24.0.tgz#e2d13f939f0016c6e4e9ad25a8652f126c467f0c" + +mime-types@^2.1.11, mime-types@^2.1.12, mime-types@~2.1.7: + version "2.1.12" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.12.tgz#152ba256777020dd4663f54c2e7bc26381e71729" + dependencies: + mime-db "~1.24.0" + +minimatch@^3.0.2: + version "3.0.3" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.3.tgz#2a4e4090b96b2db06a9d7df01055a62a77c9b774" + dependencies: + brace-expansion "^1.0.0" + +minimist@^1.1.0, minimist@^1.1.1, minimist@^1.1.3, minimist@^1.2.0, minimist@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" + +minimist@~0.0.1: + version "0.0.10" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" + +minimist@0.0.8: + version "0.0.8" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" + +mkdirp@^0.5.0, mkdirp@^0.5.1, "mkdirp@>=0.5 0", mkdirp@0.5, mkdirp@latest: + version "0.5.1" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" + dependencies: + minimist "0.0.8" + +mkdirp@~0.3.5: + version "0.3.5" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.3.5.tgz#de3e5f8961c88c787ee1368df849ac4413eca8d7" + +moment@^2.10.6: + version "2.16.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.16.0.tgz#f38f2c97c9889b0ee18fc6cc392e1e443ad2da8e" + +mongodb-core@^1.2.24: + version "1.3.21" + resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-1.3.21.tgz#fe129e7bee2b3b26c1409de02ab60d03f6291cca" + dependencies: + bson "~0.4.23" + require_optional "~1.0.0" + +mongodb-core@2.0.13: + version "2.0.13" + resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-2.0.13.tgz#f9394b588dce0e579482e53d74dbc7d7a9d4519c" + dependencies: + bson "~0.5.6" + require_optional "~1.0.0" + +mongodb-core@christkv/mongodb-core#2.0: + version "2.1.1" + resolved "https://codeload.github.com/christkv/mongodb-core/tar.gz/c3565e81a4a26ec04c56be49336bdc413748d097" + dependencies: + bson "~1.0.1" + require_optional "~1.0.0" + +mongodb-download-url@^0.1.10: + version "0.1.10" + resolved "https://registry.yarnpkg.com/mongodb-download-url/-/mongodb-download-url-0.1.10.tgz#a7047eec95001de9f4df39f7e4030dc87eb3f806" + dependencies: + async "^1.5.0" + debug "^2.2.0" + lodash.defaults "^4.0.0" + minimist "^1.2.0" + mongodb-version-list "^0.0.3" + request "^2.65.0" + semver "^5.0.3" + +mongodb-extended-json@1.7.1: + version "1.7.1" + resolved "https://registry.yarnpkg.com/mongodb-extended-json/-/mongodb-extended-json-1.7.1.tgz#457ec1fe3582eb1c70c4c12a979d831c01344812" + dependencies: + async "^1.4.2" + bson "^0.5.2" + event-stream "^3.3.1" + JSONStream "^1.1.1" + lodash.isfunction "^3.0.6" + lodash.transform "^3.0.4" + moment "^2.10.6" + raf "^3.1.0" + +mongodb-topology-manager@1.0.x: + version "1.0.10" + resolved "https://registry.yarnpkg.com/mongodb-topology-manager/-/mongodb-topology-manager-1.0.10.tgz#587a563508a1c44f58977bc6aced1172502a1aea" + dependencies: + babel-core "^6.10.4" + babel-polyfill "^6.9.1" + bluebird "^3.4.1" + co "^4.6.0" + es6-promise "^3.2.1" + kerberos "0.0.17" + mkdirp "^0.5.1" + mongodb-core "^1.2.24" + rimraf "^2.4.3" + +mongodb-version-list@^0.0.3, mongodb-version-list@0.0.3: + version "0.0.3" + resolved "https://registry.yarnpkg.com/mongodb-version-list/-/mongodb-version-list-0.0.3.tgz#bbb261861f041fcfc5bc72b5fe2681788bd52cef" + dependencies: + cheerio "^0.19.0" + debug "^2.2.0" + downcache "0.0.8" + fs-extra "^0.22.1" + minimist "^1.1.1" + semver "^5.0.1" + +mongodb-version-manager@christkv/mongodb-version-manager#master: + version "1.0.7" + resolved "https://codeload.github.com/christkv/mongodb-version-manager/tar.gz/3ea7c20925d6a0b3a9243d341d3c69abf95e66b6" + dependencies: + ampersand-state "^5.0.1" + async "~1.5.0" + chalk "^1.1.1" + debug "~2.2.0" + docopt "~0.6.2" + figures "^1.4.0" + fs-extra "~0.30.0" + get-mongodb-version "0.0.1" + lodash.defaults "^3.1.2" + lodash.difference "^4.1.1" + mongodb-download-url "^0.1.10" + mongodb-version-list "0.0.3" + nugget "^2.0.0" + semver "~5.1.0" + tar "~2.2.1" + tildify "~1.2.0" + untildify "~2.1.0" + unzip "^0.1.11" + +mongodb@^2.0.39: + version "2.2.11" + resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-2.2.11.tgz#a828b036fe6a437a35e723af5f81781c4976306c" + dependencies: + es6-promise "3.2.1" + mongodb-core "2.0.13" + readable-stream "2.1.5" + +ms@0.7.1: + version "0.7.1" + resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.1.tgz#9cd13c03adbff25b65effde7ce864ee952017098" + +ms@0.7.2: + version "0.7.2" + resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.2.tgz#ae25cf2512b3885a1d95d7f037868d8431124765" + +mute-stream@0.0.5: + version "0.0.5" + resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.5.tgz#8fbfabb0a98a253d3184331f9e8deb7372fac6c0" + +nan@~2.0: + version "2.0.9" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.0.9.tgz#d02a770f46778842cceb94e17cab31ffc7234a05" + +natives@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/natives/-/natives-1.1.0.tgz#e9ff841418a6b2ec7a495e939984f78f163e6e31" + +natural-compare@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" + +node-uuid@~1.4.7: + version "1.4.7" + resolved "https://registry.yarnpkg.com/node-uuid/-/node-uuid-1.4.7.tgz#6da5a17668c4b3dd59623bda11cf7fa4c1f60a6f" + +normalize-package-data@^2.3.2, normalize-package-data@^2.3.4: + version "2.3.5" + resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.3.5.tgz#8d924f142960e1777e7ffe170543631cc7cb02df" + dependencies: + hosted-git-info "^2.1.4" + is-builtin-module "^1.0.0" + semver "2 || 3 || 4 || 5" + validate-npm-package-license "^3.0.1" + +normalize-path@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.0.1.tgz#47886ac1662760d4261b7d979d241709d3ce3f7a" + +npmlog@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-1.0.0.tgz#ed2f290b60316887c39e0da9f09f8d13847cef0f" + dependencies: + ansi "~0.3.0" + are-we-there-yet "~1.0.0" + gauge "~1.0.2" + +nth-check@~1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-1.0.1.tgz#9929acdf628fc2c41098deab82ac580cf149aae4" + dependencies: + boolbase "~1.0.0" + +nugget@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/nugget/-/nugget-2.0.1.tgz#201095a487e1ad36081b3432fa3cada4f8d071b0" + dependencies: + debug "^2.1.3" + minimist "^1.1.0" + pretty-bytes "^1.0.2" + progress-stream "^1.1.0" + request "^2.45.0" + single-line-log "^1.1.2" + throttleit "0.0.2" + +number-is-nan@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" + +nyc@^8.1.0: + version "8.4.0" + resolved "https://registry.yarnpkg.com/nyc/-/nyc-8.4.0.tgz#660371c807caef0427fb9b0948f74180624ea6e4" + dependencies: + archy "^1.0.0" + arrify "^1.0.1" + caching-transform "^1.0.0" + convert-source-map "^1.3.0" + default-require-extensions "^1.0.0" + find-cache-dir "^0.1.1" + find-up "^1.1.2" + foreground-child "^1.5.3" + glob "^7.0.6" + istanbul-lib-coverage "^1.0.0" + istanbul-lib-hook "^1.0.0-alpha.4" + istanbul-lib-instrument "^1.2.0" + istanbul-lib-report "^1.0.0-alpha.3" + istanbul-lib-source-maps "^1.0.2" + istanbul-reports "^1.0.0" + md5-hex "^1.2.0" + micromatch "^2.3.11" + mkdirp "^0.5.0" + resolve-from "^2.0.0" + rimraf "^2.5.4" + signal-exit "^3.0.1" + spawn-wrap "^1.2.4" + test-exclude "^2.1.3" + yargs "^6.0.0" + yargs-parser "^4.0.2" + +oauth-sign@~0.8.1: + version "0.8.2" + resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43" + +object-assign@^4.0.1, object-assign@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.0.tgz#7a3b3d0e98063d43f4c03f2e8ae6cd51a86883a0" + +object-keys@~0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-0.4.0.tgz#28a6aae7428dd2c3a92f3d95f21335dd204e0336" + +object.omit@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-2.0.1.tgz#1a9c744829f39dbb858c76ca3579ae2a54ebd1fa" + dependencies: + for-own "^0.1.4" + is-extendable "^0.1.1" + +once@^1.3.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + dependencies: + wrappy "1" + +onetime@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/onetime/-/onetime-1.1.0.tgz#a1f7838f8314c516f05ecefcbc4ccfe04b4ed789" + +optimist@^0.6.1, optimist@0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" + dependencies: + minimist "~0.0.1" + wordwrap "~0.0.2" + +optimist@~0.3, optimist@~0.3.5: + version "0.3.7" + resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.3.7.tgz#c90941ad59e4273328923074d2cf2e7cbc6ec0d9" + dependencies: + wordwrap "~0.0.2" + +optionator@^0.8.2: + version "0.8.2" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64" + dependencies: + deep-is "~0.1.3" + fast-levenshtein "~2.0.4" + levn "~0.3.0" + prelude-ls "~1.1.2" + type-check "~0.3.2" + wordwrap "~1.0.0" + +os-homedir@^1.0.0, os-homedir@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" + +os-locale@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz#20f9f17ae29ed345e8bde583b13d2009803c14d9" + dependencies: + lcid "^1.0.0" + +os-tmpdir@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" + +"over@>= 0.0.5 < 1": + version "0.0.5" + resolved "https://registry.yarnpkg.com/over/-/over-0.0.5.tgz#f29852e70fd7e25f360e013a8ec44c82aedb5708" + +parse-glob@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c" + dependencies: + glob-base "^0.3.0" + is-dotfile "^1.0.0" + is-extglob "^1.0.0" + is-glob "^2.0.0" + +parse-json@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" + dependencies: + error-ex "^1.2.0" + +path-exists@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b" + dependencies: + pinkie-promise "^2.0.0" + +path-is-absolute@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + +path-is-inside@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53" + +path-parse@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1" + +path-type@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441" + dependencies: + graceful-fs "^4.1.2" + pify "^2.0.0" + pinkie-promise "^2.0.0" + +pause-stream@0.0.11: + version "0.0.11" + resolved "https://registry.yarnpkg.com/pause-stream/-/pause-stream-0.0.11.tgz#fe5a34b0cbce12b5aa6a2b403ee2e73b602f1445" + dependencies: + through "~2.3" + +performance-now@~0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-0.2.0.tgz#33ef30c5c77d4ea21c5a53869d91b56d8f2555e5" + +pify@^2.0.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" + +pinkie-promise@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" + dependencies: + pinkie "^2.0.0" + +pinkie@^2.0.0: + version "2.0.4" + resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" + +pkg-dir@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-1.0.0.tgz#7a4b508a8d5bb2d629d447056ff4e9c9314cf3d4" + dependencies: + find-up "^1.0.0" + +pluralize@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-1.2.1.tgz#d1a21483fd22bb41e58a12fa3421823140897c45" + +prelude-ls@~1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" + +preserve@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" + +pretty-bytes@^1.0.2: + version "1.0.4" + resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-1.0.4.tgz#0a22e8210609ad35542f8c8d5d2159aff0751c84" + dependencies: + get-stdin "^4.0.1" + meow "^3.1.0" + +private@^0.1.6: + version "0.1.6" + resolved "https://registry.yarnpkg.com/private/-/private-0.1.6.tgz#55c6a976d0f9bafb9924851350fe47b9b5fbb7c1" + +process-nextick-args@~1.0.6: + version "1.0.7" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3" + +progress-stream@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/progress-stream/-/progress-stream-1.2.0.tgz#2cd3cfea33ba3a89c9c121ec3347abe9ab125f77" + dependencies: + speedometer "~0.1.2" + through2 "~0.2.3" + +progress@^1.1.8: + version "1.1.8" + resolved "https://registry.yarnpkg.com/progress/-/progress-1.1.8.tgz#e260c78f6161cdd9b0e56cc3e0a85de17c7a57be" + +prr@~0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/prr/-/prr-0.0.0.tgz#1a84b85908325501411853d0081ee3fa86e2926a" + +pseudomap@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" + +"pullstream@>= 0.4.1 < 1": + version "0.4.1" + resolved "https://registry.yarnpkg.com/pullstream/-/pullstream-0.4.1.tgz#d6fb3bf5aed697e831150eb1002c25a3f8ae1314" + dependencies: + over ">= 0.0.5 < 1" + readable-stream "~1.0.31" + setimmediate ">= 1.0.2 < 2" + slice-stream ">= 1.0.0 < 2" + +punycode@^1.4.1: + version "1.4.1" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" + +qs@~6.2.0: + version "6.2.1" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.2.1.tgz#ce03c5ff0935bc1d9d69a9f14cbd18e568d67625" + +qs@~6.3.0: + version "6.3.0" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.3.0.tgz#f403b264f23bc01228c74131b407f18d5ea5d442" + +raf@^3.1.0: + version "3.3.0" + resolved "https://registry.yarnpkg.com/raf/-/raf-3.3.0.tgz#93845eeffc773f8129039f677f80a36044eee2c3" + dependencies: + performance-now "~0.2.0" + +randomatic@^1.1.3: + version "1.1.5" + resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-1.1.5.tgz#5e9ef5f2d573c67bd2b8124ae90b5156e457840b" + dependencies: + is-number "^2.0.2" + kind-of "^3.0.2" + +read-pkg-up@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" + dependencies: + find-up "^1.0.0" + read-pkg "^1.0.0" + +read-pkg@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28" + dependencies: + load-json-file "^1.0.0" + normalize-package-data "^2.3.2" + path-type "^1.0.0" + +"readable-stream@^2.0.0 || ^1.1.13": + version "2.2.2" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.2.2.tgz#a9e6fec3c7dda85f8bb1b3ba7028604556fc825e" + dependencies: + buffer-shims "^1.0.0" + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "~1.0.0" + process-nextick-args "~1.0.6" + string_decoder "~0.10.x" + util-deprecate "~1.0.1" + +"readable-stream@>=1.0.33-1 <1.1.0-0", readable-stream@~1.0.0, readable-stream@~1.0.31: + version "1.0.34" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + +readable-stream@~1.1.9: + version "1.1.14" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + +readable-stream@~2.0.0, readable-stream@~2.0.5: + version "2.0.6" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.0.6.tgz#8f90341e68a53ccc928788dacfcd11b36eb9b78e" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "~1.0.0" + process-nextick-args "~1.0.6" + string_decoder "~0.10.x" + util-deprecate "~1.0.1" + +readable-stream@1.1: + version "1.1.13" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.13.tgz#f6eef764f514c89e2b9e23146a75ba106756d23e" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + +readable-stream@2.1.5: + version "2.1.5" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.1.5.tgz#66fa8b720e1438b364681f2ad1a63c618448c9d0" + dependencies: + buffer-shims "^1.0.0" + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "~1.0.0" + process-nextick-args "~1.0.6" + string_decoder "~0.10.x" + util-deprecate "~1.0.1" + +readline2@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/readline2/-/readline2-1.0.1.tgz#41059608ffc154757b715d9989d199ffbf372e35" + dependencies: + code-point-at "^1.0.0" + is-fullwidth-code-point "^1.0.0" + mute-stream "0.0.5" + +rechoir@^0.6.2: + version "0.6.2" + resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" + dependencies: + resolve "^1.1.6" + +redent@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/redent/-/redent-1.0.0.tgz#cf916ab1fd5f1f16dfb20822dd6ec7f730c2afde" + dependencies: + indent-string "^2.1.0" + strip-indent "^1.0.1" + +regenerator-runtime@^0.9.5: + version "0.9.6" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.9.6.tgz#d33eb95d0d2001a4be39659707c51b0cb71ce029" + +regex-cache@^0.4.2: + version "0.4.3" + resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.3.tgz#9b1a6c35d4d0dfcef5711ae651e8e9d3d7114145" + dependencies: + is-equal-shallow "^0.1.3" + is-primitive "^2.0.0" + +repeat-element@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.2.tgz#ef089a178d1483baae4d93eb98b4f9e4e11d990a" + +repeat-string@^1.5.2: + version "1.6.1" + resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" + +repeating@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" + dependencies: + is-finite "^1.0.0" + +request@^2.34.0, request@^2.45.0, request@^2.65.0: + version "2.78.0" + resolved "https://registry.yarnpkg.com/request/-/request-2.78.0.tgz#e1c8dec346e1c81923b24acdb337f11decabe9cc" + dependencies: + aws-sign2 "~0.6.0" + aws4 "^1.2.1" + caseless "~0.11.0" + combined-stream "~1.0.5" + extend "~3.0.0" + forever-agent "~0.6.1" + form-data "~2.1.1" + har-validator "~2.0.6" + hawk "~3.1.3" + http-signature "~1.1.0" + is-typedarray "~1.0.0" + isstream "~0.1.2" + json-stringify-safe "~5.0.1" + mime-types "~2.1.7" + node-uuid "~1.4.7" + oauth-sign "~0.8.1" + qs "~6.3.0" + stringstream "~0.0.4" + tough-cookie "~2.3.0" + tunnel-agent "~0.4.1" + +request@2.75.0: + version "2.75.0" + resolved "https://registry.yarnpkg.com/request/-/request-2.75.0.tgz#d2b8268a286da13eaa5d01adf5d18cc90f657d93" + dependencies: + aws-sign2 "~0.6.0" + aws4 "^1.2.1" + bl "~1.1.2" + caseless "~0.11.0" + combined-stream "~1.0.5" + extend "~3.0.0" + forever-agent "~0.6.1" + form-data "~2.0.0" + har-validator "~2.0.6" + hawk "~3.1.3" + http-signature "~1.1.0" + is-typedarray "~1.0.0" + isstream "~0.1.2" + json-stringify-safe "~5.0.1" + mime-types "~2.1.7" + node-uuid "~1.4.7" + oauth-sign "~0.8.1" + qs "~6.2.0" + stringstream "~0.0.4" + tough-cookie "~2.3.0" + tunnel-agent "~0.4.1" + +require_optional@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/require_optional/-/require_optional-1.0.0.tgz#52a86137a849728eb60a55533617f8f914f59abf" + dependencies: + resolve-from "^2.0.0" + semver "^5.1.0" + +require-directory@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" + +require-main-filename@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1" + +require-uncached@^1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/require-uncached/-/require-uncached-1.0.3.tgz#4e0d56d6c9662fd31e43011c4b95aa49955421d3" + dependencies: + caller-path "^0.1.0" + resolve-from "^1.0.0" + +requizzle@~0.2.0: + version "0.2.1" + resolved "https://registry.yarnpkg.com/requizzle/-/requizzle-0.2.1.tgz#6943c3530c4d9a7e46f1cddd51c158fc670cdbde" + dependencies: + underscore "~1.6.0" + +resolve-from@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-1.0.1.tgz#26cbfe935d1aeeeabb29bc3fe5aeb01e93d44226" + +resolve-from@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-2.0.0.tgz#9480ab20e94ffa1d9e80a804c7ea147611966b57" + +resolve@^1.1.6: + version "1.1.7" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" + +restore-cursor@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-1.0.1.tgz#34661f46886327fed2991479152252df92daa541" + dependencies: + exit-hook "^1.0.0" + onetime "^1.0.0" + +right-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" + dependencies: + align-text "^0.1.1" + +rimraf@^2.2.8, rimraf@^2.3.3, rimraf@^2.4.3, rimraf@^2.4.4, rimraf@^2.5.4, rimraf@2, rimraf@2.5.4: + version "2.5.4" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.5.4.tgz#96800093cbf1a0c86bd95b4625467535c29dfa04" + dependencies: + glob "^7.0.5" + +rimraf@2.2.6: + version "2.2.6" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.6.tgz#c59597569b14d956ad29cacc42bdddf5f0ea4f4c" + +run-async@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/run-async/-/run-async-0.1.0.tgz#c8ad4a5e110661e402a7d21b530e009f25f8e389" + dependencies: + once "^1.3.0" + +rx-lite@^3.1.2: + version "3.1.2" + resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-3.1.2.tgz#19ce502ca572665f3b647b10939f97fd1615f102" + +semver@^5.0.1, semver@^5.0.3, semver@^5.1.0, semver@^5.3.0, "semver@2 || 3 || 4 || 5", semver@5.3.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f" + +semver@~5.1.0: + version "5.1.1" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.1.1.tgz#a3292a373e6f3e0798da0b20641b9a9c5bc47e19" + +set-blocking@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" + +"setimmediate@>= 1.0.1 < 2", "setimmediate@>= 1.0.2 < 2": + version "1.0.5" + resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" + +shelljs@^0.7.5: + version "0.7.5" + resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.7.5.tgz#2eef7a50a21e1ccf37da00df767ec69e30ad0675" + dependencies: + glob "^7.0.0" + interpret "^1.0.0" + rechoir "^0.6.2" + +signal-exit@^2.0.0: + version "2.1.2" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-2.1.2.tgz#375879b1f92ebc3b334480d038dc546a6d558564" + +signal-exit@^3.0.0, signal-exit@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.1.tgz#5a4c884992b63a7acd9badb7894c3ee9cfccad81" + +single-line-log@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/single-line-log/-/single-line-log-1.1.2.tgz#c2f83f273a3e1a16edb0995661da0ed5ef033364" + dependencies: + string-width "^1.0.1" + +slash@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/slash/-/slash-1.0.0.tgz#c41f2f6c39fc16d1cd17ad4b5d896114ae470d55" + +slice-ansi@0.0.4: + version "0.0.4" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-0.0.4.tgz#edbf8903f66f7ce2f8eafd6ceed65e264c831b35" + +"slice-stream@>= 1.0.0 < 2": + version "1.0.0" + resolved "https://registry.yarnpkg.com/slice-stream/-/slice-stream-1.0.0.tgz#5b33bd66f013b1a7f86460b03d463dec39ad3ea0" + dependencies: + readable-stream "~1.0.31" + +slide@^1.1.5: + version "1.1.6" + resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707" + +sntp@1.x.x: + version "1.0.9" + resolved "https://registry.yarnpkg.com/sntp/-/sntp-1.0.9.tgz#6541184cc90aeea6c6e7b35e2659082443c66198" + dependencies: + hoek "2.x.x" + +source-map-support@^0.4.2: + version "0.4.6" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.4.6.tgz#32552aa64b458392a85eab3b0b5ee61527167aeb" + dependencies: + source-map "^0.5.3" + +source-map@^0.4.4: + version "0.4.4" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" + dependencies: + amdefine ">=0.0.4" + +source-map@^0.5.0, source-map@^0.5.3, source-map@~0.5.1: + version "0.5.6" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.6.tgz#75ce38f52bf0733c5a7f0c118d81334a2bb5f412" + +source-map@~0.1.30, source-map@~0.1.7: + version "0.1.43" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.1.43.tgz#c24bc146ca517c1471f5dacbe2571b2b7f9e3346" + dependencies: + amdefine ">=0.0.4" + +spawn-wrap@^1.2.4: + version "1.2.4" + resolved "https://registry.yarnpkg.com/spawn-wrap/-/spawn-wrap-1.2.4.tgz#920eb211a769c093eebfbd5b0e7a5d2e68ab2e40" + dependencies: + foreground-child "^1.3.3" + mkdirp "^0.5.0" + os-homedir "^1.0.1" + rimraf "^2.3.3" + signal-exit "^2.0.0" + which "^1.2.4" + +spdx-correct@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-1.0.2.tgz#4b3073d933ff51f3912f03ac5519498a4150db40" + dependencies: + spdx-license-ids "^1.0.2" + +spdx-expression-parse@~1.0.0: + version "1.0.4" + resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz#9bdf2f20e1f40ed447fbe273266191fced51626c" + +spdx-license-ids@^1.0.2: + version "1.2.2" + resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz#c9df7a3424594ade6bd11900d596696dc06bac57" + +speedometer@~0.1.2: + version "0.1.4" + resolved "https://registry.yarnpkg.com/speedometer/-/speedometer-0.1.4.tgz#9876dbd2a169d3115402d48e6ea6329c8816a50d" + +split@0.3: + version "0.3.3" + resolved "https://registry.yarnpkg.com/split/-/split-0.3.3.tgz#cd0eea5e63a211dfff7eb0f091c4133e2d0dd28f" + dependencies: + through "2" + +split2@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/split2/-/split2-0.2.1.tgz#02ddac9adc03ec0bb78c1282ec079ca6e85ae900" + dependencies: + through2 "~0.6.1" + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + +sshpk@^1.7.0: + version "1.10.1" + resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.10.1.tgz#30e1a5d329244974a1af61511339d595af6638b0" + dependencies: + asn1 "~0.2.3" + assert-plus "^1.0.0" + dashdash "^1.12.0" + getpass "^0.1.1" + optionalDependencies: + bcrypt-pbkdf "^1.0.0" + ecc-jsbn "~0.1.1" + jodid25519 "^1.0.0" + jsbn "~0.1.0" + tweetnacl "~0.14.0" + +stream-combiner@~0.0.4: + version "0.0.4" + resolved "https://registry.yarnpkg.com/stream-combiner/-/stream-combiner-0.0.4.tgz#4d5e433c185261dde623ca3f44c586bcf5c4ad14" + dependencies: + duplexer "~0.1.1" + +string_decoder@~0.10.x: + version "0.10.31" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" + +string-width@^1.0.1, string-width@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" + dependencies: + code-point-at "^1.0.0" + is-fullwidth-code-point "^1.0.0" + strip-ansi "^3.0.0" + +string-width@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.0.0.tgz#635c5436cc72a6e0c387ceca278d4e2eec52687e" + dependencies: + is-fullwidth-code-point "^2.0.0" + strip-ansi "^3.0.0" + +stringstream@~0.0.4: + version "0.0.5" + resolved "https://registry.yarnpkg.com/stringstream/-/stringstream-0.0.5.tgz#4e484cd4de5a0bbbee18e46307710a8a81621878" + +strip-ansi@^3.0.0, strip-ansi@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + dependencies: + ansi-regex "^2.0.0" + +strip-bom@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" + dependencies: + is-utf8 "^0.2.0" + +strip-bom@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" + +strip-indent@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-1.0.1.tgz#0c7962a6adefa7bbd4ac366460a638552ae1a0a2" + dependencies: + get-stdin "^4.0.1" + +strip-json-comments@~1.0.1, strip-json-comments@~1.0.2: + version "1.0.4" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-1.0.4.tgz#1e15fbcac97d3ee99bf2d73b4c656b082bbafb91" + +supports-color@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" + +supports-color@^3.1.2: + version "3.1.2" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.1.2.tgz#72a262894d9d408b956ca05ff37b2ed8a6e2a2d5" + dependencies: + has-flag "^1.0.0" + +table@^3.7.4, table@^3.7.8: + version "3.8.3" + resolved "https://registry.yarnpkg.com/table/-/table-3.8.3.tgz#2bbc542f0fda9861a755d3947fefd8b3f513855f" + dependencies: + ajv "^4.7.0" + ajv-keywords "^1.0.0" + chalk "^1.1.1" + lodash "^4.0.0" + slice-ansi "0.0.4" + string-width "^2.0.0" + +"taffydb@https://github.com/hegemonic/taffydb/tarball/7d100bcee0e997ee4977e273cdce60bd8933050e": + version "2.6.2" + resolved "https://github.com/hegemonic/taffydb/tarball/7d100bcee0e997ee4977e273cdce60bd8933050e#3c549d2f5712d7d1d109ad6bb1a4084f1b7add4e" + +tar@~2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.1.tgz#8e4d2a256c0e2185c6b18ad694aec968b83cb1d1" + dependencies: + block-stream "*" + fstream "^1.0.2" + inherits "2" + +test-exclude@^2.1.3: + version "2.1.3" + resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-2.1.3.tgz#a8d8968e1da83266f9864f2852c55e220f06434a" + dependencies: + arrify "^1.0.1" + micromatch "^2.3.11" + object-assign "^4.1.0" + read-pkg-up "^1.0.1" + require-main-filename "^1.0.1" + +text-table@~0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" + +throttleit@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/throttleit/-/throttleit-0.0.2.tgz#cfedf88e60c00dd9697b61fdd2a8343a9b680eaf" + +through@^2.3.6, "through@>=2.2.7 <3", through@~2.3, through@~2.3.1, through@2: + version "2.3.8" + resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" + +through2@^0.6.1, through2@^0.6.3, through2@~0.6.1: + version "0.6.5" + resolved "https://registry.yarnpkg.com/through2/-/through2-0.6.5.tgz#41ab9c67b29d57209071410e1d7a7a968cd3ad48" + dependencies: + readable-stream ">=1.0.33-1 <1.1.0-0" + xtend ">=4.0.0 <4.1.0-0" + +through2@~0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/through2/-/through2-0.2.3.tgz#eb3284da4ea311b6cc8ace3653748a52abf25a3f" + dependencies: + readable-stream "~1.1.9" + xtend "~2.1.1" + +tildify@~1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/tildify/-/tildify-1.2.0.tgz#dcec03f55dca9b7aa3e5b04f21817eb56e63588a" + dependencies: + os-homedir "^1.0.0" + +to-fast-properties@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.2.tgz#f3f5c0c3ba7299a7ef99427e44633257ade43320" + +tough-cookie@~2.3.0: + version "2.3.2" + resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.2.tgz#f081f76e4c85720e6c37a5faced737150d84072a" + dependencies: + punycode "^1.4.1" + +"traverse@>=0.3.0 <0.4": + version "0.3.9" + resolved "https://registry.yarnpkg.com/traverse/-/traverse-0.3.9.tgz#717b8f220cc0bb7b44e40514c22b2e8bbc70d8b9" + +trim-newlines@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613" + +tryit@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/tryit/-/tryit-1.0.3.tgz#393be730a9446fd1ead6da59a014308f36c289cb" + +tunnel-agent@~0.4.1: + version "0.4.3" + resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.4.3.tgz#6373db76909fe570e08d73583365ed828a74eeeb" + +tweetnacl@^0.14.3, tweetnacl@~0.14.0: + version "0.14.3" + resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.3.tgz#3da382f670f25ded78d7b3d1792119bca0b7132d" + +type-check@~0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" + dependencies: + prelude-ls "~1.1.2" + +typedarray@~0.0.5: + version "0.0.6" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + +uglify-js@^2.6: + version "2.7.4" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.7.4.tgz#a295a0de12b6a650c031c40deb0dc40b14568bd2" + dependencies: + async "~0.2.6" + source-map "~0.5.1" + uglify-to-browserify "~1.0.0" + yargs "~3.10.0" + +uglify-js@~2.3: + version "2.3.6" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.3.6.tgz#fa0984770b428b7a9b2a8058f46355d14fef211a" + dependencies: + async "~0.2.6" + optimist "~0.3.5" + source-map "~0.1.7" + +uglify-to-browserify@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" + +underscore-contrib@~0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/underscore-contrib/-/underscore-contrib-0.3.0.tgz#665b66c24783f8fa2b18c9f8cbb0e2c7d48c26c7" + dependencies: + underscore "1.6.0" + +underscore@~1.6.0, underscore@1.6.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.6.0.tgz#8b38b10cacdef63337b8b24e4ff86d45aea529a8" + +underscore@~1.8.3: + version "1.8.3" + resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.8.3.tgz#4f3fb53b106e6097fcf9cb4109f2a5e9bdfa5022" + +untildify@~2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/untildify/-/untildify-2.1.0.tgz#17eb2807987f76952e9c0485fc311d06a826a2e0" + dependencies: + os-homedir "^1.0.0" + +unzip@^0.1.11: + version "0.1.11" + resolved "https://registry.yarnpkg.com/unzip/-/unzip-0.1.11.tgz#89749c63b058d7d90d619f86b98aa1535d3b97f0" + dependencies: + binary ">= 0.3.0 < 1" + fstream ">= 0.1.30 < 1" + match-stream ">= 0.0.2 < 1" + pullstream ">= 0.4.1 < 1" + readable-stream "~1.0.31" + setimmediate ">= 1.0.1 < 2" + +user-home@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/user-home/-/user-home-2.0.0.tgz#9c70bfd8169bc1dcbf48604e0f04b8b49cde9e9f" + dependencies: + os-homedir "^1.0.0" + +util-deprecate@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + +validate-npm-package-license@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz#2804babe712ad3379459acfbe24746ab2c303fbc" + dependencies: + spdx-correct "~1.0.0" + spdx-expression-parse "~1.0.0" + +verror@1.3.6: + version "1.3.6" + resolved "https://registry.yarnpkg.com/verror/-/verror-1.3.6.tgz#cff5df12946d297d2baaefaa2689e25be01c005c" + dependencies: + extsprintf "1.0.2" + +which-module@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/which-module/-/which-module-1.0.0.tgz#bba63ca861948994ff307736089e3b96026c2a4f" + +which@^1.1.1, which@^1.2.4, which@^1.2.9: + version "1.2.12" + resolved "https://registry.yarnpkg.com/which/-/which-1.2.12.tgz#de67b5e450269f194909ef23ece4ebe416fa1192" + dependencies: + isexe "^1.1.1" + +window-size@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.2.0.tgz#b4315bb4214a3d7058ebeee892e13fa24d98b075" + +window-size@0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" + +wordwrap@~0.0.2: + version "0.0.3" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" + +wordwrap@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" + +wordwrap@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" + +worker-farm@^1.3.1: + version "1.3.1" + resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.3.1.tgz#4333112bb49b17aa050b87895ca6b2cacf40e5ff" + dependencies: + errno ">=0.1.1 <0.2.0-0" + xtend ">=4.0.0 <4.1.0-0" + +wrap-ansi@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.0.0.tgz#7d30f8f873f9a5bbc3a64dabc8d177e071ae426f" + dependencies: + string-width "^1.0.1" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + +wrench@~1.5.8: + version "1.5.9" + resolved "https://registry.yarnpkg.com/wrench/-/wrench-1.5.9.tgz#411691c63a9b2531b1700267279bdeca23b2142a" + +write-file-atomic@^1.1.4: + version "1.2.0" + resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-1.2.0.tgz#14c66d4e4cb3ca0565c28cf3b7a6f3e4d5938fab" + dependencies: + graceful-fs "^4.1.2" + imurmurhash "^0.1.4" + slide "^1.1.5" + +write@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/write/-/write-0.2.1.tgz#5fc03828e264cea3fe91455476f7a3c566cb0757" + dependencies: + mkdirp "^0.5.1" + +xtend@^4.0.0, "xtend@>=4.0.0 <4.1.0-0": + version "4.0.1" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af" + +xtend@~2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-2.1.2.tgz#6efecc2a4dad8e6962c4901b337ce7ba87b5d28b" + dependencies: + object-keys "~0.4.0" + +y18n@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41" + +yallist@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.0.0.tgz#306c543835f09ee1a4cb23b7bce9ab341c91cdd4" + +yargs-parser@^4.0.2, yargs-parser@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-4.1.0.tgz#313df030f20124124aeae8fbab2da53ec28c56d7" + dependencies: + camelcase "^3.0.0" + +yargs@^6.0.0: + version "6.4.0" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-6.4.0.tgz#816e1a866d5598ccf34e5596ddce22d92da490d4" + dependencies: + camelcase "^3.0.0" + cliui "^3.2.0" + decamelize "^1.1.1" + get-caller-file "^1.0.1" + os-locale "^1.4.0" + read-pkg-up "^1.0.1" + require-directory "^2.1.1" + require-main-filename "^1.0.1" + set-blocking "^2.0.0" + string-width "^1.0.2" + which-module "^1.0.0" + window-size "^0.2.0" + y18n "^3.2.1" + yargs-parser "^4.1.0" + +yargs@~3.10.0: + version "3.10.0" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" + dependencies: + camelcase "^1.0.2" + cliui "^2.1.0" + decamelize "^1.0.0" + window-size "0.1.0" + |