Created
April 18, 2013 16:20
-
-
Save develar/5414059 to your computer and use it in GitHub Desktop.
ef
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/home/sebastian/.local/bin/node --debug-brk=53438 --trace_debug_json server/app.js | |
debugger listening on port 53438 | |
{"seq":894,"type":"request","command":"version"} | |
{"seq":0,"request_seq":894,"type":"response","command":"version","success":true,"body":{"V8Version":"3.14.5.8"},"refs":[],"running":false} | |
{"seq":895,"type":"request","command":"backtrace","arguments":{"inlineRefs":true}} | |
{"seq":1,"request_seq":895,"type":"response","command":"backtrace","success":true,"body":{"fromFrame":0,"toFrame":7,"totalFrames":7,"frames":[{"type":"frame","index":0,"receiver":{"ref":0,"type":"object","className":"Object"},"func":{"ref":1,"type":"function","name":"","inferredName":"","scriptId":33},"script":{"ref":3},"constructCall":false,"atReturn":false,"debuggerFrame":false,"arguments":[{"name":"exports","value":{"ref":0,"type":"object","className":"Object"}},{"name":"require","value":{"ref":4,"type":"function","name":"require","inferredName":"","scriptId":23}},{"name":"module","value":{"ref":7,"type":"object","className":"Object"}},{"name":"__filename","value":{"ref":8,"type":"string","value":"/mnt/raid/var/www/tests/filestop/server/app.js"}},{"name":"__dirname","value":{"ref":9,"type":"string","value":"/mnt/raid/var/www/tests/filestop/server"}}],"locals":[{"name":"foo","value":{"ref":10,"type":"undefined"}}],"position":62,"line":0,"column":62,"sourceLineText":"(function (exports, require, module, __filename, __dirname) { var foo = \"ff\";","scopes":[{"type":1,"index":0},{"type":0,"index":1}],"text":"#00 #<Object>.[anonymous](exports=#<Object>, require=function require(path) {\n return self.require(path);\n }, module=#<Module>, __filename=/mnt/raid/var/www/tests/filestop/server/app.js, __dirname=/mnt/raid/var/www/tests/filestop/server) /mnt/raid/var/www/tests/filestop/server/app.js line 1 column 63 (position 63)"},{"type":"frame","index":1,"receiver":{"ref":7,"type":"object","className":"Object"},"func":{"ref":15,"type":"function","name":"","inferredName":"Module._compile","scriptId":23},"script":{"ref":6},"constructCall":false,"atReturn":false,"debuggerFrame":false,"arguments":[{"name":"content","value":{"ref":16,"type":"string","value":"var foo = \"ff\";\nconsole.log(foo)"}},{"name":"filename","value":{"ref":8,"type":"string","value":"/mnt/raid/var/www/tests/filestop/server/app.js"}}],"locals":[{"name":"require","value":{"ref":4,"type":"function","name":"require","inferredName":"","scriptId":23}},{"name":"dirname","value":{"ref":9,"type":"string","value":"/mnt/raid/var/www/tests/filestop/server"}},{"name":"sandbox","value":{"ref":10,"type":"undefined"}},{"name":"k","value":{"ref":10,"type":"undefined"}},{"name":"wrapper","value":{"ref":17,"type":"string","value":"(function (exports, require, module, __filename, __dirname) { var foo = \"ff\";\nco... (length: 98)"}},{"name":"compiledWrapper","value":{"ref":1,"type":"function","name":"","inferredName":"","scriptId":33}},{"name":"args","value":{"ref":18,"type":"object","className":"Array"}},{"name":"self","value":{"ref":7,"type":"object","className":"Object"}}],"position":12854,"line":455,"column":25,"sourceLineText":" return compiledWrapper.apply(self.exports, args);","scopes":[{"type":1,"index":0},{"type":3,"index":1},{"type":0,"index":2}],"text":"#01 #<Module>._compile(content=var foo = \"ff\";\nconsole.log(foo), filename=/mnt/raid/var/www/tests/filestop/server/app.js) module.js line 456 column 26 (position 12855)"},{"type":"frame","index":2,"receiver":{"ref":20,"type":"object","className":"Object"},"func":{"ref":21,"type":"function","name":"","inferredName":"Module._extensions..js","scriptId":23},"script":{"ref":6},"constructCall":false,"atReturn":false,"debuggerFrame":false,"arguments":[{"name":"module","value":{"ref":7,"type":"object","className":"Object"}},{"name":"filename","value":{"ref":8,"type":"string","value":"/mnt/raid/var/www/tests/filestop/server/app.js"}}],"locals":[{"name":"content","value":{"ref":16,"type":"string","value":"var foo = \"ff\";\nconsole.log(foo)"}}],"position":13365,"line":473,"column":9,"sourceLineText":" module._compile(stripBOM(content), filename);","scopes":[{"type":1,"index":0},{"type":3,"index":1},{"type":0,"index":2}],"text":"#02 #<Object>..js(module=#<Module>, filename=/mnt/raid/var/www/tests/filestop/server/app.js) module.js line 474 column 10 (position 13366)"},{"type":"frame","index":3,"receiver":{"ref":7,"type":"object","className":"Object"},"func":{"ref":22,"type":"function","name":"","inferredName":"Module.load","scriptId":23},"script":{"ref":6},"constructCall":false,"atReturn":false,"debuggerFrame":false,"arguments":[{"name":"filename","value":{"ref":8,"type":"string","value":"/mnt/raid/var/www/tests/filestop/server/app.js"}}],"locals":[{"name":"extension","value":{"ref":23,"type":"string","value":".js"}}],"position":10114,"line":355,"column":31,"sourceLineText":" Module._extensions[extension](this, filename);","scopes":[{"type":1,"index":0},{"type":3,"index":1},{"type":0,"index":2}],"text":"#03 #<Module>.load(filename=/mnt/raid/var/www/tests/filestop/server/app.js) module.js line 356 column 32 (position 10115)"},{"type":"frame","index":4,"receiver":{"ref":14,"type":"function","name":"Module","inferredName":"","scriptId":23},"func":{"ref":24,"type":"function","name":"","inferredName":"Module._load","scriptId":23},"script":{"ref":6},"constructCall":false,"atReturn":false,"debuggerFrame":false,"arguments":[{"name":"request","value":{"ref":8,"type":"string","value":"/mnt/raid/var/www/tests/filestop/server/app.js"}},{"name":"parent","value":{"ref":13,"type":"null","value":null}},{"name":"isMain","value":{"ref":25,"type":"boolean","value":true}}],"locals":[{"name":"filename","value":{"ref":8,"type":"string","value":"/mnt/raid/var/www/tests/filestop/server/app.js"}},{"name":"cachedModule","value":{"ref":10,"type":"undefined"}},{"name":"replModule","value":{"ref":10,"type":"undefined"}},{"name":"module","value":{"ref":7,"type":"object","className":"Object"}},{"name":"hadException","value":{"ref":25,"type":"boolean","value":true}}],"position":8947,"line":311,"column":11,"sourceLineText":" module.load(filename);","scopes":[{"type":1,"index":0},{"type":3,"index":1},{"type":0,"index":2}],"text":"#04 function Module(id, parent) {\n this.id = id;\n this.exports = {};\n this.parent = parent;\n if (parent && parent.children) {\n parent.children.push(this);\n }\n\n this.filename = null;\n this.loaded = false;\n this.children = [];\n}._load(request=/mnt/raid/var/www/tests/filestop/server/app.js, parent=null, isMain=true) module.js line 312 column 12 (position 8948)"},{"type":"frame","index":5,"receiver":{"ref":27,"type":"object","className":"Object"},"func":{"ref":28,"type":"function","name":"","inferredName":"Module.runMain","scriptId":23},"script":{"ref":6},"constructCall":false,"atReturn":false,"debuggerFrame":false,"arguments":[],"locals":[],"position":13920,"line":496,"column":9,"sourceLineText":" Module._load(process.argv[1], null, true);","scopes":[{"type":1,"index":0},{"type":3,"index":1},{"type":0,"index":2}],"text":"#05 #<Object>._onTimeout() module.js line 497 column 10 (position 13921)"},{"type":"frame","index":6,"receiver":{"ref":31,"type":"object","className":"Timer"},"func":{"ref":32,"type":"function","name":"listOnTimeout","inferredName":"","scriptId":24},"script":{"ref":34},"constructCall":false,"atReturn":false,"debuggerFrame":false,"arguments":[{"value":{"ref":35,"type":"number","value":0}}],"locals":[{"name":"msecs","value":{"ref":36,"type":"number","value":50}},{"name":"now","value":{"ref":37,"type":"number","value":1366302014466}},{"name":"first","value":{"ref":27,"type":"object","className":"Object"}},{"name":"diff","value":{"ref":38,"type":"number","value":51}},{"name":"domain","value":{"ref":10,"type":"undefined"}},{"name":"threw","value":{"ref":25,"type":"boolean","value":true}},{"name":"list","value":{"ref":31,"type":"object","className":"Timer"}}],"position":3529,"line":109,"column":14,"sourceLineText":" first._onTimeout();","scopes":[{"type":1,"index":0},{"type":3,"index":1},{"type":0,"index":2}],"text":"#06 #<Timer>.ontimeout(aka listOnTimeout)(0) timers.js line 110 column 15 (position 3530)"}]},"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/server/app.js","id":33,"lineOffset":0,"columnOffset":0,"lineCount":3,"sourceStart":"(function (exports, require, module, __filename, __dirname) { var foo = \"ff\";\nco","sourceLength":98,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/server/app.js (lines: 3)"},{"handle":6,"type":"script","name":"module.js","id":23,"lineOffset":0,"columnOffset":0,"lineCount":539,"sourceStart":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyen","sourceLength":14908,"scriptType":2,"compilationType":0,"context":{"ref":5},"text":"module.js (lines: 539)"},{"handle":34,"type":"script","name":"timers.js","id":24,"lineOffset":0,"columnOffset":0,"lineCount":364,"sourceStart":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyen","sourceLength":8922,"scriptType":2,"compilationType":0,"context":{"ref":33},"text":"timers.js (lines: 364)"}],"running":false} | |
{"seq":896,"type":"request","command":"setbreakpoint","arguments":{"enabled":true,"target":"^\/[vV][aA][rR]\/[wW][wW][wW]\/[tT][eE][sS][tT][sS]\/[fF][iI][lL][eE][sS][tT][oO][pP]\/[sS][eE][rR][vV][eE][rR]\/[sS][eE][rR][vV][eE][rR]\\.[jJ][sS]([;?#].*)?$","line":8,"type":"scriptRegExp"}} | |
{"seq":2,"request_seq":896,"type":"response","command":"setbreakpoint","success":true,"body":{"type":"scriptRegExp","breakpoint":2,"script_regexp":"^/[vV][aA][rR]/[wW][wW][wW]/[tT][eE][sS][tT][sS]/[fF][iI][lL][eE][sS][tT][oO][pP]/[sS][eE][rR][vV][eE][rR]/[sS][eE][rR][vV][eE][rR]\\.[jJ][sS]([;?#].*)?$","line":8,"column":null,"actual_locations":[]},"refs":[],"running":false} | |
{"seq":897,"type":"request","command":"setbreakpoint","arguments":{"enabled":true,"target":"^\/[vV][aA][rR]\/[wW][wW][wW]\/[tT][eE][sS][tT][sS]\/[fF][iI][lL][eE][sS][tT][oO][pP]\/[sS][eE][rR][vV][eE][rR]\/[sS][eE][rR][vV][eE][rR]\\.[jJ][sS]([;?#].*)?$","line":9,"type":"scriptRegExp"}} | |
{"seq":3,"request_seq":897,"type":"response","command":"setbreakpoint","success":true,"body":{"type":"scriptRegExp","breakpoint":3,"script_regexp":"^/[vV][aA][rR]/[wW][wW][wW]/[tT][eE][sS][tT][sS]/[fF][iI][lL][eE][sS][tT][oO][pP]/[sS][eE][rR][vV][eE][rR]/[sS][eE][rR][vV][eE][rR]\\.[jJ][sS]([;?#].*)?$","line":9,"column":null,"actual_locations":[]},"refs":[],"running":false} | |
{"seq":898,"type":"request","command":"setbreakpoint","arguments":{"enabled":true,"target":"^\/[vV][aA][rR]\/[wW][wW][wW]\/[tT][eE][sS][tT][sS]\/[fF][iI][lL][eE][sS][tT][oO][pP]\/[sS][eE][rR][vV][eE][rR]\/[aA][pP][pP]\\.[jJ][sS]([;?#].*)?$","line":1,"type":"scriptRegExp"}} | |
{"seq":4,"request_seq":898,"type":"response","command":"setbreakpoint","success":true,"body":{"type":"scriptRegExp","breakpoint":4,"script_regexp":"^/[vV][aA][rR]/[wW][wW][wW]/[tT][eE][sS][tT][sS]/[fF][iI][lL][eE][sS][tT][oO][pP]/[sS][eE][rR][vV][eE][rR]/[aA][pP][pP]\\.[jJ][sS]([;?#].*)?$","line":1,"column":null,"actual_locations":[]},"refs":[],"running":false} | |
{"seq":900,"type":"request","command":"scripts","arguments":{"includeSource":true,"types":4}} | |
{"seq":5,"request_seq":900,"type":"response","command":"scripts","success":true,"body":[{"handle":42,"type":"script","name":"node.js","id":17,"lineOffset":0,"columnOffset":0,"lineCount":902,"source":"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Hello, and welcome to hacking node.js!\n//\n// This file is invoked by node::Load in src/node.cc, and responsible for\n// bootstrapping the node.js core. Special caution is given to the performance\n// of the startup process, so many dependencies are invoked lazily.\n(function(process) {\n this.global = this;\n\n function startup() {\n var EventEmitter = NativeModule.require('events').EventEmitter;\n\n process.__proto__ = Object.create(EventEmitter.prototype, {\n constructor: {\n value: process.constructor\n }\n });\n EventEmitter.call(process);\n\n process.EventEmitter = EventEmitter; // process.EventEmitter is deprecated\n\n // do this good and early, since it handles errors.\n startup.processFatal();\n\n startup.globalVariables();\n startup.globalTimeouts();\n startup.globalConsole();\n\n startup.processAssert();\n startup.processConfig();\n startup.processNextTick();\n startup.processStdio();\n startup.processKillAndExit();\n startup.processSignalHandlers();\n\n startup.processChannel();\n\n startup.resolveArgv0();\n\n // There are various modes that Node can run in. The most common two\n // are running from a script and running the REPL - but there are a few\n // others like the debugger or running --eval arguments. Here we decide\n // which mode we run in.\n\n if (NativeModule.exists('_third_party_main')) {\n // To allow people to extend Node in different ways, this hook allows\n // one to drop a file lib/_third_party_main.js into the build\n // directory which will be executed instead of Node's normal loading.\n process.nextTick(function() {\n NativeModule.require('_third_party_main');\n });\n\n } else if (process.argv[1] == 'debug') {\n // Start the debugger agent\n var d = NativeModule.require('_debugger');\n d.start();\n\n } else if (process._eval != null) {\n // User passed '-e' or '--eval' arguments to Node.\n evalScript('[eval]');\n } else if (process.argv[1]) {\n // make process.argv[1] into a full path\n var path = NativeModule.require('path');\n process.argv[1] = path.resolve(process.argv[1]);\n\n // If this is a worker in cluster mode, start up the communiction\n // channel.\n if (process.env.NODE_UNIQUE_ID) {\n var cluster = NativeModule.require('cluster');\n cluster._setupWorker();\n\n // Make sure it's not accidentally inherited by child processes.\n delete process.env.NODE_UNIQUE_ID;\n }\n\n var Module = NativeModule.require('module');\n\n if (global.v8debug &&\n process.execArgv.some(function(arg) {\n return arg.match(/^--debug-brk(=[0-9]*)?$/);\n })) {\n\n // XXX Fix this terrible hack!\n //\n // Give the client program a few ticks to connect.\n // Otherwise, there's a race condition where `node debug foo.js`\n // will not be able to connect in time to catch the first\n // breakpoint message on line 1.\n //\n // A better fix would be to somehow get a message from the\n // global.v8debug object about a connection, and runMain when\n // that occurs. --isaacs\n\n var debugTimeout = +process.env.NODE_DEBUG_TIMEOUT || 50;\n setTimeout(Module.runMain, debugTimeout);\n\n } else {\n // Main entry point into most programs:\n Module.runMain();\n }\n\n } else {\n var Module = NativeModule.require('module');\n\n // If -i or --interactive were passed, or stdin is a TTY.\n if (process._forceRepl || NativeModule.require('tty').isatty(0)) {\n // REPL\n var opts = {\n useGlobal: true,\n ignoreUndefined: false\n };\n if (parseInt(process.env['NODE_NO_READLINE'], 10)) {\n opts.terminal = false;\n }\n if (parseInt(process.env['NODE_DISABLE_COLORS'], 10)) {\n opts.useColors = false;\n }\n var repl = Module.requireRepl().start(opts);\n repl.on('exit', function() {\n process.exit();\n });\n\n } else {\n // Read all of stdin - execute it.\n process.stdin.setEncoding('utf8');\n\n var code = '';\n process.stdin.on('data', function(d) {\n code += d;\n });\n\n process.stdin.on('end', function() {\n process._eval = code;\n evalScript('[stdin]');\n });\n }\n }\n }\n\n startup.globalVariables = function() {\n global.process = process;\n global.global = global;\n global.GLOBAL = global;\n global.root = global;\n global.Buffer = NativeModule.require('buffer').Buffer;\n process.binding('buffer').setFastBufferConstructor(global.Buffer);\n process.domain = null;\n process._exiting = false;\n };\n\n startup.globalTimeouts = function() {\n global.setTimeout = function() {\n var t = NativeModule.require('timers');\n return t.setTimeout.apply(this, arguments);\n };\n\n global.setInterval = function() {\n var t = NativeModule.require('timers');\n return t.setInterval.apply(this, arguments);\n };\n\n global.clearTimeout = function() {\n var t = NativeModule.require('timers');\n return t.clearTimeout.apply(this, arguments);\n };\n\n global.clearInterval = function() {\n var t = NativeModule.require('timers');\n return t.clearInterval.apply(this, arguments);\n };\n\n global.setImmediate = function() {\n var t = NativeModule.require('timers');\n return t.setImmediate.apply(this, arguments);\n };\n\n global.clearImmediate = function() {\n var t = NativeModule.require('timers');\n return t.clearImmediate.apply(this, arguments);\n };\n };\n\n startup.globalConsole = function() {\n global.__defineGetter__('console', function() {\n return NativeModule.require('console');\n });\n };\n\n\n startup._lazyConstants = null;\n\n startup.lazyConstants = function() {\n if (!startup._lazyConstants) {\n startup._lazyConstants = process.binding('constants');\n }\n return startup._lazyConstants;\n };\n\n startup.processFatal = function() {\n // call into the active domain, or emit uncaughtException,\n // and exit if there are no listeners.\n process._fatalException = function(er) {\n var caught = false;\n if (process.domain) {\n var domain = process.domain;\n var domainModule = NativeModule.require('domain');\n var domainStack = domainModule._stack;\n\n // ignore errors on disposed domains.\n //\n // XXX This is a bit stupid. We should probably get rid of\n // domain.dispose() altogether. It's almost always a terrible\n // idea. --isaacs\n if (domain._disposed)\n return true;\n\n er.domain = domain;\n er.domainThrown = true;\n // wrap this in a try/catch so we don't get infinite throwing\n try {\n // One of three things will happen here.\n //\n // 1. There is a handler, caught = true\n // 2. There is no handler, caught = false\n // 3. It throws, caught = false\n //\n // If caught is false after this, then there's no need to exit()\n // the domain, because we're going to crash the process anyway.\n caught = domain.emit('error', er);\n\n // Exit all domains on the stack. Uncaught exceptions end the\n // current tick and no domains should be left on the stack\n // between ticks.\n var domainModule = NativeModule.require('domain');\n domainStack.length = 0;\n domainModule.active = process.domain = null;\n } catch (er2) {\n // The domain error handler threw! oh no!\n // See if another domain can catch THIS error,\n // or else crash on the original one.\n // If the user already exited it, then don't double-exit.\n if (domain === domainModule.active)\n domainStack.pop();\n if (domainStack.length) {\n var parentDomain = domainStack[domainStack.length - 1];\n process.domain = domainModule.active = parentDomain;\n caught = process._fatalException(er2);\n } else\n caught = false;\n }\n } else {\n caught = process.emit('uncaughtException', er);\n }\n // if someone handled it, then great. otherwise, die in C++ land\n // since that means that we'll exit the process, emit the 'exit' event\n if (!caught) {\n try {\n if (!process._exiting) {\n process._exiting = true;\n process.emit('exit', 1);\n }\n } catch (er) {\n // nothing to be done about it at this point.\n }\n }\n // if we handled an error, then make sure any ticks get processed\n if (caught)\n process._needTickCallback();\n return caught;\n };\n };\n\n var assert;\n startup.processAssert = function() {\n // Note that calls to assert() are pre-processed out by JS2C for the\n // normal build of node. They persist only in the node_g build.\n // Similarly for debug().\n assert = process.assert = function(x, msg) {\n if (!x) throw new Error(msg || 'assertion error');\n };\n };\n\n startup.processConfig = function() {\n // used for `process.config`, but not a real module\n var config = NativeModule._source.config;\n delete NativeModule._source.config;\n\n // strip the gyp comment line at the beginning\n config = config.split('\\n').slice(1).join('\\n').replace(/'/g, '\"');\n\n process.config = JSON.parse(config, function(key, value) {\n if (value === 'true') return true;\n if (value === 'false') return false;\n return value;\n });\n };\n\n startup.processNextTick = function() {\n var _needTickCallback = process._needTickCallback;\n var nextTickQueue = [];\n var needSpinner = true;\n var inTick = false;\n\n // this infobox thing is used so that the C++ code in src/node.cc\n // can have easy accesss to our nextTick state, and avoid unnecessary\n // calls into process._tickCallback.\n // order is [length, index, depth]\n // Never write code like this without very good reason!\n var infoBox = process._tickInfoBox;\n var length = 0;\n var index = 1;\n var depth = 2;\n\n process.nextTick = nextTick;\n // needs to be accessible from cc land\n process._nextDomainTick = _nextDomainTick;\n process._tickCallback = _tickCallback;\n process._tickDomainCallback = _tickDomainCallback;\n process._tickFromSpinner = _tickFromSpinner;\n\n // the maximum number of times it'll process something like\n // nextTick(function f(){nextTick(f)})\n // It's unlikely, but not illegal, to hit this limit. When\n // that happens, it yields to libuv's tick spinner.\n // This is a loop counter, not a stack depth, so we aren't using\n // up lots of memory here. I/O can sneak in before nextTick if this\n // limit is hit, which is not ideal, but not terrible.\n process.maxTickDepth = 1000;\n\n function tickDone(tickDepth_) {\n if (infoBox[length] !== 0) {\n if (infoBox[length] <= infoBox[index]) {\n nextTickQueue = [];\n infoBox[length] = 0;\n } else {\n nextTickQueue.splice(0, infoBox[index]);\n infoBox[length] = nextTickQueue.length;\n if (needSpinner) {\n _needTickCallback();\n needSpinner = false;\n }\n }\n }\n inTick = false;\n infoBox[index] = 0;\n infoBox[depth] = tickDepth_;\n }\n\n function maxTickWarn() {\n // XXX Remove all this maxTickDepth stuff in 0.11\n var msg = '(node) warning: Recursive process.nextTick detected. ' +\n 'This will break in the next version of node. ' +\n 'Please use setImmediate for recursive deferral.';\n if (process.throwDeprecation)\n throw new Error(msg);\n else if (process.traceDeprecation)\n console.trace(msg);\n else\n console.error(msg);\n }\n\n function _tickFromSpinner() {\n needSpinner = true;\n // coming from spinner, reset!\n if (infoBox[depth] !== 0)\n infoBox[depth] = 0;\n // no callbacks to run\n if (infoBox[length] === 0)\n return infoBox[index] = infoBox[depth] = 0;\n process._tickCallback();\n }\n\n // run callbacks that have no domain\n // using domains will cause this to be overridden\n function _tickCallback() {\n var callback, nextTickLength, threw;\n\n if (inTick) return;\n if (infoBox[length] === 0) {\n infoBox[index] = 0;\n infoBox[depth] = 0;\n return;\n }\n inTick = true;\n\n while (infoBox[depth]++ < process.maxTickDepth) {\n nextTickLength = infoBox[length];\n if (infoBox[index] === nextTickLength)\n return tickDone(0);\n\n while (infoBox[index] < nextTickLength) {\n callback = nextTickQueue[infoBox[index]++].callback;\n threw = true;\n try {\n callback();\n threw = false;\n } finally {\n if (threw) tickDone(infoBox[depth]);\n }\n }\n }\n\n tickDone(0);\n }\n\n function _tickDomainCallback() {\n var nextTickLength, tock, callback, threw;\n\n // if you add a nextTick in a domain's error handler, then\n // it's possible to cycle indefinitely. Normally, the tickDone\n // in the finally{} block below will prevent this, however if\n // that error handler ALSO triggers multiple MakeCallbacks, then\n // it'll try to keep clearing the queue, since the finally block\n // fires *before* the error hits the top level and is handled.\n if (infoBox[depth] >= process.maxTickDepth)\n return _needTickCallback();\n\n if (inTick) return;\n inTick = true;\n\n // always do this at least once. otherwise if process.maxTickDepth\n // is set to some negative value, or if there were repeated errors\n // preventing depth from being cleared, we'd never process any\n // of them.\n while (infoBox[depth]++ < process.maxTickDepth) {\n nextTickLength = infoBox[length];\n if (infoBox[index] === nextTickLength)\n return tickDone(0);\n\n while (infoBox[index] < nextTickLength) {\n tock = nextTickQueue[infoBox[index]++];\n callback = tock.callback;\n if (tock.domain) {\n if (tock.domain._disposed) continue;\n tock.domain.enter();\n }\n threw = true;\n try {\n callback();\n threw = false;\n } finally {\n // finally blocks fire before the error hits the top level,\n // so we can't clear the depth at this point.\n if (threw) tickDone(infoBox[depth]);\n }\n if (tock.domain) {\n tock.domain.exit();\n }\n }\n }\n\n tickDone(0);\n }\n\n function nextTick(callback) {\n // on the way out, don't bother. it won't get fired anyway.\n if (process._exiting)\n return;\n if (infoBox[depth] >= process.maxTickDepth)\n maxTickWarn();\n\n var obj = { callback: callback, domain: null };\n\n nextTickQueue.push(obj);\n infoBox[length]++;\n\n if (needSpinner) {\n _needTickCallback();\n needSpinner = false;\n }\n }\n\n function _nextDomainTick(callback) {\n // on the way out, don't bother. it won't get fired anyway.\n if (process._exiting)\n return;\n if (infoBox[depth] >= process.maxTickDepth)\n maxTickWarn();\n\n var obj = { callback: callback, domain: process.domain };\n\n nextTickQueue.push(obj);\n infoBox[length]++;\n\n if (needSpinner) {\n _needTickCallback();\n needSpinner = false;\n }\n }\n };\n\n function evalScript(name) {\n var Module = NativeModule.require('module');\n var path = NativeModule.require('path');\n var cwd = process.cwd();\n\n var module = new Module(name);\n module.filename = path.join(cwd, name);\n module.paths = Module._nodeModulePaths(cwd);\n var script = process._eval;\n if (!Module._contextLoad) {\n var body = script;\n script = 'global.__filename = ' + JSON.stringify(name) + ';\\n' +\n 'global.exports = exports;\\n' +\n 'global.module = module;\\n' +\n 'global.__dirname = __dirname;\\n' +\n 'global.require = require;\\n' +\n 'return require(\"vm\").runInThisContext(' +\n JSON.stringify(body) + ', ' +\n JSON.stringify(name) + ', true);\\n';\n }\n var result = module._compile(script, name + '-wrapper');\n if (process._print_eval) console.log(result);\n }\n\n function errnoException(errorno, syscall) {\n // TODO make this more compatible with ErrnoException from src/node.cc\n // Once all of Node is using this function the ErrnoException from\n // src/node.cc should be removed.\n var e = new Error(syscall + ' ' + errorno);\n e.errno = e.code = errorno;\n e.syscall = syscall;\n return e;\n }\n\n function createWritableStdioStream(fd) {\n var stream;\n var tty_wrap = process.binding('tty_wrap');\n\n // Note stream._type is used for test-module-load-list.js\n\n switch (tty_wrap.guessHandleType(fd)) {\n case 'TTY':\n var tty = NativeModule.require('tty');\n stream = new tty.WriteStream(fd);\n stream._type = 'tty';\n\n // Hack to have stream not keep the event loop alive.\n // See https://github.com/joyent/node/issues/1726\n if (stream._handle && stream._handle.unref) {\n stream._handle.unref();\n }\n break;\n\n case 'FILE':\n var fs = NativeModule.require('fs');\n stream = new fs.SyncWriteStream(fd);\n stream._type = 'fs';\n break;\n\n case 'PIPE':\n case 'TCP':\n var net = NativeModule.require('net');\n stream = new net.Socket({\n fd: fd,\n readable: false,\n writable: true\n });\n\n // FIXME Should probably have an option in net.Socket to create a\n // stream from an existing fd which is writable only. But for now\n // we'll just add this hack and set the `readable` member to false.\n // Test: ./node test/fixtures/echo.js < /etc/passwd\n stream.readable = false;\n stream.read = null;\n stream._type = 'pipe';\n\n // FIXME Hack to have stream not keep the event loop alive.\n // See https://github.com/joyent/node/issues/1726\n if (stream._handle && stream._handle.unref) {\n stream._handle.unref();\n }\n break;\n\n default:\n // Probably an error on in uv_guess_handle()\n throw new Error('Implement me. Unknown stream file type!');\n }\n\n // For supporting legacy API we put the FD here.\n stream.fd = fd;\n\n stream._isStdio = true;\n\n return stream;\n }\n\n startup.processStdio = function() {\n var stdin, stdout, stderr;\n\n process.__defineGetter__('stdout', function() {\n if (stdout) return stdout;\n stdout = createWritableStdioStream(1);\n stdout.destroy = stdout.destroySoon = function(er) {\n er = er || new Error('process.stdout cannot be closed.');\n stdout.emit('error', er);\n };\n if (stdout.isTTY) {\n process.on('SIGWINCH', function() {\n stdout._refreshSize();\n });\n }\n return stdout;\n });\n\n process.__defineGetter__('stderr', function() {\n if (stderr) return stderr;\n stderr = createWritableStdioStream(2);\n stderr.destroy = stderr.destroySoon = function(er) {\n er = er || new Error('process.stderr cannot be closed.');\n stderr.emit('error', er);\n };\n return stderr;\n });\n\n process.__defineGetter__('stdin', function() {\n if (stdin) return stdin;\n\n var tty_wrap = process.binding('tty_wrap');\n var fd = 0;\n\n switch (tty_wrap.guessHandleType(fd)) {\n case 'TTY':\n var tty = NativeModule.require('tty');\n stdin = new tty.ReadStream(fd, {\n highWaterMark: 0,\n readable: true,\n writable: false\n });\n break;\n\n case 'FILE':\n var fs = NativeModule.require('fs');\n stdin = new fs.ReadStream(null, { fd: fd });\n break;\n\n case 'PIPE':\n case 'TCP':\n var net = NativeModule.require('net');\n stdin = new net.Socket({\n fd: fd,\n readable: true,\n writable: false\n });\n break;\n\n default:\n // Probably an error on in uv_guess_handle()\n throw new Error('Implement me. Unknown stdin file type!');\n }\n\n // For supporting legacy API we put the FD here.\n stdin.fd = fd;\n\n // stdin starts out life in a paused state, but node doesn't\n // know yet. Explicitly to readStop() it to put it in the\n // not-reading state.\n if (stdin._handle && stdin._handle.readStop) {\n stdin._handle.reading = false;\n stdin._readableState.reading = false;\n stdin._handle.readStop();\n }\n\n // if the user calls stdin.pause(), then we need to stop reading\n // immediately, so that the process can close down.\n stdin.on('pause', function() {\n if (!stdin._handle)\n return;\n stdin._readableState.reading = false;\n stdin._handle.reading = false;\n stdin._handle.readStop();\n });\n\n return stdin;\n });\n\n process.openStdin = function() {\n process.stdin.resume();\n return process.stdin;\n };\n };\n\n startup.processKillAndExit = function() {\n process.exit = function(code) {\n if (!process._exiting) {\n process._exiting = true;\n process.emit('exit', code || 0);\n }\n process.reallyExit(code || 0);\n };\n\n process.kill = function(pid, sig) {\n var r;\n\n // preserve null signal\n if (0 === sig) {\n r = process._kill(pid, 0);\n } else {\n sig = sig || 'SIGTERM';\n if (startup.lazyConstants()[sig]) {\n r = process._kill(pid, startup.lazyConstants()[sig]);\n } else {\n throw new Error('Unknown signal: ' + sig);\n }\n }\n\n if (r) {\n throw errnoException(process._errno, 'kill');\n }\n\n return true;\n };\n };\n\n startup.processSignalHandlers = function() {\n // Load events module in order to access prototype elements on process like\n // process.addListener.\n var signalWraps = {};\n var addListener = process.addListener;\n var removeListener = process.removeListener;\n\n function isSignal(event) {\n return event.slice(0, 3) === 'SIG' &&\n startup.lazyConstants().hasOwnProperty(event);\n }\n\n // Wrap addListener for the special signal types\n process.on = process.addListener = function(type, listener) {\n if (isSignal(type) &&\n !signalWraps.hasOwnProperty(type)) {\n var Signal = process.binding('signal_wrap').Signal;\n var wrap = new Signal();\n\n wrap.unref();\n\n wrap.onsignal = function() { process.emit(type); };\n\n var signum = startup.lazyConstants()[type];\n var r = wrap.start(signum);\n if (r) {\n wrap.close();\n throw errnoException(process._errno, 'uv_signal_start');\n }\n\n signalWraps[type] = wrap;\n }\n\n return addListener.apply(this, arguments);\n };\n\n process.removeListener = function(type, listener) {\n var ret = removeListener.apply(this, arguments);\n if (isSignal(type)) {\n assert(signalWraps.hasOwnProperty(type));\n\n if (this.listeners(type).length === 0) {\n signalWraps[type].close();\n delete signalWraps[type];\n }\n }\n\n return ret;\n };\n };\n\n\n startup.processChannel = function() {\n // If we were spawned with env NODE_CHANNEL_FD then load that up and\n // start parsing data from that stream.\n if (process.env.NODE_CHANNEL_FD) {\n var fd = parseInt(process.env.NODE_CHANNEL_FD, 10);\n assert(fd >= 0);\n\n // Make sure it's not accidentally inherited by child processes.\n delete process.env.NODE_CHANNEL_FD;\n\n var cp = NativeModule.require('child_process');\n\n // Load tcp_wrap to avoid situation where we might immediately receive\n // a message.\n // FIXME is this really necessary?\n process.binding('tcp_wrap');\n\n cp._forkChild(fd);\n assert(process.send);\n }\n }\n\n startup.resolveArgv0 = function() {\n var cwd = process.cwd();\n var isWindows = process.platform === 'win32';\n\n // Make process.argv[0] into a full path, but only touch argv[0] if it's\n // not a system $PATH lookup.\n // TODO: Make this work on Windows as well. Note that \"node\" might\n // execute cwd\\node.exe, or some %PATH%\\node.exe on Windows,\n // and that every directory has its own cwd, so d:node.exe is valid.\n var argv0 = process.argv[0];\n if (!isWindows && argv0.indexOf('/') !== -1 && argv0.charAt(0) !== '/') {\n var path = NativeModule.require('path');\n process.argv[0] = path.join(cwd, process.argv[0]);\n }\n };\n\n // Below you find a minimal module system, which is used to load the node\n // core modules found in lib/*.js. All core modules are compiled into the\n // node binary, so they can be loaded faster.\n\n var Script = process.binding('evals').NodeScript;\n var runInThisContext = Script.runInThisContext;\n\n function NativeModule(id) {\n this.filename = id + '.js';\n this.id = id;\n this.exports = {};\n this.loaded = false;\n }\n\n NativeModule._source = process.binding('natives');\n NativeModule._cache = {};\n\n NativeModule.require = function(id) {\n if (id == 'native_module') {\n return NativeModule;\n }\n\n var cached = NativeModule.getCached(id);\n if (cached) {\n return cached.exports;\n }\n\n if (!NativeModule.exists(id)) {\n throw new Error('No such native module ' + id);\n }\n\n process.moduleLoadList.push('NativeModule ' + id);\n\n var nativeModule = new NativeModule(id);\n\n nativeModule.cache();\n nativeModule.compile();\n\n return nativeModule.exports;\n };\n\n NativeModule.getCached = function(id) {\n return NativeModule._cache[id];\n }\n\n NativeModule.exists = function(id) {\n return NativeModule._source.hasOwnProperty(id);\n }\n\n NativeModule.getSource = function(id) {\n return NativeModule._source[id];\n }\n\n NativeModule.wrap = function(script) {\n return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];\n };\n\n NativeModule.wrapper = [\n '(function (exports, require, module, __filename, __dirname) { ',\n '\\n});'\n ];\n\n NativeModule.prototype.compile = function() {\n var source = NativeModule.getSource(this.id);\n source = NativeModule.wrap(source);\n\n var fn = runInThisContext(source, this.filename, true);\n fn(this.exports, NativeModule.require, this, this.filename);\n\n this.loaded = true;\n };\n\n NativeModule.prototype.cache = function() {\n NativeModule._cache[this.id] = this;\n };\n\n startup();\n});\n","sourceLength":28054,"scriptType":2,"compilationType":0,"context":{"ref":41},"text":"node.js (lines: 902)"},{"handle":44,"type":"script","name":"path.js","id":22,"lineOffset":0,"columnOffset":0,"lineCount":489,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\nvar isWindows = process.platform === 'win32';\nvar util = require('util');\n\n\n// resolves . and .. elements in a path array with directory names there\n// must be no slashes, empty elements, or device names (c:\\) in the array\n// (so also no leading and trailing slashes - it does not distinguish\n// relative and absolute paths)\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n\nif (isWindows) {\n // Regex to split a windows path into three parts: [*, device, slash,\n // tail] windows-only\n var splitDeviceRe =\n /^([a-zA-Z]:|[\\\\\\/]{2}[^\\\\\\/]+[\\\\\\/]+[^\\\\\\/]+)?([\\\\\\/])?([\\s\\S]*?)$/;\n\n // Regex to split the tail part of the above into [*, dir, basename, ext]\n var splitTailRe =\n /^([\\s\\S]*?)((?:\\.{1,2}|[^\\\\\\/]+?|)(\\.[^.\\/\\\\]*|))(?:[\\\\\\/]*)$/;\n\n // Function to split a filename into [root, dir, basename, ext]\n // windows version\n var splitPath = function(filename) {\n // Separate device+slash from tail\n var result = splitDeviceRe.exec(filename),\n device = (result[1] || '') + (result[2] || ''),\n tail = result[3] || '';\n // Split the tail into dir, basename and extension\n var result2 = splitTailRe.exec(tail),\n dir = result2[1],\n basename = result2[2],\n ext = result2[3];\n return [device, dir, basename, ext];\n };\n\n var normalizeUNCRoot = function(device) {\n return '\\\\\\\\' + device.replace(/^[\\\\\\/]+/, '').replace(/[\\\\\\/]+/g, '\\\\');\n };\n\n // path.resolve([from ...], to)\n // windows version\n exports.resolve = function() {\n var resolvedDevice = '',\n resolvedTail = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1; i--) {\n var path;\n if (i >= 0) {\n path = arguments[i];\n } else if (!resolvedDevice) {\n path = process.cwd();\n } else {\n // Windows has the concept of drive-specific current working\n // directories. If we've resolved a drive letter but not yet an\n // absolute path, get cwd for that drive. We're sure the device is not\n // an unc path at this points, because unc paths are always absolute.\n path = process.env['=' + resolvedDevice];\n // Verify that a drive-local cwd was found and that it actually points\n // to our drive. If not, default to the drive's root.\n if (!path || path.substr(0, 3).toLowerCase() !==\n resolvedDevice.toLowerCase() + '\\\\') {\n path = resolvedDevice + '\\\\';\n }\n }\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n var result = splitDeviceRe.exec(path),\n device = result[1] || '',\n isUnc = device && device.charAt(1) !== ':',\n isAbsolute = !!result[2] || isUnc, // UNC paths are always absolute\n tail = result[3];\n\n if (device &&\n resolvedDevice &&\n device.toLowerCase() !== resolvedDevice.toLowerCase()) {\n // This path points to another device so it is not applicable\n continue;\n }\n\n if (!resolvedDevice) {\n resolvedDevice = device;\n }\n if (!resolvedAbsolute) {\n resolvedTail = tail + '\\\\' + resolvedTail;\n resolvedAbsolute = isAbsolute;\n }\n\n if (resolvedDevice && resolvedAbsolute) {\n break;\n }\n }\n\n // Convert slashes to backslashes when `resolvedDevice` points to an UNC\n // root. Also squash multiple slashes into a single one where appropriate.\n if (isUnc) {\n resolvedDevice = normalizeUNCRoot(resolvedDevice);\n }\n\n // At this point the path should be resolved to a full absolute path,\n // but handle relative paths to be safe (might happen when process.cwd()\n // fails)\n\n // Normalize the tail path\n\n function f(p) {\n return !!p;\n }\n\n resolvedTail = normalizeArray(resolvedTail.split(/[\\\\\\/]+/).filter(f),\n !resolvedAbsolute).join('\\\\');\n\n return (resolvedDevice + (resolvedAbsolute ? '\\\\' : '') + resolvedTail) ||\n '.';\n };\n\n // windows version\n exports.normalize = function(path) {\n var result = splitDeviceRe.exec(path),\n device = result[1] || '',\n isUnc = device && device.charAt(1) !== ':',\n isAbsolute = !!result[2] || isUnc, // UNC paths are always absolute\n tail = result[3],\n trailingSlash = /[\\\\\\/]$/.test(tail);\n\n // Normalize the tail path\n tail = normalizeArray(tail.split(/[\\\\\\/]+/).filter(function(p) {\n return !!p;\n }), !isAbsolute).join('\\\\');\n\n if (!tail && !isAbsolute) {\n tail = '.';\n }\n if (tail && trailingSlash) {\n tail += '\\\\';\n }\n\n // Convert slashes to backslashes when `device` points to an UNC root.\n // Also squash multiple slashes into a single one where appropriate.\n if (isUnc) {\n device = normalizeUNCRoot(device);\n }\n\n return device + (isAbsolute ? '\\\\' : '') + tail;\n };\n\n // windows version\n exports.join = function() {\n function f(p) {\n if (typeof p !== 'string') {\n throw new TypeError('Arguments to path.join must be strings');\n }\n return p;\n }\n\n var paths = Array.prototype.filter.call(arguments, f);\n var joined = paths.join('\\\\');\n\n // Make sure that the joined path doesn't start with two slashes, because\n // normalize() will mistake it for an UNC path then.\n //\n // This step is skipped when it is very clear that the user actually\n // intended to point at an UNC path. This is assumed when the first\n // non-empty string arguments starts with exactly two slashes followed by\n // at least one more non-slash character.\n //\n // Note that for normalize() to treat a path as an UNC path it needs to\n // have at least 2 components, so we don't filter for that here.\n // This means that the user can use join to construct UNC paths from\n // a server name and a share name; for example:\n // path.join('//server', 'share') -> '\\\\\\\\server\\\\share\\')\n if (!/^[\\\\\\/]{2}[^\\\\\\/]/.test(paths[0])) {\n joined = joined.replace(/^[\\\\\\/]{2,}/, '\\\\');\n }\n\n return exports.normalize(joined);\n };\n\n // path.relative(from, to)\n // it will solve the relative path from 'from' to 'to', for instance:\n // from = 'C:\\\\orandea\\\\test\\\\aaa'\n // to = 'C:\\\\orandea\\\\impl\\\\bbb'\n // The output of the function should be: '..\\\\..\\\\impl\\\\bbb'\n // windows version\n exports.relative = function(from, to) {\n from = exports.resolve(from);\n to = exports.resolve(to);\n\n // windows is not case sensitive\n var lowerFrom = from.toLowerCase();\n var lowerTo = to.toLowerCase();\n\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') break;\n }\n\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') break;\n }\n\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n\n var toParts = trim(to.split('\\\\'));\n\n var lowerFromParts = trim(lowerFrom.split('\\\\'));\n var lowerToParts = trim(lowerTo.split('\\\\'));\n\n var length = Math.min(lowerFromParts.length, lowerToParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (lowerFromParts[i] !== lowerToParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n if (samePartsLength == 0) {\n return to;\n }\n\n var outputParts = [];\n for (var i = samePartsLength; i < lowerFromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('\\\\');\n };\n\n exports.sep = '\\\\';\n exports.delimiter = ';';\n\n} else /* posix */ {\n\n // Split a filename into [root, dir, basename, ext], unix version\n // 'root' is just a slash, or nothing.\n var splitPathRe =\n /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\n var splitPath = function(filename) {\n return splitPathRe.exec(filename).slice(1);\n };\n\n // path.resolve([from ...], to)\n // posix version\n exports.resolve = function() {\n var resolvedPath = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0) ? arguments[i] : process.cwd();\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n };\n\n // path.normalize(path)\n // posix version\n exports.normalize = function(path) {\n var isAbsolute = path.charAt(0) === '/',\n trailingSlash = path.substr(-1) === '/';\n\n // Normalize the path\n path = normalizeArray(path.split('/').filter(function(p) {\n return !!p;\n }), !isAbsolute).join('/');\n\n if (!path && !isAbsolute) {\n path = '.';\n }\n if (path && trailingSlash) {\n path += '/';\n }\n\n return (isAbsolute ? '/' : '') + path;\n };\n\n\n // posix version\n exports.join = function() {\n var paths = Array.prototype.slice.call(arguments, 0);\n return exports.normalize(paths.filter(function(p, index) {\n if (typeof p !== 'string') {\n throw new TypeError('Arguments to path.join must be strings');\n }\n return p;\n }).join('/'));\n };\n\n\n // path.relative(from, to)\n // posix version\n exports.relative = function(from, to) {\n from = exports.resolve(from).substr(1);\n to = exports.resolve(to).substr(1);\n\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') break;\n }\n\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') break;\n }\n\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n\n var fromParts = trim(from.split('/'));\n var toParts = trim(to.split('/'));\n\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n };\n\n exports.sep = '/';\n exports.delimiter = ':';\n}\n\n\nexports.dirname = function(path) {\n var result = splitPath(path),\n root = result[0],\n dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.substr(0, dir.length - 1);\n }\n\n return root + dir;\n};\n\n\nexports.basename = function(path, ext) {\n var f = splitPath(path)[2];\n // TODO: make this comparison case-insensitive on windows?\n if (ext && f.substr(-1 * ext.length) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n};\n\n\nexports.extname = function(path) {\n return splitPath(path)[3];\n};\n\n\nexports.exists = util.deprecate(function(path, callback) {\n require('fs').exists(path, callback);\n}, 'path.exists is now called `fs.exists`.');\n\n\nexports.existsSync = util.deprecate(function(path) {\n return require('fs').existsSync(path);\n}, 'path.existsSync is now called `fs.existsSync`.');\n\n\nif (isWindows) {\n exports._makeLong = function(path) {\n // Note: this will *probably* throw somewhere.\n if (typeof path !== 'string')\n return path;\n\n if (!path) {\n return '';\n }\n\n var resolvedPath = exports.resolve(path);\n\n if (/^[a-zA-Z]\\:\\\\/.test(resolvedPath)) {\n // path is local filesystem path, which needs to be converted\n // to long UNC path.\n return '\\\\\\\\?\\\\' + resolvedPath;\n } else if (/^\\\\\\\\[^?.]/.test(resolvedPath)) {\n // path is network UNC path, which needs to be converted\n // to long UNC path.\n return '\\\\\\\\?\\\\UNC\\\\' + resolvedPath.substring(2);\n }\n\n return path;\n };\n} else {\n exports._makeLong = function(path) {\n return path;\n };\n}\n\n});","sourceLength":14350,"scriptType":2,"compilationType":0,"context":{"ref":43},"text":"path.js (lines: 489)"},{"handle":46,"type":"script","name":"assert.js","id":20,"lineOffset":0,"columnOffset":0,"lineCount":332,"source":"(function (exports, require, module, __filename, __dirname) { // http://wiki.commonjs.org/wiki/Unit_Testing/1.0\n//\n// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!\n//\n// Originally from narwhal.js (http://narwhaljs.org)\n// Copyright (c) 2009 Thomas Robinson <280north.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the 'Software'), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// UTILITY\nvar util = require('util');\nvar pSlice = Array.prototype.slice;\n\n// 1. The assert module provides functions that throw\n// AssertionError's when particular conditions are not met. The\n// assert module must conform to the following interface.\n\nvar assert = module.exports = ok;\n\n// 2. The AssertionError is defined in assert.\n// new assert.AssertionError({ message: message,\n// actual: actual,\n// expected: expected })\n\nassert.AssertionError = function AssertionError(options) {\n this.message = options.message;\n this.actual = options.actual;\n this.expected = options.expected;\n this.operator = options.operator;\n var stackStartFunction = options.stackStartFunction || fail;\n\n this.name = getName(this, options.message);\n Error.captureStackTrace(this, stackStartFunction);\n};\n\n// assert.AssertionError instanceof Error\nutil.inherits(assert.AssertionError, Error);\n\nfunction replacer(key, value) {\n if (value === undefined) {\n return '' + value;\n }\n if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {\n return value.toString();\n }\n if (typeof value === 'function' || value instanceof RegExp) {\n return value.toString();\n }\n return value;\n}\n\nfunction truncate(s, n) {\n if (typeof s == 'string') {\n return s.length < n ? s : s.slice(0, n);\n } else {\n return s;\n }\n}\n\nfunction getName(self, message) {\n if (message) {\n return 'AssertionError: ' + message;\n } else {\n return 'AssertionError: ' +\n truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +\n self.operator + ' ' +\n truncate(JSON.stringify(self.expected, replacer), 128);\n }\n}\n\n// At present only the three keys mentioned above are used and\n// understood by the spec. Implementations or sub modules can pass\n// other keys to the AssertionError's constructor - they will be\n// ignored.\n\n// 3. All of the following functions must throw an AssertionError\n// when a corresponding condition is not met, with a message that\n// may be undefined if not provided. All assertion methods provide\n// both the actual and expected values to the assertion error for\n// display purposes.\n\nfunction fail(actual, expected, message, operator, stackStartFunction) {\n throw new assert.AssertionError({\n message: message,\n actual: actual,\n expected: expected,\n operator: operator,\n stackStartFunction: stackStartFunction\n });\n}\n\n// EXTENSION! allows for well behaved errors defined elsewhere.\nassert.fail = fail;\n\n// 4. Pure assertion tests whether a value is truthy, as determined\n// by !!guard.\n// assert.ok(guard, message_opt);\n// This statement is equivalent to assert.equal(true, !!guard,\n// message_opt);. To test strictly for the value true, use\n// assert.strictEqual(true, guard, message_opt);.\n\nfunction ok(value, message) {\n if (!!!value) fail(value, true, message, '==', assert.ok);\n}\nassert.ok = ok;\n\n// 5. The equality assertion tests shallow, coercive equality with\n// ==.\n// assert.equal(actual, expected, message_opt);\n\nassert.equal = function equal(actual, expected, message) {\n if (actual != expected) fail(actual, expected, message, '==', assert.equal);\n};\n\n// 6. The non-equality assertion tests for whether two objects are not equal\n// with != assert.notEqual(actual, expected, message_opt);\n\nassert.notEqual = function notEqual(actual, expected, message) {\n if (actual == expected) {\n fail(actual, expected, message, '!=', assert.notEqual);\n }\n};\n\n// 7. The equivalence assertion tests a deep equality relation.\n// assert.deepEqual(actual, expected, message_opt);\n\nassert.deepEqual = function deepEqual(actual, expected, message) {\n if (!_deepEqual(actual, expected)) {\n fail(actual, expected, message, 'deepEqual', assert.deepEqual);\n }\n};\n\nfunction _deepEqual(actual, expected) {\n // 7.1. All identical values are equivalent, as determined by ===.\n if (actual === expected) {\n return true;\n\n } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {\n if (actual.length != expected.length) return false;\n\n for (var i = 0; i < actual.length; i++) {\n if (actual[i] !== expected[i]) return false;\n }\n\n return true;\n\n // 7.2. If the expected value is a Date object, the actual value is\n // equivalent if it is also a Date object that refers to the same time.\n } else if (actual instanceof Date && expected instanceof Date) {\n return actual.getTime() === expected.getTime();\n\n // 7.3 If the expected value is a RegExp object, the actual value is\n // equivalent if it is also a RegExp object with the same source and\n // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).\n } else if (actual instanceof RegExp && expected instanceof RegExp) {\n return actual.source === expected.source &&\n actual.global === expected.global &&\n actual.multiline === expected.multiline &&\n actual.lastIndex === expected.lastIndex &&\n actual.ignoreCase === expected.ignoreCase;\n\n // 7.4. Other pairs that do not both pass typeof value == 'object',\n // equivalence is determined by ==.\n } else if (typeof actual != 'object' && typeof expected != 'object') {\n return actual == expected;\n\n // 7.5 For all other Object pairs, including Array objects, equivalence is\n // determined by having the same number of owned properties (as verified\n // with Object.prototype.hasOwnProperty.call), the same set of keys\n // (although not necessarily the same order), equivalent values for every\n // corresponding key, and an identical 'prototype' property. Note: this\n // accounts for both named and indexed properties on Arrays.\n } else {\n return objEquiv(actual, expected);\n }\n}\n\nfunction isUndefinedOrNull(value) {\n return value === null || value === undefined;\n}\n\nfunction isArguments(object) {\n return Object.prototype.toString.call(object) == '[object Arguments]';\n}\n\nfunction objEquiv(a, b) {\n if (isUndefinedOrNull(a) || isUndefinedOrNull(b))\n return false;\n // an identical 'prototype' property.\n if (a.prototype !== b.prototype) return false;\n //~~~I've managed to break Object.keys through screwy arguments passing.\n // Converting to array solves the problem.\n if (isArguments(a)) {\n if (!isArguments(b)) {\n return false;\n }\n a = pSlice.call(a);\n b = pSlice.call(b);\n return _deepEqual(a, b);\n }\n try {\n var ka = Object.keys(a),\n kb = Object.keys(b),\n key, i;\n } catch (e) {//happens when one is a string literal and the other isn't\n return false;\n }\n // having the same number of owned properties (keys incorporates\n // hasOwnProperty)\n if (ka.length != kb.length)\n return false;\n //the same set of keys (although not necessarily the same order),\n ka.sort();\n kb.sort();\n //~~~cheap key test\n for (i = ka.length - 1; i >= 0; i--) {\n if (ka[i] != kb[i])\n return false;\n }\n //equivalent values for every corresponding key, and\n //~~~possibly expensive deep test\n for (i = ka.length - 1; i >= 0; i--) {\n key = ka[i];\n if (!_deepEqual(a[key], b[key])) return false;\n }\n return true;\n}\n\n// 8. The non-equivalence assertion tests for any deep inequality.\n// assert.notDeepEqual(actual, expected, message_opt);\n\nassert.notDeepEqual = function notDeepEqual(actual, expected, message) {\n if (_deepEqual(actual, expected)) {\n fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);\n }\n};\n\n// 9. The strict equality assertion tests strict equality, as determined by ===.\n// assert.strictEqual(actual, expected, message_opt);\n\nassert.strictEqual = function strictEqual(actual, expected, message) {\n if (actual !== expected) {\n fail(actual, expected, message, '===', assert.strictEqual);\n }\n};\n\n// 10. The strict non-equality assertion tests for strict inequality, as\n// determined by !==. assert.notStrictEqual(actual, expected, message_opt);\n\nassert.notStrictEqual = function notStrictEqual(actual, expected, message) {\n if (actual === expected) {\n fail(actual, expected, message, '!==', assert.notStrictEqual);\n }\n};\n\nfunction expectedException(actual, expected) {\n if (!actual || !expected) {\n return false;\n }\n\n if (Object.prototype.toString.call(expected) == '[object RegExp]') {\n return expected.test(actual);\n } else if (actual instanceof expected) {\n return true;\n } else if (expected.call({}, actual) === true) {\n return true;\n }\n\n return false;\n}\n\nfunction _throws(shouldThrow, block, expected, message) {\n var actual;\n\n if (typeof expected === 'string') {\n message = expected;\n expected = null;\n }\n\n try {\n block();\n } catch (e) {\n actual = e;\n }\n\n message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +\n (message ? ' ' + message : '.');\n\n if (shouldThrow && !actual) {\n fail(actual, expected, 'Missing expected exception' + message);\n }\n\n if (!shouldThrow && expectedException(actual, expected)) {\n fail(actual, expected, 'Got unwanted exception' + message);\n }\n\n if ((shouldThrow && actual && expected &&\n !expectedException(actual, expected)) || (!shouldThrow && actual)) {\n throw actual;\n }\n}\n\n// 11. Expected to throw an error:\n// assert.throws(block, Error_opt, message_opt);\n\nassert.throws = function(block, /*optional*/error, /*optional*/message) {\n _throws.apply(this, [true].concat(pSlice.call(arguments)));\n};\n\n// EXTENSION! This is annoying to write outside this module.\nassert.doesNotThrow = function(block, /*optional*/message) {\n _throws.apply(this, [false].concat(pSlice.call(arguments)));\n};\n\nassert.ifError = function(err) { if (err) {throw err;}};\n\n});","sourceLength":10940,"scriptType":2,"compilationType":0,"context":{"ref":45},"text":"assert.js (lines: 332)"},{"handle":48,"type":"script","name":"buffer.js","id":19,"lineOffset":0,"columnOffset":0,"lineCount":954,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar SlowBuffer = process.binding('buffer').SlowBuffer;\nvar assert = require('assert');\n\nexports.INSPECT_MAX_BYTES = 50;\n\n// Make SlowBuffer inherit from Buffer.\n// This is an exception to the rule that __proto__ is not allowed in core.\nSlowBuffer.prototype.__proto__ = Buffer.prototype;\n\n\nfunction clamp(index, len, defaultValue) {\n if (typeof index !== 'number') return defaultValue;\n index = ~~index; // Coerce to integer.\n if (index >= len) return len;\n if (index >= 0) return index;\n index += len;\n if (index >= 0) return index;\n return 0;\n}\n\n\nfunction toHex(n) {\n if (n < 16) return '0' + n.toString(16);\n return n.toString(16);\n}\n\n\nSlowBuffer.prototype.toString = function(encoding, start, end) {\n encoding = String(encoding || 'utf8').toLowerCase();\n start = +start || 0;\n if (typeof end !== 'number') end = this.length;\n\n // Fastpath empty strings\n if (+end == start) {\n return '';\n }\n\n switch (encoding) {\n case 'hex':\n return this.hexSlice(start, end);\n\n case 'utf8':\n case 'utf-8':\n return this.utf8Slice(start, end);\n\n case 'ascii':\n return this.asciiSlice(start, end);\n\n case 'binary':\n return this.binarySlice(start, end);\n\n case 'base64':\n return this.base64Slice(start, end);\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return this.ucs2Slice(start, end);\n\n default:\n throw new TypeError('Unknown encoding: ' + encoding);\n }\n};\n\n\nSlowBuffer.prototype.write = function(string, offset, length, encoding) {\n // Support both (string, offset, length, encoding)\n // and the legacy (string, encoding, offset, length)\n if (isFinite(offset)) {\n if (!isFinite(length)) {\n encoding = length;\n length = undefined;\n }\n } else { // legacy\n var swap = encoding;\n encoding = offset;\n offset = length;\n length = swap;\n }\n\n offset = +offset || 0;\n var remaining = this.length - offset;\n if (!length) {\n length = remaining;\n } else {\n length = +length;\n if (length > remaining) {\n length = remaining;\n }\n }\n encoding = String(encoding || 'utf8').toLowerCase();\n\n switch (encoding) {\n case 'hex':\n return this.hexWrite(string, offset, length);\n\n case 'utf8':\n case 'utf-8':\n return this.utf8Write(string, offset, length);\n\n case 'ascii':\n return this.asciiWrite(string, offset, length);\n\n case 'binary':\n return this.binaryWrite(string, offset, length);\n\n case 'base64':\n return this.base64Write(string, offset, length);\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return this.ucs2Write(string, offset, length);\n\n default:\n throw new TypeError('Unknown encoding: ' + encoding);\n }\n};\n\n\n// slice(start, end)\nSlowBuffer.prototype.slice = function(start, end) {\n var len = this.length;\n start = clamp(start, len, 0);\n end = clamp(end, len, len);\n return new Buffer(this, end - start, start);\n};\n\n\nvar zeroBuffer = new SlowBuffer(0);\n\n// Buffer\nfunction Buffer(subject, encoding, offset) {\n if (!(this instanceof Buffer)) {\n return new Buffer(subject, encoding, offset);\n }\n\n var type;\n\n // Are we slicing?\n if (typeof offset === 'number') {\n if (!Buffer.isBuffer(subject)) {\n throw new TypeError('First argument must be a Buffer when slicing');\n }\n\n this.length = +encoding > 0 ? Math.ceil(encoding) : 0;\n this.parent = subject.parent ? subject.parent : subject;\n this.offset = offset;\n } else {\n // Find the length\n switch (type = typeof subject) {\n case 'number':\n this.length = +subject > 0 ? Math.ceil(subject) : 0;\n break;\n\n case 'string':\n this.length = Buffer.byteLength(subject, encoding);\n break;\n\n case 'object': // Assume object is array-ish\n this.length = +subject.length > 0 ? Math.ceil(subject.length) : 0;\n break;\n\n default:\n throw new TypeError('First argument needs to be a number, ' +\n 'array or string.');\n }\n\n if (this.length > Buffer.poolSize) {\n // Big buffer, just alloc one.\n this.parent = new SlowBuffer(this.length);\n this.offset = 0;\n\n } else if (this.length > 0) {\n // Small buffer.\n if (!pool || pool.length - pool.used < this.length) allocPool();\n this.parent = pool;\n this.offset = pool.used;\n pool.used += this.length;\n if (pool.used & 7) pool.used = (pool.used + 8) & ~7;\n\n } else {\n // Zero-length buffer\n this.parent = zeroBuffer;\n this.offset = 0;\n }\n\n // optimize by branching logic for new allocations\n if (typeof subject !== 'number') {\n if (type === 'string') {\n // We are a string\n this.length = this.write(subject, 0, encoding);\n // if subject is buffer then use built-in copy method\n } else if (Buffer.isBuffer(subject)) {\n if (subject.parent)\n subject.parent.copy(this.parent,\n this.offset,\n subject.offset,\n this.length + subject.offset);\n else\n subject.copy(this.parent, this.offset, 0, this.length);\n } else if (isArrayIsh(subject)) {\n for (var i = 0; i < this.length; i++)\n this.parent[i + this.offset] = subject[i];\n }\n }\n }\n\n SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length);\n}\n\nfunction isArrayIsh(subject) {\n return Array.isArray(subject) ||\n subject && typeof subject === 'object' &&\n typeof subject.length === 'number';\n}\n\nexports.SlowBuffer = SlowBuffer;\nexports.Buffer = Buffer;\n\n\nBuffer.isEncoding = function(encoding) {\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n case 'raw':\n return true;\n\n default:\n return false;\n }\n};\n\n\n\nBuffer.poolSize = 8 * 1024;\nvar pool;\n\nfunction allocPool() {\n pool = new SlowBuffer(Buffer.poolSize);\n pool.used = 0;\n}\n\n\n// Static methods\nBuffer.isBuffer = function isBuffer(b) {\n return b instanceof Buffer;\n};\n\n\n// Inspect\nBuffer.prototype.inspect = function inspect() {\n var out = [],\n len = this.length,\n name = this.constructor.name;\n\n for (var i = 0; i < len; i++) {\n out[i] = toHex(this[i]);\n if (i == exports.INSPECT_MAX_BYTES) {\n out[i + 1] = '...';\n break;\n }\n }\n\n return '<' + name + ' ' + out.join(' ') + '>';\n};\n\n\nBuffer.prototype.get = function get(offset) {\n if (offset < 0 || offset >= this.length)\n throw new RangeError('offset is out of bounds');\n return this.parent[this.offset + offset];\n};\n\n\nBuffer.prototype.set = function set(offset, v) {\n if (offset < 0 || offset >= this.length)\n throw new RangeError('offset is out of bounds');\n return this.parent[this.offset + offset] = v;\n};\n\n\n// write(string, offset = 0, length = buffer.length-offset, encoding = 'utf8')\nBuffer.prototype.write = function(string, offset, length, encoding) {\n // Support both (string, offset, length, encoding)\n // and the legacy (string, encoding, offset, length)\n if (isFinite(offset)) {\n if (!isFinite(length)) {\n encoding = length;\n length = undefined;\n }\n } else { // legacy\n var swap = encoding;\n encoding = offset;\n offset = length;\n length = swap;\n }\n\n offset = +offset || 0;\n var remaining = this.length - offset;\n if (!length) {\n length = remaining;\n } else {\n length = +length;\n if (length > remaining) {\n length = remaining;\n }\n }\n encoding = String(encoding || 'utf8').toLowerCase();\n\n var ret;\n switch (encoding) {\n case 'hex':\n ret = this.parent.hexWrite(string, this.offset + offset, length);\n break;\n\n case 'utf8':\n case 'utf-8':\n ret = this.parent.utf8Write(string, this.offset + offset, length);\n break;\n\n case 'ascii':\n ret = this.parent.asciiWrite(string, this.offset + offset, length);\n break;\n\n case 'binary':\n ret = this.parent.binaryWrite(string, this.offset + offset, length);\n break;\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n ret = this.parent.base64Write(string, this.offset + offset, length);\n break;\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n ret = this.parent.ucs2Write(string, this.offset + offset, length);\n break;\n\n default:\n throw new TypeError('Unknown encoding: ' + encoding);\n }\n\n Buffer._charsWritten = SlowBuffer._charsWritten;\n\n return ret;\n};\n\n\nBuffer.prototype.toJSON = function() {\n return Array.prototype.slice.call(this, 0);\n};\n\n\n// toString(encoding, start=0, end=buffer.length)\nBuffer.prototype.toString = function(encoding, start, end) {\n encoding = String(encoding || 'utf8').toLowerCase();\n\n if (typeof start !== 'number' || start < 0) {\n start = 0;\n } else if (start > this.length) {\n start = this.length;\n }\n\n if (typeof end !== 'number' || end > this.length) {\n end = this.length;\n } else if (end < 0) {\n end = 0;\n }\n\n start = start + this.offset;\n end = end + this.offset;\n\n switch (encoding) {\n case 'hex':\n return this.parent.hexSlice(start, end);\n\n case 'utf8':\n case 'utf-8':\n return this.parent.utf8Slice(start, end);\n\n case 'ascii':\n return this.parent.asciiSlice(start, end);\n\n case 'binary':\n return this.parent.binarySlice(start, end);\n\n case 'base64':\n return this.parent.base64Slice(start, end);\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return this.parent.ucs2Slice(start, end);\n\n default:\n throw new TypeError('Unknown encoding: ' + encoding);\n }\n};\n\n\n// byteLength\nBuffer.byteLength = SlowBuffer.byteLength;\n\n\n// fill(value, start=0, end=buffer.length)\nBuffer.prototype.fill = function fill(value, start, end) {\n value || (value = 0);\n start || (start = 0);\n end || (end = this.length);\n\n if (typeof value === 'string') {\n value = value.charCodeAt(0);\n }\n if (typeof value !== 'number' || isNaN(value)) {\n throw new TypeError('value is not a number');\n }\n\n if (end < start) throw new RangeError('end < start');\n\n // Fill 0 bytes; we're done\n if (end === start) return 0;\n if (this.length == 0) return 0;\n\n if (start < 0 || start >= this.length) {\n throw new RangeError('start out of bounds');\n }\n\n if (end < 0 || end > this.length) {\n throw new RangeError('end out of bounds');\n }\n\n return this.parent.fill(value,\n start + this.offset,\n end + this.offset);\n};\n\n\nBuffer.concat = function(list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('Usage: Buffer.concat(list, [length])');\n }\n\n if (list.length === 0) {\n return new Buffer(0);\n } else if (list.length === 1) {\n return list[0];\n }\n\n if (typeof length !== 'number') {\n length = 0;\n for (var i = 0; i < list.length; i++) {\n var buf = list[i];\n length += buf.length;\n }\n }\n\n var buffer = new Buffer(length);\n var pos = 0;\n for (var i = 0; i < list.length; i++) {\n var buf = list[i];\n buf.copy(buffer, pos);\n pos += buf.length;\n }\n return buffer;\n};\n\n\n\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function(target, target_start, start, end) {\n // set undefined/NaN or out of bounds values equal to their default\n if (!(target_start >= 0)) target_start = 0;\n if (!(start >= 0)) start = 0;\n if (!(end < this.length)) end = this.length;\n\n // Copy 0 bytes; we're done\n if (end === start ||\n target.length === 0 ||\n this.length === 0 ||\n start > this.length)\n return 0;\n\n if (end < start)\n throw new RangeError('sourceEnd < sourceStart');\n\n if (target_start >= target.length)\n throw new RangeError('targetStart out of bounds');\n\n if (target.length - target_start < end - start)\n end = target.length - target_start + start;\n\n return this.parent.copy(target.parent || target,\n target_start + (target.offset || 0),\n start + this.offset,\n end + this.offset);\n};\n\n\n// slice(start, end)\nBuffer.prototype.slice = function(start, end) {\n var len = this.length;\n start = clamp(start, len, 0);\n end = clamp(end, len, len);\n return new Buffer(this.parent, end - start, start + this.offset);\n};\n\n\n// Legacy methods for backwards compatibility.\n\nBuffer.prototype.utf8Slice = function(start, end) {\n return this.toString('utf8', start, end);\n};\n\nBuffer.prototype.binarySlice = function(start, end) {\n return this.toString('binary', start, end);\n};\n\nBuffer.prototype.asciiSlice = function(start, end) {\n return this.toString('ascii', start, end);\n};\n\nBuffer.prototype.utf8Write = function(string, offset) {\n return this.write(string, offset, 'utf8');\n};\n\nBuffer.prototype.binaryWrite = function(string, offset) {\n return this.write(string, offset, 'binary');\n};\n\nBuffer.prototype.asciiWrite = function(string, offset) {\n return this.write(string, offset, 'ascii');\n};\n\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n * This check is far too slow internally for fast buffers.\n */\nfunction checkOffset(offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0)\n throw new RangeError('offset is not uint');\n if (offset + ext > length)\n throw new RangeError('Trying to access beyond buffer length');\n}\n\n\nBuffer.prototype.readUInt8 = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 1, this.length);\n return this[offset];\n};\n\n\nfunction readUInt16(buffer, offset, isBigEndian) {\n var val = 0;\n if (isBigEndian) {\n val = buffer[offset] << 8;\n val |= buffer[offset + 1];\n } else {\n val = buffer[offset];\n val |= buffer[offset + 1] << 8;\n }\n\n return val;\n}\n\n\nBuffer.prototype.readUInt16LE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 2, this.length);\n return readUInt16(this, offset, false, noAssert);\n};\n\n\nBuffer.prototype.readUInt16BE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 2, this.length);\n return readUInt16(this, offset, true, noAssert);\n};\n\n\nfunction readUInt32(buffer, offset, isBigEndian, noAssert) {\n var val = 0;\n\n if (isBigEndian) {\n val = buffer[offset + 1] << 16;\n val |= buffer[offset + 2] << 8;\n val |= buffer[offset + 3];\n val = val + (buffer[offset] << 24 >>> 0);\n } else {\n val = buffer[offset + 2] << 16;\n val |= buffer[offset + 1] << 8;\n val |= buffer[offset];\n val = val + (buffer[offset + 3] << 24 >>> 0);\n }\n\n return val;\n}\n\n\nBuffer.prototype.readUInt32LE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 4, this.length);\n return readUInt32(this, offset, false, noAssert);\n};\n\n\nBuffer.prototype.readUInt32BE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 4, this.length);\n return readUInt32(this, offset, true, noAssert);\n};\n\n\n/*\n * Signed integer types, yay team! A reminder on how two's complement actually\n * works. The first bit is the signed bit, i.e. tells us whether or not the\n * number should be positive or negative. If the two's complement value is\n * positive, then we're done, as it's equivalent to the unsigned representation.\n *\n * Now if the number is positive, you're pretty much done, you can just leverage\n * the unsigned translations and return those. Unfortunately, negative numbers\n * aren't quite that straightforward.\n *\n * At first glance, one might be inclined to use the traditional formula to\n * translate binary numbers between the positive and negative values in two's\n * complement. (Though it doesn't quite work for the most negative value)\n * Mainly:\n * - invert all the bits\n * - add one to the result\n *\n * Of course, this doesn't quite work in Javascript. Take for example the value\n * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of\n * course, Javascript will do the following:\n *\n * > ~0xff80\n * -65409\n *\n * Whoh there, Javascript, that's not quite right. But wait, according to\n * Javascript that's perfectly correct. When Javascript ends up seeing the\n * constant 0xff80, it has no notion that it is actually a signed number. It\n * assumes that we've input the unsigned value 0xff80. Thus, when it does the\n * binary negation, it casts it into a signed value, (positive 0xff80). Then\n * when you perform binary negation on that, it turns it into a negative number.\n *\n * Instead, we're going to have to use the following general formula, that works\n * in a rather Javascript friendly way. I'm glad we don't support this kind of\n * weird numbering scheme in the kernel.\n *\n * (BIT-MAX - (unsigned)val + 1) * -1\n *\n * The astute observer, may think that this doesn't make sense for 8-bit numbers\n * (really it isn't necessary for them). However, when you get 16-bit numbers,\n * you do. Let's go back to our prior example and see how this will look:\n *\n * (0xffff - 0xff80 + 1) * -1\n * (0x007f + 1) * -1\n * (0x0080) * -1\n */\n\nBuffer.prototype.readInt8 = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 1, this.length);\n if (!(this[offset] & 0x80))\n return (this[offset]);\n return ((0xff - this[offset] + 1) * -1);\n};\n\n\nfunction readInt16(buffer, offset, isBigEndian) {\n var val = readUInt16(buffer, offset, isBigEndian);\n\n if (!(val & 0x8000))\n return val;\n return (0xffff - val + 1) * -1;\n}\n\n\nBuffer.prototype.readInt16LE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 2, this.length);\n return readInt16(this, offset, false);\n};\n\n\nBuffer.prototype.readInt16BE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 2, this.length);\n return readInt16(this, offset, true);\n};\n\n\nfunction readInt32(buffer, offset, isBigEndian) {\n var val = readUInt32(buffer, offset, isBigEndian);\n\n if (!(val & 0x80000000))\n return (val);\n return (0xffffffff - val + 1) * -1;\n}\n\n\nBuffer.prototype.readInt32LE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 4, this.length);\n return readInt32(this, offset, false);\n};\n\n\nBuffer.prototype.readInt32BE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 4, this.length);\n return readInt32(this, offset, true);\n};\n\nBuffer.prototype.readFloatLE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 4, this.length);\n return this.parent.readFloatLE(this.offset + offset, !!noAssert);\n};\n\n\nBuffer.prototype.readFloatBE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 4, this.length);\n return this.parent.readFloatBE(this.offset + offset, !!noAssert);\n};\n\n\nBuffer.prototype.readDoubleLE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 8, this.length);\n return this.parent.readDoubleLE(this.offset + offset, !!noAssert);\n};\n\n\nBuffer.prototype.readDoubleBE = function(offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 8, this.length);\n return this.parent.readDoubleBE(this.offset + offset, !!noAssert);\n};\n\n\nfunction checkInt(buffer, value, offset, ext, max, min) {\n if ((value % 1) !== 0 || value > max || value < min)\n throw TypeError('value is out of bounds');\n if ((offset % 1) !== 0 || offset < 0)\n throw TypeError('offset is not uint');\n if (offset + ext > buffer.length || buffer.length + offset < 0)\n throw RangeError('Trying to write outside buffer length');\n}\n\n\nBuffer.prototype.writeUInt8 = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 1, 0xff, 0);\n this[offset] = value;\n};\n\n\nfunction writeUInt16(buffer, value, offset, isBigEndian) {\n if (isBigEndian) {\n buffer[offset] = (value & 0xff00) >>> 8;\n buffer[offset + 1] = value & 0x00ff;\n } else {\n buffer[offset + 1] = (value & 0xff00) >>> 8;\n buffer[offset] = value & 0x00ff;\n }\n}\n\n\nBuffer.prototype.writeUInt16LE = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 2, 0xffff, 0);\n writeUInt16(this, value, offset, false);\n};\n\n\nBuffer.prototype.writeUInt16BE = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 2, 0xffff, 0);\n writeUInt16(this, value, offset, true);\n};\n\n\nfunction writeUInt32(buffer, value, offset, isBigEndian) {\n if (isBigEndian) {\n buffer[offset] = (value >>> 24) & 0xff;\n buffer[offset + 1] = (value >>> 16) & 0xff;\n buffer[offset + 2] = (value >>> 8) & 0xff;\n buffer[offset + 3] = value & 0xff;\n } else {\n buffer[offset + 3] = (value >>> 24) & 0xff;\n buffer[offset + 2] = (value >>> 16) & 0xff;\n buffer[offset + 1] = (value >>> 8) & 0xff;\n buffer[offset] = value & 0xff;\n }\n}\n\n\nBuffer.prototype.writeUInt32LE = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 4, 0xffffffff, 0);\n writeUInt32(this, value, offset, false);\n};\n\n\nBuffer.prototype.writeUInt32BE = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 4, 0xffffffff, 0);\n writeUInt32(this, value, offset, true);\n};\n\n\n/*\n * We now move onto our friends in the signed number category. Unlike unsigned\n * numbers, we're going to have to worry a bit more about how we put values into\n * arrays. Since we are only worrying about signed 32-bit values, we're in\n * slightly better shape. Unfortunately, we really can't do our favorite binary\n * & in this system. It really seems to do the wrong thing. For example:\n *\n * > -32 & 0xff\n * 224\n *\n * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of\n * this aren't treated as a signed number. Ultimately a bad thing.\n *\n * What we're going to want to do is basically create the unsigned equivalent of\n * our representation and pass that off to the wuint* functions. To do that\n * we're going to do the following:\n *\n * - if the value is positive\n * we can pass it directly off to the equivalent wuint\n * - if the value is negative\n * we do the following computation:\n * mb + val + 1, where\n * mb is the maximum unsigned value in that byte size\n * val is the Javascript negative integer\n *\n *\n * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If\n * you do out the computations:\n *\n * 0xffff - 128 + 1\n * 0xffff - 127\n * 0xff80\n *\n * You can then encode this value as the signed version. This is really rather\n * hacky, but it should work and get the job done which is our goal here.\n */\n\nBuffer.prototype.writeInt8 = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 1, 0x7f, -0x80);\n if (value < 0) value = 0xff + value + 1;\n this[offset] = value;\n};\n\n\nBuffer.prototype.writeInt16LE = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 2, 0x7fff, -0x8000);\n if (value < 0) value = 0xffff + value + 1;\n writeUInt16(this, value, offset, false);\n};\n\n\nBuffer.prototype.writeInt16BE = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 2, 0x7fff, -0x8000);\n if (value < 0) value = 0xffff + value + 1;\n writeUInt16(this, value, offset, true);\n};\n\n\nBuffer.prototype.writeInt32LE = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);\n if (value < 0) value = 0xffffffff + value + 1;\n writeUInt32(this, value, offset, false);\n};\n\n\nBuffer.prototype.writeInt32BE = function(value, offset, noAssert) {\n if (!noAssert)\n checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);\n if (value < 0) value = 0xffffffff + value + 1;\n writeUInt32(this, value, offset, true);\n};\n\n\nBuffer.prototype.writeFloatLE = function(value, offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 4, this.length);\n this.parent.writeFloatLE(value, this.offset + offset, !!noAssert);\n};\n\n\nBuffer.prototype.writeFloatBE = function(value, offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 4, this.length);\n this.parent.writeFloatBE(value, this.offset + offset, !!noAssert);\n};\n\n\nBuffer.prototype.writeDoubleLE = function(value, offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 8, this.length);\n this.parent.writeDoubleLE(value, this.offset + offset, !!noAssert);\n};\n\n\nBuffer.prototype.writeDoubleBE = function(value, offset, noAssert) {\n if (!noAssert)\n checkOffset(offset, 8, this.length);\n this.parent.writeDoubleBE(value, this.offset + offset, !!noAssert);\n};\n\n});","sourceLength":25681,"scriptType":2,"compilationType":0,"context":{"ref":47},"text":"buffer.js (lines: 954)"},{"handle":50,"type":"script","name":"_stream_transform.js","id":31,"lineOffset":0,"columnOffset":0,"lineCount":207,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\nmodule.exports = Transform;\n\nvar Duplex = require('_stream_duplex');\nvar util = require('util');\nutil.inherits(Transform, Duplex);\n\n\nfunction TransformState(options, stream) {\n this.afterTransform = function(er, data) {\n return afterTransform(stream, er, data);\n };\n\n this.needTransform = false;\n this.transforming = false;\n this.writecb = null;\n this.writechunk = null;\n}\n\nfunction afterTransform(stream, er, data) {\n var ts = stream._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb)\n return stream.emit('error', new Error('no writecb in Transform class'));\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data !== null && data !== undefined)\n stream.push(data);\n\n if (cb)\n cb(er);\n\n var rs = stream._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n stream._read(rs.highWaterMark);\n }\n}\n\n\nfunction Transform(options) {\n if (!(this instanceof Transform))\n return new Transform(options);\n\n Duplex.call(this, options);\n\n var ts = this._transformState = new TransformState(options, this);\n\n // when the writable side finishes, then flush out anything remaining.\n var stream = this;\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n this.once('finish', function() {\n if ('function' === typeof this._flush)\n this._flush(function(er) {\n done(stream, er);\n });\n else\n done(stream);\n });\n}\n\nTransform.prototype.push = function(chunk) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function(chunk, encoding, cb) {\n throw new Error('not implemented');\n};\n\nTransform.prototype._write = function(chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform ||\n rs.needReadable ||\n rs.length < rs.highWaterMark)\n this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function(n) {\n var ts = this._transformState;\n\n if (ts.writechunk && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\n\nfunction done(stream, er) {\n if (er)\n return stream.emit('error', er);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n var ws = stream._writableState;\n var rs = stream._readableState;\n var ts = stream._transformState;\n\n if (ws.length)\n throw new Error('calling transform done when ws.length != 0');\n\n if (ts.transforming)\n throw new Error('calling transform done when still transforming');\n\n return stream.push(null);\n}\n\n});","sourceLength":7347,"scriptType":2,"compilationType":0,"context":{"ref":49},"text":"_stream_transform.js (lines: 207)"},{"handle":52,"type":"script","name":"util.js","id":21,"lineOffset":0,"columnOffset":0,"lineCount":581,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (typeof f !== 'string') {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j': return JSON.stringify(args[i++]);\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (x === null || typeof x !== 'object') {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n if (process.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nexports.print = function() {\n for (var i = 0, len = arguments.length; i < len; ++i) {\n process.stdout.write(String(arguments[i]));\n }\n};\n\n\nexports.puts = function() {\n for (var i = 0, len = arguments.length; i < len; ++i) {\n process.stdout.write(arguments[i] + '\\n');\n }\n};\n\n\nexports.debug = function(x) {\n process.stderr.write('DEBUG: ' + x + '\\n');\n};\n\n\nvar error = exports.error = function(x) {\n for (var i = 0, len = arguments.length; i < len; ++i) {\n process.stderr.write(arguments[i] + '\\n');\n }\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (typeof opts === 'boolean') {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (typeof ctx.showHidden === 'undefined') ctx.showHidden = false;\n if (typeof ctx.depth === 'undefined') ctx.depth = 2;\n if (typeof ctx.colors === 'undefined') ctx.colors = false;\n if (typeof ctx.customInspect === 'undefined') ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect && value && typeof value.inspect === 'function' &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n return String(value.inspect(recurseTimes));\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (typeof value === 'function') {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (typeof value === 'function') {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n switch (typeof value) {\n case 'undefined':\n return ctx.stylize('undefined', 'undefined');\n\n case 'string':\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n\n case 'number':\n return ctx.stylize('' + value, 'number');\n\n case 'boolean':\n return ctx.stylize('' + value, 'boolean');\n }\n // For some reason typeof null is \"object\", so special case here.\n if (value === null) {\n return ctx.stylize('null', 'null');\n }\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (recurseTimes === null) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (typeof name === 'undefined') {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar) ||\n (typeof ar === 'object' && objectToString(ar) === '[object Array]');\n}\nexports.isArray = isArray;\n\n\nfunction isRegExp(re) {\n return typeof re === 'object' && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\n\nfunction isDate(d) {\n return typeof d === 'object' && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\n\nfunction isError(e) {\n return typeof e === 'object' && objectToString(e) === '[object Error]';\n}\nexports.isError = isError;\n\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nexports.p = exports.deprecate(function() {\n for (var i = 0, len = arguments.length; i < len; ++i) {\n error(exports.inspect(arguments[i]));\n }\n}, 'util.p: Use console.error() instead.');\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\nexports.log = function(msg) {\n exports.puts(timestamp() + ' - ' + msg.toString());\n};\n\n\nexports.exec = exports.deprecate(function() {\n return require('child_process').exec.apply(this, arguments);\n}, 'util.exec is now called `child_process.exec`.');\n\n\nfunction pump(readStream, writeStream, callback) {\n var callbackCalled = false;\n\n function call(a, b, c) {\n if (callback && !callbackCalled) {\n callback(a, b, c);\n callbackCalled = true;\n }\n }\n\n readStream.addListener('data', function(chunk) {\n if (writeStream.write(chunk) === false) readStream.pause();\n });\n\n writeStream.addListener('drain', function() {\n readStream.resume();\n });\n\n readStream.addListener('end', function() {\n writeStream.end();\n });\n\n readStream.addListener('close', function() {\n call();\n });\n\n readStream.addListener('error', function(err) {\n writeStream.end();\n call(err);\n });\n\n writeStream.addListener('error', function(err) {\n readStream.destroy();\n call(err);\n });\n}\nexports.pump = exports.deprecate(pump,\n 'util.pump() is deprecated. Use readableStream.pipe() instead.');\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = function(ctor, superCtor) {\n ctor.super_ = superCtor;\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n};\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || typeof add !== 'object') return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n});","sourceLength":15322,"scriptType":2,"compilationType":0,"context":{"ref":51},"text":"util.js (lines: 581)"},{"handle":54,"type":"script","name":"_linklist.js","id":25,"lineOffset":0,"columnOffset":0,"lineCount":78,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction init(list) {\n list._idleNext = list;\n list._idlePrev = list;\n}\nexports.init = init;\n\n\n// show the most idle item\nfunction peek(list) {\n if (list._idlePrev == list) return null;\n return list._idlePrev;\n}\nexports.peek = peek;\n\n\n// remove the most idle item from the list\nfunction shift(list) {\n var first = list._idlePrev;\n remove(first);\n return first;\n}\nexports.shift = shift;\n\n\n// remove a item from its list\nfunction remove(item) {\n if (item._idleNext) {\n item._idleNext._idlePrev = item._idlePrev;\n }\n\n if (item._idlePrev) {\n item._idlePrev._idleNext = item._idleNext;\n }\n\n item._idleNext = null;\n item._idlePrev = null;\n}\nexports.remove = remove;\n\n\n// remove a item from its list and place at the end.\nfunction append(list, item) {\n remove(item);\n item._idleNext = list._idleNext;\n list._idleNext._idlePrev = item;\n item._idlePrev = list;\n list._idleNext = item;\n}\nexports.append = append;\n\n\nfunction isEmpty(list) {\n return list._idleNext === list;\n}\nexports.isEmpty = isEmpty;\n\n});","sourceLength":2217,"scriptType":2,"compilationType":0,"context":{"ref":53},"text":"_linklist.js (lines: 78)"},{"handle":34,"type":"script","name":"timers.js","id":24,"lineOffset":0,"columnOffset":0,"lineCount":364,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar Timer = process.binding('timer_wrap').Timer;\nvar L = require('_linklist');\nvar assert = require('assert').ok;\n\n// Timeout values > TIMEOUT_MAX are set to 1.\nvar TIMEOUT_MAX = 2147483647; // 2^31-1\n\nvar debug;\nif (process.env.NODE_DEBUG && /timer/.test(process.env.NODE_DEBUG)) {\n debug = function() { require('util').error.apply(this, arguments); };\n} else {\n debug = function() { };\n}\n\n\n// IDLE TIMEOUTS\n//\n// Because often many sockets will have the same idle timeout we will not\n// use one timeout watcher per item. It is too much overhead. Instead\n// we'll use a single watcher for all sockets with the same timeout value\n// and a linked list. This technique is described in the libev manual:\n// http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Be_smart_about_timeouts\n\n// Object containing all lists, timers\n// key = time in milliseconds\n// value = list\nvar lists = {};\n\n// the main function - creates lists on demand and the watchers associated\n// with them.\nfunction insert(item, msecs) {\n item._idleStart = Date.now();\n item._idleTimeout = msecs;\n\n if (msecs < 0) return;\n\n var list;\n\n if (lists[msecs]) {\n list = lists[msecs];\n } else {\n list = new Timer();\n list.start(msecs, 0);\n\n L.init(list);\n\n lists[msecs] = list;\n list.msecs = msecs;\n list.ontimeout = listOnTimeout;\n }\n\n L.append(list, item);\n assert(!L.isEmpty(list)); // list is not empty\n}\n\nfunction listOnTimeout() {\n var msecs = this.msecs;\n var list = this;\n\n debug('timeout callback ' + msecs);\n\n var now = Date.now();\n debug('now: ' + now);\n\n var first;\n while (first = L.peek(list)) {\n var diff = now - first._idleStart;\n if (diff < msecs) {\n list.start(msecs - diff, 0);\n debug(msecs + ' list wait because diff is ' + diff);\n return;\n } else {\n L.remove(first);\n assert(first !== L.peek(list));\n\n if (!first._onTimeout) continue;\n\n // v0.4 compatibility: if the timer callback throws and the\n // domain or uncaughtException handler ignore the exception,\n // other timers that expire on this tick should still run.\n //\n // https://github.com/joyent/node/issues/2631\n var domain = first.domain;\n if (domain && domain._disposed) continue;\n try {\n if (domain)\n domain.enter();\n var threw = true;\n first._onTimeout();\n if (domain)\n domain.exit();\n threw = false;\n } finally {\n if (threw) {\n process.nextTick(function() {\n list.ontimeout();\n });\n }\n }\n }\n }\n\n debug(msecs + ' list empty');\n assert(L.isEmpty(list));\n list.close();\n delete lists[msecs];\n}\n\n\nvar unenroll = exports.unenroll = function(item) {\n L.remove(item);\n\n var list = lists[item._idleTimeout];\n // if empty then stop the watcher\n debug('unenroll');\n if (list && L.isEmpty(list)) {\n debug('unenroll: list empty');\n list.close();\n delete lists[item._idleTimeout];\n }\n // if active is called later, then we want to make sure not to insert again\n item._idleTimeout = -1;\n};\n\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n // if this item was already in a list somewhere\n // then we should unenroll it from that\n if (item._idleNext) unenroll(item);\n\n // Ensure that msecs fits into signed int32\n if (msecs > 0x7fffffff) {\n msecs = 0x7fffffff;\n }\n\n item._idleTimeout = msecs;\n L.init(item);\n};\n\n\n// call this whenever the item is active (not idle)\n// it will reset its timeout.\nexports.active = function(item) {\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n\n var list = lists[msecs];\n if (!list || L.isEmpty(list)) {\n insert(item, msecs);\n } else {\n item._idleStart = Date.now();\n L.append(list, item);\n }\n }\n};\n\n\n/*\n * DOM-style timers\n */\n\n\nexports.setTimeout = function(callback, after) {\n var timer;\n\n after *= 1; // coalesce to number or NaN\n\n if (!(after >= 1 && after <= TIMEOUT_MAX)) {\n after = 1; // schedule on next tick, follows browser behaviour\n }\n\n timer = new Timeout(after);\n\n if (arguments.length <= 2) {\n timer._onTimeout = callback;\n } else {\n /*\n * Sometimes setTimeout is called with arguments, EG\n *\n * setTimeout(callback, 2000, \"hello\", \"world\")\n *\n * If that's the case we need to call the callback with\n * those args. The overhead of an extra closure is not\n * desired in the normal case.\n */\n var args = Array.prototype.slice.call(arguments, 2);\n timer._onTimeout = function() {\n callback.apply(timer, args);\n }\n }\n\n if (process.domain) timer.domain = process.domain;\n\n exports.active(timer);\n\n return timer;\n};\n\n\nexports.clearTimeout = function(timer) {\n if (timer && (timer.ontimeout || timer._onTimeout)) {\n timer.ontimeout = timer._onTimeout = null;\n if (timer instanceof Timer || timer instanceof Timeout) {\n timer.close(); // for after === 0\n } else {\n exports.unenroll(timer);\n }\n }\n};\n\n\nexports.setInterval = function(callback, repeat) {\n var timer = new Timer();\n\n if (process.domain) timer.domain = process.domain;\n\n repeat *= 1; // coalesce to number or NaN\n\n if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) {\n repeat = 1; // schedule on next tick, follows browser behaviour\n }\n\n var args = Array.prototype.slice.call(arguments, 2);\n timer.ontimeout = function() {\n callback.apply(timer, args);\n }\n\n timer.start(repeat, repeat);\n return timer;\n};\n\n\nexports.clearInterval = function(timer) {\n if (timer instanceof Timer) {\n timer.ontimeout = null;\n timer.close();\n }\n};\n\nvar Timeout = function(after) {\n this._idleTimeout = after;\n this._idlePrev = this;\n this._idleNext = this;\n this._idleStart = null;\n this._onTimeout = null;\n};\n\nTimeout.prototype.unref = function() {\n if (!this._handle) {\n var now = Date.now();\n if (!this._idleStart) this._idleStart = now;\n var delay = this._idleStart + this._idleTimeout - now;\n if (delay < 0) delay = 0;\n exports.unenroll(this);\n this._handle = new Timer();\n this._handle.ontimeout = this._onTimeout;\n this._handle.start(delay, 0);\n this._handle.domain = this.domain;\n this._handle.unref();\n } else {\n this._handle.unref();\n }\n};\n\nTimeout.prototype.ref = function() {\n if (this._handle)\n this._handle.ref();\n};\n\nTimeout.prototype.close = function() {\n this._onTimeout = null;\n if (this._handle) {\n this._handle.ontimeout = null;\n this._handle.close();\n } else {\n exports.unenroll(this);\n }\n};\n\n\nvar immediateQueue = {};\nL.init(immediateQueue);\n\n\nfunction processImmediate() {\n var immediate = L.shift(immediateQueue);\n\n if (L.isEmpty(immediateQueue)) {\n process._needImmediateCallback = false;\n }\n\n if (immediate._onImmediate) {\n if (immediate.domain) immediate.domain.enter();\n\n immediate._onImmediate();\n\n if (immediate.domain) immediate.domain.exit();\n }\n}\n\n\nexports.setImmediate = function(callback) {\n var immediate = {}, args;\n\n L.init(immediate);\n\n immediate._onImmediate = callback;\n\n if (arguments.length > 1) {\n args = Array.prototype.slice.call(arguments, 1);\n\n immediate._onImmediate = function() {\n callback.apply(immediate, args);\n };\n }\n\n if (!process._needImmediateCallback) {\n process._needImmediateCallback = true;\n process._immediateCallback = processImmediate;\n }\n\n if (process.domain) immediate.domain = process.domain;\n\n L.append(immediateQueue, immediate);\n\n return immediate;\n};\n\n\nexports.clearImmediate = function(immediate) {\n if (!immediate) return;\n\n immediate._onImmediate = undefined;\n\n L.remove(immediate);\n\n if (L.isEmpty(immediateQueue)) {\n process._needImmediateCallback = false;\n }\n};\n\n});","sourceLength":8922,"scriptType":2,"compilationType":0,"context":{"ref":33},"text":"timers.js (lines: 364)"},{"handle":56,"type":"script","name":"stream.js","id":27,"lineOffset":0,"columnOffset":0,"lineCount":129,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Stream;\n\nvar EE = require('events').EventEmitter;\nvar util = require('util');\n\nutil.inherits(Stream, EE);\nStream.Readable = require('_stream_readable');\nStream.Writable = require('_stream_writable');\nStream.Duplex = require('_stream_duplex');\nStream.Transform = require('_stream_transform');\nStream.PassThrough = require('_stream_passthrough');\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\n\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\n};\n\n});","sourceLength":3635,"scriptType":2,"compilationType":0,"context":{"ref":55},"text":"stream.js (lines: 129)"},{"handle":58,"type":"script","name":"_stream_passthrough.js","id":32,"lineOffset":0,"columnOffset":0,"lineCount":43,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\nmodule.exports = PassThrough;\n\nvar Transform = require('_stream_transform');\nvar util = require('util');\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough))\n return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function(chunk, encoding, cb) {\n cb(null, chunk);\n};\n\n});","sourceLength":1707,"scriptType":2,"compilationType":0,"context":{"ref":57},"text":"_stream_passthrough.js (lines: 43)"},{"handle":60,"type":"script","name":"_stream_duplex.js","id":30,"lineOffset":0,"columnOffset":0,"lineCount":71,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\nmodule.exports = Duplex;\nvar util = require('util');\nvar Readable = require('_stream_readable');\nvar Writable = require('_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\nObject.keys(Writable.prototype).forEach(function(method) {\n if (!Duplex.prototype[method])\n Duplex.prototype[method] = Writable.prototype[method];\n});\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex))\n return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false)\n this.readable = false;\n\n if (options && options.writable === false)\n this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false)\n this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended)\n return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n process.nextTick(this.end.bind(this));\n}\n\n});","sourceLength":2530,"scriptType":2,"compilationType":0,"context":{"ref":59},"text":"_stream_duplex.js (lines: 71)"},{"handle":6,"type":"script","name":"module.js","id":23,"lineOffset":0,"columnOffset":0,"lineCount":539,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar NativeModule = require('native_module');\nvar Script = process.binding('evals').NodeScript;\nvar runInThisContext = Script.runInThisContext;\nvar runInNewContext = Script.runInNewContext;\nvar assert = require('assert').ok;\n\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n\nfunction Module(id, parent) {\n this.id = id;\n this.exports = {};\n this.parent = parent;\n if (parent && parent.children) {\n parent.children.push(this);\n }\n\n this.filename = null;\n this.loaded = false;\n this.children = [];\n}\nmodule.exports = Module;\n\n// Set the environ variable NODE_MODULE_CONTEXTS=1 to make node load all\n// modules in thier own context.\nModule._contextLoad = (+process.env['NODE_MODULE_CONTEXTS'] > 0);\nModule._cache = {};\nModule._pathCache = {};\nModule._extensions = {};\nvar modulePaths = [];\nModule.globalPaths = [];\n\nModule.wrapper = NativeModule.wrapper;\nModule.wrap = NativeModule.wrap;\n\nvar path = NativeModule.require('path');\n\nModule._debug = function() {};\nif (process.env.NODE_DEBUG && /module/.test(process.env.NODE_DEBUG)) {\n Module._debug = function(x) {\n console.error(x);\n };\n}\n\n\n// We use this alias for the preprocessor that filters it out\nvar debug = Module._debug;\n\n\n// given a module name, and a list of paths to test, returns the first\n// matching file in the following precedence.\n//\n// require(\"a.<ext>\")\n// -> a.<ext>\n//\n// require(\"a\")\n// -> a\n// -> a.<ext>\n// -> a/index.<ext>\n\nfunction statPath(path) {\n var fs = NativeModule.require('fs');\n try {\n return fs.statSync(path);\n } catch (ex) {}\n return false;\n}\n\n// check if the directory is a package.json dir\nvar packageCache = {};\n\nfunction readPackage(requestPath) {\n if (hasOwnProperty(packageCache, requestPath)) {\n return packageCache[requestPath];\n }\n\n var fs = NativeModule.require('fs');\n try {\n var jsonPath = path.resolve(requestPath, 'package.json');\n var json = fs.readFileSync(jsonPath, 'utf8');\n } catch (e) {\n return false;\n }\n\n try {\n var pkg = packageCache[requestPath] = JSON.parse(json);\n } catch (e) {\n e.path = jsonPath;\n e.message = 'Error parsing ' + jsonPath + ': ' + e.message;\n throw e;\n }\n return pkg;\n}\n\nfunction tryPackage(requestPath, exts) {\n var pkg = readPackage(requestPath);\n\n if (!pkg || !pkg.main) return false;\n\n var filename = path.resolve(requestPath, pkg.main);\n return tryFile(filename) || tryExtensions(filename, exts) ||\n tryExtensions(path.resolve(filename, 'index'), exts);\n}\n\n// In order to minimize unnecessary lstat() calls,\n// this cache is a list of known-real paths.\n// Set to an empty object to reset.\nModule._realpathCache = {};\n\n// check if the file exists and is not a directory\nfunction tryFile(requestPath) {\n var fs = NativeModule.require('fs');\n var stats = statPath(requestPath);\n if (stats && !stats.isDirectory()) {\n return fs.realpathSync(requestPath, Module._realpathCache);\n }\n return false;\n}\n\n// given a path check a the file exists with any of the set extensions\nfunction tryExtensions(p, exts) {\n for (var i = 0, EL = exts.length; i < EL; i++) {\n var filename = tryFile(p + exts[i]);\n\n if (filename) {\n return filename;\n }\n }\n return false;\n}\n\n\nModule._findPath = function(request, paths) {\n var exts = Object.keys(Module._extensions);\n\n if (request.charAt(0) === '/') {\n paths = [''];\n }\n\n var trailingSlash = (request.slice(-1) === '/');\n\n var cacheKey = JSON.stringify({request: request, paths: paths});\n if (Module._pathCache[cacheKey]) {\n return Module._pathCache[cacheKey];\n }\n\n // For each path\n for (var i = 0, PL = paths.length; i < PL; i++) {\n var basePath = path.resolve(paths[i], request);\n var filename;\n\n if (!trailingSlash) {\n // try to join the request to the path\n filename = tryFile(basePath);\n\n if (!filename && !trailingSlash) {\n // try it with each of the extensions\n filename = tryExtensions(basePath, exts);\n }\n }\n\n if (!filename) {\n filename = tryPackage(basePath, exts);\n }\n\n if (!filename) {\n // try it with each of the extensions at \"index\"\n filename = tryExtensions(path.resolve(basePath, 'index'), exts);\n }\n\n if (filename) {\n Module._pathCache[cacheKey] = filename;\n return filename;\n }\n }\n return false;\n};\n\n// 'from' is the __dirname of the module.\nModule._nodeModulePaths = function(from) {\n // guarantee that 'from' is absolute.\n from = path.resolve(from);\n\n // note: this approach *only* works when the path is guaranteed\n // to be absolute. Doing a fully-edge-case-correct path.split\n // that works on both Windows and Posix is non-trivial.\n var splitRe = process.platform === 'win32' ? /[\\/\\\\]/ : /\\//;\n // yes, '/' works on both, but let's be a little canonical.\n var joiner = process.platform === 'win32' ? '\\\\' : '/';\n var paths = [];\n var parts = from.split(splitRe);\n\n for (var tip = parts.length - 1; tip >= 0; tip--) {\n // don't search in .../node_modules/node_modules\n if (parts[tip] === 'node_modules') continue;\n var dir = parts.slice(0, tip + 1).concat('node_modules').join(joiner);\n paths.push(dir);\n }\n\n return paths;\n};\n\n\nModule._resolveLookupPaths = function(request, parent) {\n if (NativeModule.exists(request)) {\n return [request, []];\n }\n\n var start = request.substring(0, 2);\n if (start !== './' && start !== '..') {\n var paths = modulePaths;\n if (parent) {\n if (!parent.paths) parent.paths = [];\n paths = parent.paths.concat(paths);\n }\n return [request, paths];\n }\n\n // with --eval, parent.id is not set and parent.filename is null\n if (!parent || !parent.id || !parent.filename) {\n // make require('./path/to/foo') work - normally the path is taken\n // from realpath(__filename) but with eval there is no filename\n var mainPaths = ['.'].concat(modulePaths);\n mainPaths = Module._nodeModulePaths('.').concat(mainPaths);\n return [request, mainPaths];\n }\n\n // Is the parent an index module?\n // We can assume the parent has a valid extension,\n // as it already has been accepted as a module.\n var isIndex = /^index\\.\\w+?$/.test(path.basename(parent.filename));\n var parentIdPath = isIndex ? parent.id : path.dirname(parent.id);\n var id = path.resolve(parentIdPath, request);\n\n // make sure require('./path') and require('path') get distinct ids, even\n // when called from the toplevel js file\n if (parentIdPath === '.' && id.indexOf('/') === -1) {\n id = './' + id;\n }\n\n debug('RELATIVE: requested:' + request +\n ' set ID to: ' + id + ' from ' + parent.id);\n\n return [id, [path.dirname(parent.filename)]];\n};\n\n\nModule._load = function(request, parent, isMain) {\n if (parent) {\n debug('Module._load REQUEST ' + (request) + ' parent: ' + parent.id);\n }\n\n var filename = Module._resolveFilename(request, parent);\n\n var cachedModule = Module._cache[filename];\n if (cachedModule) {\n return cachedModule.exports;\n }\n\n if (NativeModule.exists(filename)) {\n // REPL is a special case, because it needs the real require.\n if (filename == 'repl') {\n var replModule = new Module('repl');\n replModule._compile(NativeModule.getSource('repl'), 'repl.js');\n NativeModule._cache.repl = replModule;\n return replModule.exports;\n }\n\n debug('load native module ' + request);\n return NativeModule.require(filename);\n }\n\n var module = new Module(filename, parent);\n\n if (isMain) {\n process.mainModule = module;\n module.id = '.';\n }\n\n Module._cache[filename] = module;\n\n var hadException = true;\n\n try {\n module.load(filename);\n hadException = false;\n } finally {\n if (hadException) {\n delete Module._cache[filename];\n }\n }\n\n return module.exports;\n};\n\nModule._resolveFilename = function(request, parent) {\n if (NativeModule.exists(request)) {\n return request;\n }\n\n var resolvedModule = Module._resolveLookupPaths(request, parent);\n var id = resolvedModule[0];\n var paths = resolvedModule[1];\n\n // look up the filename first, since that's the cache key.\n debug('looking for ' + JSON.stringify(id) +\n ' in ' + JSON.stringify(paths));\n\n var filename = Module._findPath(request, paths);\n if (!filename) {\n var err = new Error(\"Cannot find module '\" + request + \"'\");\n err.code = 'MODULE_NOT_FOUND';\n throw err;\n }\n return filename;\n};\n\n\nModule.prototype.load = function(filename) {\n debug('load ' + JSON.stringify(filename) +\n ' for module ' + JSON.stringify(this.id));\n\n assert(!this.loaded);\n this.filename = filename;\n this.paths = Module._nodeModulePaths(path.dirname(filename));\n\n var extension = path.extname(filename) || '.js';\n if (!Module._extensions[extension]) extension = '.js';\n Module._extensions[extension](this, filename);\n this.loaded = true;\n};\n\n\nModule.prototype.require = function(path) {\n assert(typeof path === 'string', 'path must be a string');\n assert(path, 'missing path');\n return Module._load(path, this);\n};\n\n\n// Resolved path to process.argv[1] will be lazily placed here\n// (needed for setting breakpoint when called with --debug-brk)\nvar resolvedArgv;\n\n\n// Returns exception if any\nModule.prototype._compile = function(content, filename) {\n var self = this;\n // remove shebang\n content = content.replace(/^\\#\\!.*/, '');\n\n function require(path) {\n return self.require(path);\n }\n\n require.resolve = function(request) {\n return Module._resolveFilename(request, self);\n };\n\n Object.defineProperty(require, 'paths', { get: function() {\n throw new Error('require.paths is removed. Use ' +\n 'node_modules folders, or the NODE_PATH ' +\n 'environment variable instead.');\n }});\n\n require.main = process.mainModule;\n\n // Enable support to add extra extension types\n require.extensions = Module._extensions;\n require.registerExtension = function() {\n throw new Error('require.registerExtension() removed. Use ' +\n 'require.extensions instead.');\n };\n\n require.cache = Module._cache;\n\n var dirname = path.dirname(filename);\n\n if (Module._contextLoad) {\n if (self.id !== '.') {\n debug('load submodule');\n // not root module\n var sandbox = {};\n for (var k in global) {\n sandbox[k] = global[k];\n }\n sandbox.require = require;\n sandbox.exports = self.exports;\n sandbox.__filename = filename;\n sandbox.__dirname = dirname;\n sandbox.module = self;\n sandbox.global = sandbox;\n sandbox.root = root;\n\n return runInNewContext(content, sandbox, filename, true);\n }\n\n debug('load root module');\n // root module\n global.require = require;\n global.exports = self.exports;\n global.__filename = filename;\n global.__dirname = dirname;\n global.module = self;\n\n return runInThisContext(content, filename, true);\n }\n\n // create wrapper function\n var wrapper = Module.wrap(content);\n\n var compiledWrapper = runInThisContext(wrapper, filename, true);\n if (global.v8debug) {\n if (!resolvedArgv) {\n // we enter the repl if we're not given a filename argument.\n if (process.argv[1]) {\n resolvedArgv = Module._resolveFilename(process.argv[1], null);\n } else {\n resolvedArgv = 'repl';\n }\n }\n\n // Set breakpoint on module start\n if (filename === resolvedArgv) {\n global.v8debug.Debug.setBreakPoint(compiledWrapper, 0, 0);\n }\n }\n var args = [self.exports, require, self, filename, dirname];\n return compiledWrapper.apply(self.exports, args);\n};\n\n\nfunction stripBOM(content) {\n // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n // because the buffer-to-string conversion in `fs.readFileSync()`\n // translates it to FEFF, the UTF-16 BOM.\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n\n// Native extension for .js\nModule._extensions['.js'] = function(module, filename) {\n var content = NativeModule.require('fs').readFileSync(filename, 'utf8');\n module._compile(stripBOM(content), filename);\n};\n\n\n// Native extension for .json\nModule._extensions['.json'] = function(module, filename) {\n var content = NativeModule.require('fs').readFileSync(filename, 'utf8');\n try {\n module.exports = JSON.parse(stripBOM(content));\n } catch (err) {\n err.message = filename + ': ' + err.message;\n throw err;\n }\n};\n\n\n//Native extension for .node\nModule._extensions['.node'] = process.dlopen;\n\n\n// bootstrap main module.\nModule.runMain = function() {\n // Load the main module--the command line argument.\n Module._load(process.argv[1], null, true);\n // Handle any nextTicks added in the first tick of the program\n process._tickCallback();\n};\n\nModule._initPaths = function() {\n var isWindows = process.platform === 'win32';\n\n if (isWindows) {\n var homeDir = process.env.USERPROFILE;\n } else {\n var homeDir = process.env.HOME;\n }\n\n var paths = [path.resolve(process.execPath, '..', '..', 'lib', 'node')];\n\n if (homeDir) {\n paths.unshift(path.resolve(homeDir, '.node_libraries'));\n paths.unshift(path.resolve(homeDir, '.node_modules'));\n }\n\n if (process.env['NODE_PATH']) {\n var splitter = isWindows ? ';' : ':';\n paths = process.env['NODE_PATH'].split(splitter).concat(paths);\n }\n\n modulePaths = paths;\n\n // clone as a read-only copy, for introspection.\n Module.globalPaths = modulePaths.slice(0);\n};\n\n// bootstrap repl\nModule.requireRepl = function() {\n return Module._load('repl', '.');\n};\n\nModule._initPaths();\n\n// backwards compatibility\nModule.Module = Module;\n\n});","sourceLength":14908,"scriptType":2,"compilationType":0,"context":{"ref":5},"text":"module.js (lines: 539)"},{"handle":62,"type":"script","name":"_stream_readable.js","id":28,"lineOffset":0,"columnOffset":0,"lineCount":888,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Readable;\nReadable.ReadableState = ReadableState;\n\nvar EE = require('events').EventEmitter;\nvar Stream = require('stream');\nvar util = require('util');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nfunction ReadableState(options, stream) {\n options = options || {};\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;\n\n // cast to ints.\n this.highWaterMark = ~~this.highWaterMark;\n\n this.buffer = [];\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = false;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // In streams that never have any data, and do push(null) right away,\n // the consumer can miss the 'end' event if they do some I/O before\n // consuming the stream. So, we don't emit('end') until some reading\n // happens.\n this.calledRead = false;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, becuase any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n // when piping, we only care about 'readable' events that happen\n // after read()ing all the bytes and not getting any pushback.\n this.ranOut = false;\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n if (options.encoding) {\n if (!StringDecoder)\n StringDecoder = require('string_decoder').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n }\n}\n\nfunction Readable(options) {\n if (!(this instanceof Readable))\n return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n Stream.call(this);\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function(chunk) {\n var state = this._readableState;\n if (typeof chunk === 'string' && !state.objectMode)\n chunk = new Buffer(chunk, arguments[1]);\n return readableAddChunk(this, state, chunk, false);\n};\n\nReadable.prototype.unshift = function(chunk) {\n var state = this._readableState;\n if (typeof chunk === 'string' && !state.objectMode)\n chunk = new Buffer(chunk, arguments[1]);\n return readableAddChunk(this, state, chunk, true);\n};\n\nfunction readableAddChunk(stream, state, chunk, addToFront) {\n state.reading = false;\n\n var er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (chunk === null || chunk === undefined) {\n onEofChunk(stream, state);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (state.decoder)\n chunk = state.decoder.write(chunk);\n\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront)\n state.buffer.unshift(chunk);\n else\n state.buffer.push(chunk);\n\n if (state.needReadable)\n emitReadable(stream);\n\n maybeReadMore(stream, state);\n }\n\n return needMoreData(state);\n}\n\n\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended &&\n (state.needReadable ||\n state.length < state.highWaterMark ||\n state.length === 0);\n}\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function(enc) {\n if (!StringDecoder)\n StringDecoder = require('string_decoder').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n};\n\n// Don't raise the hwm > 128MB\nvar MAX_HWM = 0x800000;\nfunction roundUpToNextPowerOf2(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2\n n--;\n for (var p = 1; p < 32; p <<= 1) n |= n >> p;\n n++;\n }\n return n;\n}\n\nfunction howMuchToRead(n, state) {\n if (state.length === 0 && state.ended)\n return 0;\n\n if (state.objectMode)\n return n === 0 ? 0 : 1;\n\n if (isNaN(n) || n === null) {\n // only flow one buffer at a time\n if (state.flowing && state.buffer.length)\n return state.buffer[0].length;\n else\n return state.length;\n }\n\n if (n <= 0)\n return 0;\n\n // If we're asking for more than the target buffer level,\n // then raise the water mark. Bump up to the next highest\n // power of 2, to prevent increasing it excessively in tiny\n // amounts.\n if (n > state.highWaterMark)\n state.highWaterMark = roundUpToNextPowerOf2(n);\n\n // don't have that much. return null, unless we've ended.\n if (n > state.length) {\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n } else\n return state.length;\n }\n\n return n;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function(n) {\n var state = this._readableState;\n state.calledRead = true;\n var nOrig = n;\n\n if (typeof n !== 'number' || n > 0)\n state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 &&\n state.needReadable &&\n (state.length >= state.highWaterMark || state.ended)) {\n emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0)\n endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length - n <= state.highWaterMark)\n doRead = true;\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading)\n doRead = false;\n\n if (doRead) {\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0)\n state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n }\n\n // If _read called its callback synchronously, then `reading`\n // will be false, and we need to re-evaluate how much data we\n // can return to the user.\n if (doRead && !state.reading)\n n = howMuchToRead(nOrig, state);\n\n var ret;\n if (n > 0)\n ret = fromList(n, state);\n else\n ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n }\n\n state.length -= n;\n\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (state.length === 0 && !state.ended)\n state.needReadable = true;\n\n // If we happened to read() exactly the remaining amount in the\n // buffer, and the EOF has been seen at this point, then make sure\n // that we emit 'end' on the very next tick.\n if (state.ended && !state.endEmitted && state.length === 0)\n endReadable(this);\n\n return ret;\n};\n\nfunction chunkInvalid(state, chunk) {\n var er = null;\n if (!Buffer.isBuffer(chunk) &&\n 'string' !== typeof chunk &&\n chunk !== null &&\n chunk !== undefined &&\n !state.objectMode &&\n !er) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n\nfunction onEofChunk(stream, state) {\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // if we've ended and we have some data left, then emit\n // 'readable' now to make sure it gets picked up.\n if (state.length > 0)\n emitReadable(stream);\n else\n endReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (state.emittedReadable)\n return;\n\n state.emittedReadable = true;\n if (state.sync)\n process.nextTick(function() {\n emitReadable_(stream);\n });\n else\n emitReadable_(stream);\n}\n\nfunction emitReadable_(stream) {\n stream.emit('readable');\n}\n\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(function() {\n maybeReadMore_(stream, state);\n });\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended &&\n state.length < state.highWaterMark) {\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;\n else\n len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function(n) {\n this.emit('error', new Error('not implemented'));\n};\n\nReadable.prototype.pipe = function(dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) &&\n dest !== process.stdout &&\n dest !== process.stderr;\n\n var endFn = doEnd ? onend : cleanup;\n if (state.endEmitted)\n process.nextTick(endFn);\n else\n src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable) {\n if (readable !== src) return;\n cleanup();\n }\n\n function onend() {\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n function cleanup() {\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', cleanup);\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (!dest._writableState || dest._writableState.needDrain)\n ondrain();\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n unpipe();\n if (EE.listenerCount(dest, 'error') === 0)\n dest.emit('error', er);\n }\n dest.once('error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n // the handler that waits for readable events after all\n // the data gets sucked out in flow.\n // This would be easier to follow with a .once() handler\n // in flow(), but that is too slow.\n this.on('readable', pipeOnReadable);\n\n state.flowing = true;\n process.nextTick(function() {\n flow(src);\n });\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function() {\n var dest = this;\n var state = src._readableState;\n state.awaitDrain--;\n if (state.awaitDrain === 0)\n flow(src);\n };\n}\n\nfunction flow(src) {\n var state = src._readableState;\n var chunk;\n state.awaitDrain = 0;\n\n function write(dest, i, list) {\n var written = dest.write(chunk);\n if (false === written) {\n state.awaitDrain++;\n }\n }\n\n while (state.pipesCount && null !== (chunk = src.read())) {\n\n if (state.pipesCount === 1)\n write(state.pipes, 0, null);\n else\n state.pipes.forEach(write);\n\n src.emit('data', chunk);\n\n // if anyone needs a drain, then we have to wait for that.\n if (state.awaitDrain > 0)\n return;\n }\n\n // if every destination was unpiped, either before entering this\n // function, or in the while loop, then stop flowing.\n //\n // NB: This is a pretty rare edge case.\n if (state.pipesCount === 0) {\n state.flowing = false;\n\n // if there were data event listeners added, then switch to old mode.\n if (EE.listenerCount(src, 'data') > 0)\n emitDataEvents(src);\n return;\n }\n\n // at this point, no one needed a drain, so we just ran out of data\n // on the next readable event, start it over again.\n state.ranOut = true;\n}\n\nfunction pipeOnReadable() {\n if (this._readableState.ranOut) {\n this._readableState.ranOut = false;\n flow(this);\n }\n}\n\n\nReadable.prototype.unpipe = function(dest) {\n var state = this._readableState;\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0)\n return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes)\n return this;\n\n if (!dest)\n dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n this.removeListener('readable', pipeOnReadable);\n state.flowing = false;\n if (dest)\n dest.emit('unpipe', this);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n this.removeListener('readable', pipeOnReadable);\n state.flowing = false;\n\n for (var i = 0; i < len; i++)\n dests[i].emit('unpipe', this);\n return this;\n }\n\n // try to find the right one.\n var i = state.pipes.indexOf(dest);\n if (i === -1)\n return this;\n\n state.pipes.splice(i, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1)\n state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function(ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data' && !this._readableState.flowing)\n emitDataEvents(this);\n\n if (ev === 'readable' && this.readable) {\n var state = this._readableState;\n if (!state.readableListening) {\n state.readableListening = true;\n state.emittedReadable = false;\n state.needReadable = true;\n if (!state.reading) {\n this.read(0);\n } else if (state.length) {\n emitReadable(this, state);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function() {\n emitDataEvents(this);\n this.read(0);\n this.emit('resume');\n};\n\nReadable.prototype.pause = function() {\n emitDataEvents(this, true);\n this.emit('pause');\n};\n\nfunction emitDataEvents(stream, startPaused) {\n var state = stream._readableState;\n\n if (state.flowing) {\n // https://github.com/isaacs/readable-stream/issues/16\n throw new Error('Cannot switch to old mode now.');\n }\n\n var paused = startPaused || false;\n var readable = false;\n\n // convert to an old-style stream.\n stream.readable = true;\n stream.pipe = Stream.prototype.pipe;\n stream.on = stream.addListener = Stream.prototype.on;\n\n stream.on('readable', function() {\n readable = true;\n\n var c;\n while (!paused && (null !== (c = stream.read())))\n stream.emit('data', c);\n\n if (c === null) {\n readable = false;\n stream._readableState.needReadable = true;\n }\n });\n\n stream.pause = function() {\n paused = true;\n this.emit('pause');\n };\n\n stream.resume = function() {\n paused = false;\n if (readable)\n process.nextTick(function() {\n stream.emit('readable');\n });\n else\n this.read(0);\n this.emit('resume');\n };\n\n // now make it start, just in case it hadn't already.\n stream.emit('readable');\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function(stream) {\n var state = this._readableState;\n var paused = false;\n\n var self = this;\n stream.on('end', function() {\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length)\n self.push(chunk);\n }\n state.ended = true;\n\n self.push(null);\n });\n\n stream.on('data', function(chunk) {\n if (state.decoder)\n chunk = state.decoder.write(chunk);\n if (!chunk || !chunk.length)\n return;\n\n var ret = self.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (typeof stream[i] === 'function' &&\n typeof this[i] === 'undefined') {\n this[i] = function(method) { return function() {\n return stream[method].apply(stream, arguments);\n }}(i);\n }\n }\n\n // proxy certain important events.\n var events = ['error', 'close', 'destroy', 'pause', 'resume'];\n events.forEach(function(ev) {\n stream.on(ev, self.emit.bind(self, ev));\n });\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n self._read = function(n) {\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return self;\n};\n\n\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\nfunction fromList(n, state) {\n var list = state.buffer;\n var length = state.length;\n var stringMode = !!state.decoder;\n var objectMode = !!state.objectMode;\n var ret;\n\n // nothing in the list, definitely empty.\n if (list.length === 0)\n return null;\n\n if (length === 0)\n ret = null;\n else if (objectMode)\n ret = list.shift();\n else if (!n || n >= length) {\n // read it all, truncate the array.\n if (stringMode)\n ret = list.join('');\n else\n ret = Buffer.concat(list, length);\n list.length = 0;\n } else {\n // read just some of it.\n if (n < list[0].length) {\n // just take a part of the first list item.\n // slice is the same for buffers and strings.\n var buf = list[0];\n ret = buf.slice(0, n);\n list[0] = buf.slice(n);\n } else if (n === list[0].length) {\n // first list is a perfect match\n ret = list.shift();\n } else {\n // complex case.\n // we have enough to cover it, but it spans past the first buffer.\n if (stringMode)\n ret = '';\n else\n ret = new Buffer(n);\n\n var c = 0;\n for (var i = 0, l = list.length; i < l && c < n; i++) {\n var buf = list[0];\n var cpy = Math.min(n - c, buf.length);\n\n if (stringMode)\n ret += buf.slice(0, cpy);\n else\n buf.copy(ret, c, 0, cpy);\n\n if (cpy < buf.length)\n list[0] = buf.slice(cpy);\n else\n list.shift();\n\n c += cpy;\n }\n }\n }\n\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0)\n throw new Error('endReadable called on non-empty stream');\n\n if (!state.endEmitted && state.calledRead) {\n state.ended = true;\n state.endEmitted = true;\n process.nextTick(function() {\n stream.readable = false;\n stream.emit('end');\n });\n }\n}\n\n});","sourceLength":24200,"scriptType":2,"compilationType":0,"context":{"ref":61},"text":"_stream_readable.js (lines: 888)"},{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/server/app.js","id":33,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function (exports, require, module, __filename, __dirname) { var foo = \"ff\";\nconsole.log(foo)\n});","sourceLength":98,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/server/app.js (lines: 3)"},{"handle":64,"type":"script","name":"_stream_writable.js","id":29,"lineOffset":0,"columnOffset":0,"lineCount":361,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, cb), and it'll handle all\n// the drain event emission and buffering.\n\nmodule.exports = Writable;\nWritable.WritableState = WritableState;\n\nvar util = require('util');\nvar assert = require('assert');\nvar Stream = require('stream');\n\nutil.inherits(Writable, Stream);\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n}\n\nfunction WritableState(options, stream) {\n options = options || {};\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n // cast to ints.\n this.highWaterMark = ~~this.highWaterMark;\n\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, becuase any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function(er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.buffer = [];\n}\n\nfunction Writable(options) {\n // Writable ctor is applied to Duplexes, though they're not\n // instanceof Writable, they're instanceof Readable.\n if (!(this instanceof Writable) && !(this instanceof Stream.Duplex))\n return new Writable(options);\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function() {\n this.emit('error', new Error('Cannot pipe. Not readable.'));\n};\n\n\nfunction writeAfterEnd(stream, state, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n process.nextTick(function() {\n cb(er);\n });\n}\n\n// If we get something that is not a buffer, string, null, or undefined,\n// and we're not in objectMode, then that's an error.\n// Otherwise stream chunks are all considered to be of length=1, and the\n// watermarks determine how many objects to keep in the buffer, rather than\n// how many bytes or characters.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n if (!Buffer.isBuffer(chunk) &&\n 'string' !== typeof chunk &&\n chunk !== null &&\n chunk !== undefined &&\n !state.objectMode) {\n var er = new TypeError('Invalid non-string/buffer chunk');\n stream.emit('error', er);\n process.nextTick(function() {\n cb(er);\n });\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function(chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (!encoding)\n encoding = 'utf8';\n\n if (typeof cb !== 'function')\n cb = function() {};\n\n if (state.ended)\n writeAfterEnd(this, state, cb);\n else if (validChunk(this, state, chunk, cb))\n ret = writeOrBuffer(this, state, chunk, encoding, cb);\n\n return ret;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode &&\n state.decodeStrings !== false &&\n typeof chunk === 'string') {\n chunk = new Buffer(chunk, encoding);\n }\n return chunk;\n}\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, cb) {\n chunk = decodeChunk(state, chunk, encoding);\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n state.needDrain = !ret;\n\n if (state.writing)\n state.buffer.push(new WriteReq(chunk, encoding, cb));\n else\n doWrite(stream, state, len, chunk, encoding, cb);\n\n return ret;\n}\n\nfunction doWrite(stream, state, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n if (sync)\n process.nextTick(function() {\n cb(er);\n });\n else\n cb(er);\n\n stream.emit('error', er);\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er)\n onwriteError(stream, state, sync, er, cb);\n else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(stream, state);\n\n if (!finished && !state.bufferProcessing && state.buffer.length)\n clearBuffer(stream, state);\n\n if (sync) {\n process.nextTick(function() {\n afterWrite(stream, state, finished, cb);\n });\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished)\n onwriteDrain(stream, state);\n cb();\n if (finished)\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n\n for (var c = 0; c < state.buffer.length; c++) {\n var entry = state.buffer[c];\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, len, chunk, encoding, cb);\n\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n c++;\n break;\n }\n }\n\n state.bufferProcessing = false;\n if (c < state.buffer.length)\n state.buffer = state.buffer.slice(c);\n else\n state.buffer.length = 0;\n}\n\nWritable.prototype._write = function(chunk, encoding, cb) {\n cb(new Error('not implemented'));\n};\n\nWritable.prototype.end = function(chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (typeof chunk !== 'undefined' && chunk !== null)\n this.write(chunk, encoding);\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished)\n endWritable(this, state, cb);\n};\n\n\nfunction needFinish(stream, state) {\n return (state.ending &&\n state.length === 0 &&\n !state.finished &&\n !state.writing);\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(stream, state);\n if (need) {\n state.finished = true;\n stream.emit('finish');\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished)\n process.nextTick(cb);\n else\n stream.once('finish', cb);\n }\n state.ended = true;\n}\n\n});","sourceLength":10178,"scriptType":2,"compilationType":0,"context":{"ref":63},"text":"_stream_writable.js (lines: 361)"},{"handle":66,"type":"script","name":"fs.js","id":26,"lineOffset":0,"columnOffset":0,"lineCount":1761,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Maintainers, keep in mind that octal literals are not allowed\n// in strict mode. Use the decimal value and add a comment with\n// the octal value. Example:\n//\n// var mode = 438; /* mode=0666 */\n\nvar util = require('util');\nvar pathModule = require('path');\n\nvar binding = process.binding('fs');\nvar constants = process.binding('constants');\nvar fs = exports;\nvar Stream = require('stream').Stream;\nvar EventEmitter = require('events').EventEmitter;\n\nvar Readable = Stream.Readable;\nvar Writable = Stream.Writable;\n\nvar kMinPoolSpace = 128;\n\nvar O_APPEND = constants.O_APPEND || 0;\nvar O_CREAT = constants.O_CREAT || 0;\nvar O_DIRECTORY = constants.O_DIRECTORY || 0;\nvar O_EXCL = constants.O_EXCL || 0;\nvar O_NOCTTY = constants.O_NOCTTY || 0;\nvar O_NOFOLLOW = constants.O_NOFOLLOW || 0;\nvar O_RDONLY = constants.O_RDONLY || 0;\nvar O_RDWR = constants.O_RDWR || 0;\nvar O_SYMLINK = constants.O_SYMLINK || 0;\nvar O_SYNC = constants.O_SYNC || 0;\nvar O_TRUNC = constants.O_TRUNC || 0;\nvar O_WRONLY = constants.O_WRONLY || 0;\n\nvar isWindows = process.platform === 'win32';\n\nvar DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);\n\nfunction rethrow() {\n // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and\n // is fairly slow to generate.\n var callback;\n if (DEBUG) {\n var backtrace = new Error;\n callback = debugCallback;\n } else\n callback = missingCallback;\n\n return callback;\n\n function debugCallback(err) {\n if (err) {\n backtrace.message = err.message;\n err = backtrace;\n missingCallback(err);\n }\n }\n\n function missingCallback(err) {\n if (err) {\n if (process.throwDeprecation)\n throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs\n else if (!process.noDeprecation) {\n var msg = 'fs: missing callback ' + (err.stack || err.message);\n if (process.traceDeprecation)\n console.trace(msg);\n else\n console.error(msg);\n }\n }\n }\n}\n\nfunction maybeCallback(cb) {\n return typeof cb === 'function' ? cb : rethrow();\n}\n\n// Ensure that callbacks run in the global context. Only use this function\n// for callbacks that are passed to the binding layer, callbacks that are\n// invoked from JS already run in the proper scope.\nfunction makeCallback(cb) {\n if (typeof cb !== 'function') {\n return rethrow();\n }\n\n return function() {\n return cb.apply(null, arguments);\n };\n}\n\nfunction assertEncoding(encoding) {\n if (encoding && !Buffer.isEncoding(encoding)) {\n throw new Error('Unknown encoding: ' + encoding);\n }\n}\n\nfunction nullCheck(path, callback) {\n if (('' + path).indexOf('\\u0000') !== -1) {\n var er = new Error('Path must be a string without null bytes.');\n if (!callback)\n throw er;\n process.nextTick(function() {\n callback(er);\n });\n return false;\n }\n return true;\n}\n\nfs.Stats = binding.Stats;\n\nfs.Stats.prototype._checkModeProperty = function(property) {\n return ((this.mode & constants.S_IFMT) === property);\n};\n\nfs.Stats.prototype.isDirectory = function() {\n return this._checkModeProperty(constants.S_IFDIR);\n};\n\nfs.Stats.prototype.isFile = function() {\n return this._checkModeProperty(constants.S_IFREG);\n};\n\nfs.Stats.prototype.isBlockDevice = function() {\n return this._checkModeProperty(constants.S_IFBLK);\n};\n\nfs.Stats.prototype.isCharacterDevice = function() {\n return this._checkModeProperty(constants.S_IFCHR);\n};\n\nfs.Stats.prototype.isSymbolicLink = function() {\n return this._checkModeProperty(constants.S_IFLNK);\n};\n\nfs.Stats.prototype.isFIFO = function() {\n return this._checkModeProperty(constants.S_IFIFO);\n};\n\nfs.Stats.prototype.isSocket = function() {\n return this._checkModeProperty(constants.S_IFSOCK);\n};\n\nfs.exists = function(path, callback) {\n if (!nullCheck(path, cb)) return;\n binding.stat(pathModule._makeLong(path), cb);\n function cb(err, stats) {\n if (callback) callback(err ? false : true);\n }\n};\n\nfs.existsSync = function(path) {\n try {\n nullCheck(path);\n binding.stat(pathModule._makeLong(path));\n return true;\n } catch (e) {\n return false;\n }\n};\n\nfs.readFile = function(path, options, callback_) {\n var callback = maybeCallback(arguments[arguments.length - 1]);\n\n if (typeof options === 'function' || !options) {\n options = { encoding: null, flag: 'r' };\n } else if (typeof options === 'string') {\n options = { encoding: options, flag: 'r' };\n } else if (!options) {\n options = { encoding: null, flag: 'r' };\n } else if (typeof options !== 'object') {\n throw new TypeError('Bad arguments');\n }\n\n var encoding = options.encoding;\n assertEncoding(encoding);\n\n // first, stat the file, so we know the size.\n var size;\n var buffer; // single buffer with file data\n var buffers; // list for when size is unknown\n var pos = 0;\n var fd;\n\n var flag = options.flag || 'r';\n fs.open(path, flag, 438 /*=0666*/, function(er, fd_) {\n if (er) return callback(er);\n fd = fd_;\n\n fs.fstat(fd, function(er, st) {\n if (er) return callback(er);\n size = st.size;\n if (size === 0) {\n // the kernel lies about many files.\n // Go ahead and try to read some bytes.\n buffers = [];\n return read();\n }\n\n buffer = new Buffer(size);\n read();\n });\n });\n\n function read() {\n if (size === 0) {\n buffer = new Buffer(8192);\n fs.read(fd, buffer, 0, 8192, -1, afterRead);\n } else {\n fs.read(fd, buffer, pos, size - pos, -1, afterRead);\n }\n }\n\n function afterRead(er, bytesRead) {\n if (er) {\n return fs.close(fd, function(er2) {\n return callback(er);\n });\n }\n\n if (bytesRead === 0) {\n return close();\n }\n\n pos += bytesRead;\n if (size !== 0) {\n if (pos === size) close();\n else read();\n } else {\n // unknown size, just read until we don't get bytes.\n buffers.push(buffer.slice(0, bytesRead));\n read();\n }\n }\n\n function close() {\n fs.close(fd, function(er) {\n if (size === 0) {\n // collected the data into the buffers list.\n buffer = Buffer.concat(buffers, pos);\n } else if (pos < size) {\n buffer = buffer.slice(0, pos);\n }\n\n if (encoding) buffer = buffer.toString(encoding);\n return callback(er, buffer);\n });\n }\n};\n\nfs.readFileSync = function(path, options) {\n if (!options) {\n options = { encoding: null, flag: 'r' };\n } else if (typeof options === 'string') {\n options = { encoding: options, flag: 'r' };\n } else if (typeof options !== 'object') {\n throw new TypeError('Bad arguments');\n }\n\n var encoding = options.encoding;\n assertEncoding(encoding);\n\n var flag = options.flag || 'r';\n var fd = fs.openSync(path, flag, 438 /*=0666*/);\n\n var size;\n var threw = true;\n try {\n size = fs.fstatSync(fd).size;\n threw = false;\n } finally {\n if (threw) fs.closeSync(fd);\n }\n\n var pos = 0;\n var buffer; // single buffer with file data\n var buffers; // list for when size is unknown\n\n if (size === 0) {\n buffers = [];\n } else {\n buffer = new Buffer(size);\n }\n\n var done = false;\n while (!done) {\n var threw = true;\n try {\n if (size !== 0) {\n var bytesRead = fs.readSync(fd, buffer, pos, size - pos);\n } else {\n // the kernel lies about many files.\n // Go ahead and try to read some bytes.\n buffer = new Buffer(8192);\n var bytesRead = fs.readSync(fd, buffer, 0, 8192);\n if (bytesRead) {\n buffers.push(buffer.slice(0, bytesRead));\n }\n }\n threw = false;\n } finally {\n if (threw) fs.closeSync(fd);\n }\n\n pos += bytesRead;\n done = (bytesRead === 0) || (size !== 0 && pos >= size);\n }\n\n fs.closeSync(fd);\n\n if (size === 0) {\n // data was collected into the buffers list.\n buffer = Buffer.concat(buffers, pos);\n } else if (pos < size) {\n buffer = buffer.slice(0, pos);\n }\n\n if (encoding) buffer = buffer.toString(encoding);\n return buffer;\n};\n\n\n// Used by binding.open and friends\nfunction stringToFlags(flag) {\n // Only mess with strings\n if (typeof flag !== 'string') {\n return flag;\n }\n\n // O_EXCL is mandated by POSIX, Windows supports it too.\n // Let's add a check anyway, just in case.\n if (!O_EXCL && ~flag.indexOf('x')) {\n throw errnoException('ENOSYS', 'fs.open(O_EXCL)');\n }\n\n switch (flag) {\n case 'r' : return O_RDONLY;\n case 'rs' : return O_RDONLY | O_SYNC;\n case 'r+' : return O_RDWR;\n case 'rs+' : return O_RDWR | O_SYNC;\n\n case 'w' : return O_TRUNC | O_CREAT | O_WRONLY;\n case 'wx' : // fall through\n case 'xw' : return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL;\n\n case 'w+' : return O_TRUNC | O_CREAT | O_RDWR;\n case 'wx+': // fall through\n case 'xw+': return O_TRUNC | O_CREAT | O_RDWR | O_EXCL;\n\n case 'a' : return O_APPEND | O_CREAT | O_WRONLY;\n case 'ax' : // fall through\n case 'xa' : return O_APPEND | O_CREAT | O_WRONLY | O_EXCL;\n\n case 'a+' : return O_APPEND | O_CREAT | O_RDWR;\n case 'ax+': // fall through\n case 'xa+': return O_APPEND | O_CREAT | O_RDWR | O_EXCL;\n }\n\n throw new Error('Unknown file open flag: ' + flag);\n}\n\n// exported but hidden, only used by test/simple/test-fs-open-flags.js\nObject.defineProperty(exports, '_stringToFlags', {\n enumerable: false,\n value: stringToFlags\n});\n\n\n// Yes, the follow could be easily DRYed up but I provide the explicit\n// list to make the arguments clear.\n\nfs.close = function(fd, callback) {\n binding.close(fd, makeCallback(callback));\n};\n\nfs.closeSync = function(fd) {\n return binding.close(fd);\n};\n\nfunction modeNum(m, def) {\n switch (typeof m) {\n case 'number': return m;\n case 'string': return parseInt(m, 8);\n default:\n if (def) {\n return modeNum(def);\n } else {\n return undefined;\n }\n }\n}\n\nfs.open = function(path, flags, mode, callback) {\n callback = makeCallback(arguments[arguments.length - 1]);\n mode = modeNum(mode, 438 /*=0666*/);\n\n if (!nullCheck(path, callback)) return;\n binding.open(pathModule._makeLong(path),\n stringToFlags(flags),\n mode,\n callback);\n};\n\nfs.openSync = function(path, flags, mode) {\n mode = modeNum(mode, 438 /*=0666*/);\n nullCheck(path);\n return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);\n};\n\nfs.read = function(fd, buffer, offset, length, position, callback) {\n if (!Buffer.isBuffer(buffer)) {\n // legacy string interface (fd, length, position, encoding, callback)\n var cb = arguments[4],\n encoding = arguments[3];\n\n assertEncoding(encoding);\n\n position = arguments[2];\n length = arguments[1];\n buffer = new Buffer(length);\n offset = 0;\n\n callback = function(err, bytesRead) {\n if (!cb) return;\n\n var str = (bytesRead > 0) ? buffer.toString(encoding, 0, bytesRead) : '';\n\n (cb)(err, str, bytesRead);\n };\n }\n\n function wrapper(err, bytesRead) {\n // Retain a reference to buffer so that it can't be GC'ed too soon.\n callback && callback(err, bytesRead || 0, buffer);\n }\n\n binding.read(fd, buffer, offset, length, position, wrapper);\n};\n\nfs.readSync = function(fd, buffer, offset, length, position) {\n var legacy = false;\n if (!Buffer.isBuffer(buffer)) {\n // legacy string interface (fd, length, position, encoding, callback)\n legacy = true;\n var encoding = arguments[3];\n\n assertEncoding(encoding);\n\n position = arguments[2];\n length = arguments[1];\n buffer = new Buffer(length);\n\n offset = 0;\n }\n\n var r = binding.read(fd, buffer, offset, length, position);\n if (!legacy) {\n return r;\n }\n\n var str = (r > 0) ? buffer.toString(encoding, 0, r) : '';\n return [str, r];\n};\n\nfs.write = function(fd, buffer, offset, length, position, callback) {\n if (!Buffer.isBuffer(buffer)) {\n // legacy string interface (fd, data, position, encoding, callback)\n callback = arguments[4];\n position = arguments[2];\n assertEncoding(arguments[3]);\n\n buffer = new Buffer('' + arguments[1], arguments[3]);\n offset = 0;\n length = buffer.length;\n }\n\n if (!length) {\n if (typeof callback == 'function') {\n process.nextTick(function() {\n callback(undefined, 0);\n });\n }\n return;\n }\n\n callback = maybeCallback(callback);\n\n function wrapper(err, written) {\n // Retain a reference to buffer so that it can't be GC'ed too soon.\n callback(err, written || 0, buffer);\n }\n\n binding.write(fd, buffer, offset, length, position, wrapper);\n};\n\nfs.writeSync = function(fd, buffer, offset, length, position) {\n if (!Buffer.isBuffer(buffer)) {\n // legacy string interface (fd, data, position, encoding)\n position = arguments[2];\n assertEncoding(arguments[3]);\n\n buffer = new Buffer('' + arguments[1], arguments[3]);\n offset = 0;\n length = buffer.length;\n }\n if (!length) return 0;\n\n return binding.write(fd, buffer, offset, length, position);\n};\n\nfs.rename = function(oldPath, newPath, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(oldPath, callback)) return;\n if (!nullCheck(newPath, callback)) return;\n binding.rename(pathModule._makeLong(oldPath),\n pathModule._makeLong(newPath),\n callback);\n};\n\nfs.renameSync = function(oldPath, newPath) {\n nullCheck(oldPath);\n nullCheck(newPath);\n return binding.rename(pathModule._makeLong(oldPath),\n pathModule._makeLong(newPath));\n};\n\nfs.truncate = function(path, len, callback) {\n if (typeof path === 'number') {\n // legacy\n return fs.ftruncate(path, len, callback);\n }\n if (typeof len === 'function') {\n callback = len;\n len = 0;\n } else if (typeof len === 'undefined') {\n len = 0;\n }\n callback = maybeCallback(callback);\n fs.open(path, 'w', function(er, fd) {\n if (er) return callback(er);\n binding.ftruncate(fd, len, function(er) {\n fs.close(fd, function(er2) {\n callback(er || er2);\n });\n });\n });\n};\n\nfs.truncateSync = function(path, len) {\n if (typeof path === 'number') {\n // legacy\n return fs.ftruncateSync(path, len);\n }\n if (typeof len === 'undefined') {\n len = 0;\n }\n // allow error to be thrown, but still close fd.\n var fd = fs.openSync(path, 'w');\n try {\n var ret = fs.ftruncateSync(fd, len);\n } finally {\n fs.closeSync(fd);\n }\n return ret;\n};\n\nfs.ftruncate = function(fd, len, callback) {\n if (typeof len === 'function') {\n callback = len;\n len = 0;\n } else if (typeof len === 'undefined') {\n len = 0;\n }\n binding.ftruncate(fd, len, makeCallback(callback));\n};\n\nfs.ftruncateSync = function(fd, len) {\n if (typeof len === 'undefined') {\n len = 0;\n }\n return binding.ftruncate(fd, len);\n};\n\nfs.rmdir = function(path, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.rmdir(pathModule._makeLong(path), callback);\n};\n\nfs.rmdirSync = function(path) {\n nullCheck(path);\n return binding.rmdir(pathModule._makeLong(path));\n};\n\nfs.fdatasync = function(fd, callback) {\n binding.fdatasync(fd, makeCallback(callback));\n};\n\nfs.fdatasyncSync = function(fd) {\n return binding.fdatasync(fd);\n};\n\nfs.fsync = function(fd, callback) {\n binding.fsync(fd, makeCallback(callback));\n};\n\nfs.fsyncSync = function(fd) {\n return binding.fsync(fd);\n};\n\nfs.mkdir = function(path, mode, callback) {\n if (typeof mode === 'function') callback = mode;\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.mkdir(pathModule._makeLong(path),\n modeNum(mode, 511 /*=0777*/),\n callback);\n};\n\nfs.mkdirSync = function(path, mode) {\n nullCheck(path);\n return binding.mkdir(pathModule._makeLong(path),\n modeNum(mode, 511 /*=0777*/));\n};\n\nfs.readdir = function(path, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.readdir(pathModule._makeLong(path), callback);\n};\n\nfs.readdirSync = function(path) {\n nullCheck(path);\n return binding.readdir(pathModule._makeLong(path));\n};\n\nfs.fstat = function(fd, callback) {\n binding.fstat(fd, makeCallback(callback));\n};\n\nfs.lstat = function(path, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.lstat(pathModule._makeLong(path), callback);\n};\n\nfs.stat = function(path, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.stat(pathModule._makeLong(path), callback);\n};\n\nfs.fstatSync = function(fd) {\n return binding.fstat(fd);\n};\n\nfs.lstatSync = function(path) {\n nullCheck(path);\n return binding.lstat(pathModule._makeLong(path));\n};\n\nfs.statSync = function(path) {\n nullCheck(path);\n return binding.stat(pathModule._makeLong(path));\n};\n\nfs.readlink = function(path, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.readlink(pathModule._makeLong(path), callback);\n};\n\nfs.readlinkSync = function(path) {\n nullCheck(path);\n return binding.readlink(pathModule._makeLong(path));\n};\n\nfunction preprocessSymlinkDestination(path, type) {\n if (!isWindows) {\n // No preprocessing is needed on Unix.\n return path;\n } else if (type === 'junction') {\n // Junctions paths need to be absolute and \\\\?\\-prefixed.\n return pathModule._makeLong(path);\n } else {\n // Windows symlinks don't tolerate forward slashes.\n return ('' + path).replace(/\\//g, '\\\\');\n }\n}\n\nfs.symlink = function(destination, path, type_, callback) {\n var type = (typeof type_ === 'string' ? type_ : null);\n var callback = makeCallback(arguments[arguments.length - 1]);\n\n if (!nullCheck(destination, callback)) return;\n if (!nullCheck(path, callback)) return;\n\n binding.symlink(preprocessSymlinkDestination(destination, type),\n pathModule._makeLong(path),\n type,\n callback);\n};\n\nfs.symlinkSync = function(destination, path, type) {\n type = (typeof type === 'string' ? type : null);\n\n nullCheck(destination);\n nullCheck(path);\n\n return binding.symlink(preprocessSymlinkDestination(destination, type),\n pathModule._makeLong(path),\n type);\n};\n\nfs.link = function(srcpath, dstpath, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(srcpath, callback)) return;\n if (!nullCheck(dstpath, callback)) return;\n\n binding.link(pathModule._makeLong(srcpath),\n pathModule._makeLong(dstpath),\n callback);\n};\n\nfs.linkSync = function(srcpath, dstpath) {\n nullCheck(srcpath);\n nullCheck(dstpath);\n return binding.link(pathModule._makeLong(srcpath),\n pathModule._makeLong(dstpath));\n};\n\nfs.unlink = function(path, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.unlink(pathModule._makeLong(path), callback);\n};\n\nfs.unlinkSync = function(path) {\n nullCheck(path);\n return binding.unlink(pathModule._makeLong(path));\n};\n\nfs.fchmod = function(fd, mode, callback) {\n binding.fchmod(fd, modeNum(mode), makeCallback(callback));\n};\n\nfs.fchmodSync = function(fd, mode) {\n return binding.fchmod(fd, modeNum(mode));\n};\n\nif (constants.hasOwnProperty('O_SYMLINK')) {\n fs.lchmod = function(path, mode, callback) {\n callback = maybeCallback(callback);\n fs.open(path, constants.O_WRONLY | constants.O_SYMLINK, function(err, fd) {\n if (err) {\n callback(err);\n return;\n }\n // prefer to return the chmod error, if one occurs,\n // but still try to close, and report closing errors if they occur.\n fs.fchmod(fd, mode, function(err) {\n fs.close(fd, function(err2) {\n callback(err || err2);\n });\n });\n });\n };\n\n fs.lchmodSync = function(path, mode) {\n var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK);\n\n // prefer to return the chmod error, if one occurs,\n // but still try to close, and report closing errors if they occur.\n var err, err2;\n try {\n var ret = fs.fchmodSync(fd, mode);\n } catch (er) {\n err = er;\n }\n try {\n fs.closeSync(fd);\n } catch (er) {\n err2 = er;\n }\n if (err || err2) throw (err || err2);\n return ret;\n };\n}\n\n\nfs.chmod = function(path, mode, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.chmod(pathModule._makeLong(path),\n modeNum(mode),\n callback);\n};\n\nfs.chmodSync = function(path, mode) {\n nullCheck(path);\n return binding.chmod(pathModule._makeLong(path), modeNum(mode));\n};\n\nif (constants.hasOwnProperty('O_SYMLINK')) {\n fs.lchown = function(path, uid, gid, callback) {\n callback = maybeCallback(callback);\n fs.open(path, constants.O_WRONLY | constants.O_SYMLINK, function(err, fd) {\n if (err) {\n callback(err);\n return;\n }\n fs.fchown(fd, uid, gid, callback);\n });\n };\n\n fs.lchownSync = function(path, uid, gid) {\n var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK);\n return fs.fchownSync(fd, uid, gid);\n };\n}\n\nfs.fchown = function(fd, uid, gid, callback) {\n binding.fchown(fd, uid, gid, makeCallback(callback));\n};\n\nfs.fchownSync = function(fd, uid, gid) {\n return binding.fchown(fd, uid, gid);\n};\n\nfs.chown = function(path, uid, gid, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.chown(pathModule._makeLong(path), uid, gid, callback);\n};\n\nfs.chownSync = function(path, uid, gid) {\n nullCheck(path);\n return binding.chown(pathModule._makeLong(path), uid, gid);\n};\n\n// converts Date or number to a fractional UNIX timestamp\nfunction toUnixTimestamp(time) {\n if (typeof time == 'number') {\n return time;\n }\n if (time instanceof Date) {\n // convert to 123.456 UNIX timestamp\n return time.getTime() / 1000;\n }\n throw new Error('Cannot parse time: ' + time);\n}\n\n// exported for unit tests, not for public consumption\nfs._toUnixTimestamp = toUnixTimestamp;\n\nfs.utimes = function(path, atime, mtime, callback) {\n callback = makeCallback(callback);\n if (!nullCheck(path, callback)) return;\n binding.utimes(pathModule._makeLong(path),\n toUnixTimestamp(atime),\n toUnixTimestamp(mtime),\n callback);\n};\n\nfs.utimesSync = function(path, atime, mtime) {\n nullCheck(path);\n atime = toUnixTimestamp(atime);\n mtime = toUnixTimestamp(mtime);\n binding.utimes(pathModule._makeLong(path), atime, mtime);\n};\n\nfs.futimes = function(fd, atime, mtime, callback) {\n atime = toUnixTimestamp(atime);\n mtime = toUnixTimestamp(mtime);\n binding.futimes(fd, atime, mtime, makeCallback(callback));\n};\n\nfs.futimesSync = function(fd, atime, mtime) {\n atime = toUnixTimestamp(atime);\n mtime = toUnixTimestamp(mtime);\n binding.futimes(fd, atime, mtime);\n};\n\nfunction writeAll(fd, buffer, offset, length, position, callback) {\n callback = maybeCallback(arguments[arguments.length - 1]);\n\n // write(fd, buffer, offset, length, position, callback)\n fs.write(fd, buffer, offset, length, position, function(writeErr, written) {\n if (writeErr) {\n fs.close(fd, function() {\n if (callback) callback(writeErr);\n });\n } else {\n if (written === length) {\n fs.close(fd, callback);\n } else {\n offset += written;\n length -= written;\n position += written;\n writeAll(fd, buffer, offset, length, position, callback);\n }\n }\n });\n}\n\nfs.writeFile = function(path, data, options, callback) {\n var callback = maybeCallback(arguments[arguments.length - 1]);\n\n if (typeof options === 'function' || !options) {\n options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' };\n } else if (typeof options === 'string') {\n options = { encoding: options, mode: 438, flag: 'w' };\n } else if (!options) {\n options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' };\n } else if (typeof options !== 'object') {\n throw new TypeError('Bad arguments');\n }\n\n assertEncoding(options.encoding);\n\n var flag = options.flag || 'w';\n fs.open(path, options.flag || 'w', options.mode, function(openErr, fd) {\n if (openErr) {\n if (callback) callback(openErr);\n } else {\n var buffer = Buffer.isBuffer(data) ? data : new Buffer('' + data,\n options.encoding || 'utf8');\n var position = /a/.test(flag) ? null : 0;\n writeAll(fd, buffer, 0, buffer.length, position, callback);\n }\n });\n};\n\nfs.writeFileSync = function(path, data, options) {\n if (!options) {\n options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' };\n } else if (typeof options === 'string') {\n options = { encoding: options, mode: 438, flag: 'w' };\n } else if (typeof options !== 'object') {\n throw new TypeError('Bad arguments');\n }\n\n assertEncoding(options.encoding);\n\n var flag = options.flag || 'w';\n var fd = fs.openSync(path, flag, options.mode);\n if (!Buffer.isBuffer(data)) {\n data = new Buffer('' + data, options.encoding || 'utf8');\n }\n var written = 0;\n var length = data.length;\n var position = /a/.test(flag) ? null : 0;\n try {\n while (written < length) {\n written += fs.writeSync(fd, data, written, length - written, position);\n position += written;\n }\n } finally {\n fs.closeSync(fd);\n }\n};\n\nfs.appendFile = function(path, data, options, callback_) {\n var callback = maybeCallback(arguments[arguments.length - 1]);\n\n if (typeof options === 'function' || !options) {\n options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' };\n } else if (typeof options === 'string') {\n options = { encoding: options, mode: 438, flag: 'a' };\n } else if (!options) {\n options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' };\n } else if (typeof options !== 'object') {\n throw new TypeError('Bad arguments');\n }\n\n if (!options.flag)\n options = util._extend({ flag: 'a' }, options);\n fs.writeFile(path, data, options, callback);\n};\n\nfs.appendFileSync = function(path, data, options) {\n if (!options) {\n options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' };\n } else if (typeof options === 'string') {\n options = { encoding: options, mode: 438, flag: 'a' };\n } else if (typeof options !== 'object') {\n throw new TypeError('Bad arguments');\n }\n if (!options.flag)\n options = util._extend({ flag: 'a' }, options);\n\n fs.writeFileSync(path, data, options);\n};\n\nfunction errnoException(errorno, syscall) {\n // TODO make this more compatible with ErrnoException from src/node.cc\n // Once all of Node is using this function the ErrnoException from\n // src/node.cc should be removed.\n var e = new Error(syscall + ' ' + errorno);\n e.errno = e.code = errorno;\n e.syscall = syscall;\n return e;\n}\n\n\nfunction FSWatcher() {\n EventEmitter.call(this);\n\n var self = this;\n var FSEvent = process.binding('fs_event_wrap').FSEvent;\n this._handle = new FSEvent();\n this._handle.owner = this;\n\n this._handle.onchange = function(status, event, filename) {\n if (status) {\n self._handle.close();\n self.emit('error', errnoException(process._errno, 'watch'));\n } else {\n self.emit('change', event, filename);\n }\n };\n}\nutil.inherits(FSWatcher, EventEmitter);\n\nFSWatcher.prototype.start = function(filename, persistent) {\n nullCheck(filename);\n var r = this._handle.start(pathModule._makeLong(filename), persistent);\n\n if (r) {\n this._handle.close();\n throw errnoException(process._errno, 'watch');\n }\n};\n\nFSWatcher.prototype.close = function() {\n this._handle.close();\n};\n\nfs.watch = function(filename) {\n nullCheck(filename);\n var watcher;\n var options;\n var listener;\n\n if ('object' == typeof arguments[1]) {\n options = arguments[1];\n listener = arguments[2];\n } else {\n options = {};\n listener = arguments[1];\n }\n\n if (options.persistent === undefined) options.persistent = true;\n\n watcher = new FSWatcher();\n watcher.start(filename, options.persistent);\n\n if (listener) {\n watcher.addListener('change', listener);\n }\n\n return watcher;\n};\n\n\n// Stat Change Watchers\n\nfunction StatWatcher() {\n EventEmitter.call(this);\n\n var self = this;\n this._handle = new binding.StatWatcher();\n\n // uv_fs_poll is a little more powerful than ev_stat but we curb it for\n // the sake of backwards compatibility\n var oldStatus = -1;\n\n this._handle.onchange = function(current, previous, newStatus) {\n if (oldStatus === -1 &&\n newStatus === -1 &&\n current.nlink === previous.nlink) return;\n\n oldStatus = newStatus;\n self.emit('change', current, previous);\n };\n\n this._handle.onstop = function() {\n self.emit('stop');\n };\n}\nutil.inherits(StatWatcher, EventEmitter);\n\n\nStatWatcher.prototype.start = function(filename, persistent, interval) {\n nullCheck(filename);\n this._handle.start(pathModule._makeLong(filename), persistent, interval);\n};\n\n\nStatWatcher.prototype.stop = function() {\n this._handle.stop();\n};\n\n\nvar statWatchers = {};\nfunction inStatWatchers(filename) {\n return Object.prototype.hasOwnProperty.call(statWatchers, filename) &&\n statWatchers[filename];\n}\n\n\nfs.watchFile = function(filename) {\n nullCheck(filename);\n var stat;\n var listener;\n\n var options = {\n // Poll interval in milliseconds. 5007 is what libev used to use. It's\n // a little on the slow side but let's stick with it for now to keep\n // behavioral changes to a minimum.\n interval: 5007,\n persistent: true\n };\n\n if ('object' == typeof arguments[1]) {\n options = util._extend(options, arguments[1]);\n listener = arguments[2];\n } else {\n listener = arguments[1];\n }\n\n if (!listener) {\n throw new Error('watchFile requires a listener function');\n }\n\n if (inStatWatchers(filename)) {\n stat = statWatchers[filename];\n } else {\n stat = statWatchers[filename] = new StatWatcher();\n stat.start(filename, options.persistent, options.interval);\n }\n stat.addListener('change', listener);\n return stat;\n};\n\nfs.unwatchFile = function(filename, listener) {\n nullCheck(filename);\n if (!inStatWatchers(filename)) return;\n\n var stat = statWatchers[filename];\n\n if (typeof listener === 'function') {\n stat.removeListener('change', listener);\n } else {\n stat.removeAllListeners('change');\n }\n\n if (EventEmitter.listenerCount(stat, 'change') === 0) {\n stat.stop();\n statWatchers[filename] = undefined;\n }\n};\n\n// Realpath\n// Not using realpath(2) because it's bad.\n// See: http://insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html\n\nvar normalize = pathModule.normalize;\n\n// Regexp that finds the next partion of a (partial) path\n// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']\nif (isWindows) {\n var nextPartRe = /(.*?)(?:[\\/\\\\]+|$)/g;\n} else {\n var nextPartRe = /(.*?)(?:[\\/]+|$)/g;\n}\n\n// Regex to find the device root, including trailing slash. E.g. 'c:\\\\'.\nif (isWindows) {\n var splitRootRe = /^(?:[a-zA-Z]:|[\\\\\\/]{2}[^\\\\\\/]+[\\\\\\/][^\\\\\\/]+)?[\\\\\\/]*/;\n} else {\n var splitRootRe = /^[\\/]*/;\n}\n\nfs.realpathSync = function realpathSync(p, cache) {\n // make p is absolute\n p = pathModule.resolve(p);\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {\n return cache[p];\n }\n\n var original = p,\n seenLinks = {},\n knownHard = {};\n\n // current character position in p\n var pos;\n // the partial path so far, including a trailing slash if any\n var current;\n // the partial path without a trailing slash (except when pointing at a root)\n var base;\n // the partial path scanned in the previous round, with slash\n var previous;\n\n start();\n\n function start() {\n // Skip over roots\n var m = splitRootRe.exec(p);\n pos = m[0].length;\n current = m[0];\n base = m[0];\n previous = '';\n\n // On windows, check that the root exists. On unix there is no need.\n if (isWindows && !knownHard[base]) {\n fs.lstatSync(base);\n knownHard[base] = true;\n }\n }\n\n // walk down the path, swapping out linked pathparts for their real\n // values\n // NB: p.length changes.\n while (pos < p.length) {\n // find the next part\n nextPartRe.lastIndex = pos;\n var result = nextPartRe.exec(p);\n previous = current;\n current += result[0];\n base = previous + result[1];\n pos = nextPartRe.lastIndex;\n\n // continue if not a symlink\n if (knownHard[base] || (cache && cache[base] === base)) {\n continue;\n }\n\n var resolvedLink;\n if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {\n // some known symbolic link. no need to stat again.\n resolvedLink = cache[base];\n } else {\n var stat = fs.lstatSync(base);\n if (!stat.isSymbolicLink()) {\n knownHard[base] = true;\n if (cache) cache[base] = base;\n continue;\n }\n\n // read the link if it wasn't read before\n // dev/ino always return 0 on windows, so skip the check.\n var linkTarget = null;\n if (!isWindows) {\n var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);\n if (seenLinks.hasOwnProperty(id)) {\n linkTarget = seenLinks[id];\n }\n }\n if (linkTarget === null) {\n fs.statSync(base);\n linkTarget = fs.readlinkSync(base);\n }\n resolvedLink = pathModule.resolve(previous, linkTarget);\n // track this, if given a cache.\n if (cache) cache[base] = resolvedLink;\n if (!isWindows) seenLinks[id] = linkTarget;\n }\n\n // resolve the link, then start over\n p = pathModule.resolve(resolvedLink, p.slice(pos));\n start();\n }\n\n if (cache) cache[original] = p;\n\n return p;\n};\n\n\nfs.realpath = function realpath(p, cache, cb) {\n if (typeof cb !== 'function') {\n cb = maybeCallback(cache);\n cache = null;\n }\n\n // make p is absolute\n p = pathModule.resolve(p);\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {\n return process.nextTick(cb.bind(null, null, cache[p]));\n }\n\n var original = p,\n seenLinks = {},\n knownHard = {};\n\n // current character position in p\n var pos;\n // the partial path so far, including a trailing slash if any\n var current;\n // the partial path without a trailing slash (except when pointing at a root)\n var base;\n // the partial path scanned in the previous round, with slash\n var previous;\n\n start();\n\n function start() {\n // Skip over roots\n var m = splitRootRe.exec(p);\n pos = m[0].length;\n current = m[0];\n base = m[0];\n previous = '';\n\n // On windows, check that the root exists. On unix there is no need.\n if (isWindows && !knownHard[base]) {\n fs.lstat(base, function(err) {\n if (err) return cb(err);\n knownHard[base] = true;\n LOOP();\n });\n } else {\n process.nextTick(LOOP);\n }\n }\n\n // walk down the path, swapping out linked pathparts for their real\n // values\n function LOOP() {\n // stop if scanned past end of path\n if (pos >= p.length) {\n if (cache) cache[original] = p;\n return cb(null, p);\n }\n\n // find the next part\n nextPartRe.lastIndex = pos;\n var result = nextPartRe.exec(p);\n previous = current;\n current += result[0];\n base = previous + result[1];\n pos = nextPartRe.lastIndex;\n\n // continue if not a symlink\n if (knownHard[base] || (cache && cache[base] === base)) {\n return process.nextTick(LOOP);\n }\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {\n // known symbolic link. no need to stat again.\n return gotResolvedLink(cache[base]);\n }\n\n return fs.lstat(base, gotStat);\n }\n\n function gotStat(err, stat) {\n if (err) return cb(err);\n\n // if not a symlink, skip to the next path part\n if (!stat.isSymbolicLink()) {\n knownHard[base] = true;\n if (cache) cache[base] = base;\n return process.nextTick(LOOP);\n }\n\n // stat & read the link if not read before\n // call gotTarget as soon as the link target is known\n // dev/ino always return 0 on windows, so skip the check.\n if (!isWindows) {\n var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);\n if (seenLinks.hasOwnProperty(id)) {\n return gotTarget(null, seenLinks[id], base);\n }\n }\n fs.stat(base, function(err) {\n if (err) return cb(err);\n\n fs.readlink(base, function(err, target) {\n if (!isWindows) seenLinks[id] = target;\n gotTarget(err, target);\n });\n });\n }\n\n function gotTarget(err, target, base) {\n if (err) return cb(err);\n\n var resolvedLink = pathModule.resolve(previous, target);\n if (cache) cache[base] = resolvedLink;\n gotResolvedLink(resolvedLink);\n }\n\n function gotResolvedLink(resolvedLink) {\n // resolve the link, then start over\n p = pathModule.resolve(resolvedLink, p.slice(pos));\n start();\n }\n};\n\n\n\nvar pool;\n\nfunction allocNewPool(poolSize) {\n pool = new Buffer(poolSize);\n pool.used = 0;\n}\n\n\n\nfs.createReadStream = function(path, options) {\n return new ReadStream(path, options);\n};\n\nutil.inherits(ReadStream, Readable);\nfs.ReadStream = ReadStream;\n\nfunction ReadStream(path, options) {\n if (!(this instanceof ReadStream))\n return new ReadStream(path, options);\n\n // a little bit bigger buffer and water marks by default\n options = util._extend({\n highWaterMark: 64 * 1024\n }, options || {});\n\n Readable.call(this, options);\n\n this.path = path;\n this.fd = options.hasOwnProperty('fd') ? options.fd : null;\n this.flags = options.hasOwnProperty('flags') ? options.flags : 'r';\n this.mode = options.hasOwnProperty('mode') ? options.mode : 438; /*=0666*/\n\n this.start = options.hasOwnProperty('start') ? options.start : undefined;\n this.end = options.hasOwnProperty('end') ? options.end : undefined;\n this.autoClose = options.hasOwnProperty('autoClose') ?\n options.autoClose : true;\n this.pos = undefined;\n\n if (this.start !== undefined) {\n if ('number' !== typeof this.start) {\n throw TypeError('start must be a Number');\n }\n if (this.end === undefined) {\n this.end = Infinity;\n } else if ('number' !== typeof this.end) {\n throw TypeError('end must be a Number');\n }\n\n if (this.start > this.end) {\n throw new Error('start must be <= end');\n }\n\n this.pos = this.start;\n }\n\n if (typeof this.fd !== 'number')\n this.open();\n\n this.on('end', function() {\n if (this.autoClose) {\n this.destroy();\n }\n });\n}\n\nfs.FileReadStream = fs.ReadStream; // support the legacy name\n\nReadStream.prototype.open = function() {\n var self = this;\n fs.open(this.path, this.flags, this.mode, function(er, fd) {\n if (er) {\n if (this.autoClose) {\n self.destroy();\n }\n self.emit('error', er);\n return;\n }\n\n self.fd = fd;\n self.emit('open', fd);\n // start the flow of data.\n self.read();\n });\n};\n\nReadStream.prototype._read = function(n) {\n if (typeof this.fd !== 'number')\n return this.once('open', function() {\n this._read(n);\n });\n\n if (this.destroyed)\n return;\n\n if (!pool || pool.length - pool.used < kMinPoolSpace) {\n // discard the old pool.\n pool = null;\n allocNewPool(this._readableState.highWaterMark);\n }\n\n // Grab another reference to the pool in the case that while we're\n // in the thread pool another read() finishes up the pool, and\n // allocates a new one.\n var thisPool = pool;\n var toRead = Math.min(pool.length - pool.used, n);\n var start = pool.used;\n\n if (this.pos !== undefined)\n toRead = Math.min(this.end - this.pos + 1, toRead);\n\n // already read everything we were supposed to read!\n // treat as EOF.\n if (toRead <= 0)\n return this.push(null);\n\n // the actual read.\n var self = this;\n fs.read(this.fd, pool, pool.used, toRead, this.pos, onread);\n\n // move the pool positions, and internal position for reading.\n if (this.pos !== undefined)\n this.pos += toRead;\n pool.used += toRead;\n\n function onread(er, bytesRead) {\n if (er) {\n if (self.autoClose) {\n self.destroy();\n }\n self.emit('error', er);\n } else {\n var b = null;\n if (bytesRead > 0)\n b = thisPool.slice(start, start + bytesRead);\n\n self.push(b);\n }\n }\n};\n\n\nReadStream.prototype.destroy = function() {\n if (this.destroyed)\n return;\n this.destroyed = true;\n\n if ('number' === typeof this.fd)\n this.close();\n};\n\n\nReadStream.prototype.close = function(cb) {\n var self = this;\n if (cb)\n this.once('close', cb);\n if (this.closed || 'number' !== typeof this.fd) {\n if ('number' !== typeof this.fd) {\n this.once('open', close);\n return;\n }\n return process.nextTick(this.emit.bind(this, 'close'));\n }\n this.closed = true;\n close();\n\n function close(fd) {\n fs.close(fd || self.fd, function(er) {\n if (er)\n self.emit('error', er);\n else\n self.emit('close');\n });\n self.fd = null;\n }\n};\n\n\n\n\nfs.createWriteStream = function(path, options) {\n return new WriteStream(path, options);\n};\n\nutil.inherits(WriteStream, Writable);\nfs.WriteStream = WriteStream;\nfunction WriteStream(path, options) {\n if (!(this instanceof WriteStream))\n return new WriteStream(path, options);\n\n options = options || {};\n\n Writable.call(this, options);\n\n this.path = path;\n this.fd = null;\n\n this.fd = options.hasOwnProperty('fd') ? options.fd : null;\n this.flags = options.hasOwnProperty('flags') ? options.flags : 'w';\n this.mode = options.hasOwnProperty('mode') ? options.mode : 438; /*=0666*/\n\n this.start = options.hasOwnProperty('start') ? options.start : undefined;\n this.pos = undefined;\n this.bytesWritten = 0;\n\n if (this.start !== undefined) {\n if ('number' !== typeof this.start) {\n throw TypeError('start must be a Number');\n }\n if (this.start < 0) {\n throw new Error('start must be >= zero');\n }\n\n this.pos = this.start;\n }\n\n if ('number' !== typeof this.fd)\n this.open();\n\n // dispose on finish.\n this.once('finish', this.close);\n}\n\nfs.FileWriteStream = fs.WriteStream; // support the legacy name\n\n\nWriteStream.prototype.open = function() {\n fs.open(this.path, this.flags, this.mode, function(er, fd) {\n if (er) {\n this.destroy();\n this.emit('error', er);\n return;\n }\n\n this.fd = fd;\n this.emit('open', fd);\n }.bind(this));\n};\n\n\nWriteStream.prototype._write = function(data, encoding, cb) {\n if (!Buffer.isBuffer(data))\n return this.emit('error', new Error('Invalid data'));\n\n if (typeof this.fd !== 'number')\n return this.once('open', function() {\n this._write(data, encoding, cb);\n });\n\n var self = this;\n fs.write(this.fd, data, 0, data.length, this.pos, function(er, bytes) {\n if (er) {\n self.destroy();\n return cb(er);\n }\n self.bytesWritten += bytes;\n cb();\n });\n\n if (this.pos !== undefined)\n this.pos += data.length;\n};\n\n\nWriteStream.prototype.destroy = ReadStream.prototype.destroy;\nWriteStream.prototype.close = ReadStream.prototype.close;\n\n// There is no shutdown() for files.\nWriteStream.prototype.destroySoon = WriteStream.prototype.end;\n\n\n// SyncWriteStream is internal. DO NOT USE.\n// Temporary hack for process.stdout and process.stderr when piped to files.\nfunction SyncWriteStream(fd) {\n Stream.call(this);\n\n this.fd = fd;\n this.writable = true;\n this.readable = false;\n}\n\nutil.inherits(SyncWriteStream, Stream);\n\n\n// Export\nfs.SyncWriteStream = SyncWriteStream;\n\n\nSyncWriteStream.prototype.write = function(data, arg1, arg2) {\n var encoding, cb;\n\n // parse arguments\n if (arg1) {\n if (typeof arg1 === 'string') {\n encoding = arg1;\n cb = arg2;\n } else if (typeof arg1 === 'function') {\n cb = arg1;\n } else {\n throw new Error('bad arg');\n }\n }\n assertEncoding(encoding);\n\n // Change strings to buffers. SLOW\n if (typeof data == 'string') {\n data = new Buffer(data, encoding);\n }\n\n fs.writeSync(this.fd, data, 0, data.length);\n\n if (cb) {\n process.nextTick(cb);\n }\n\n return true;\n};\n\n\nSyncWriteStream.prototype.end = function(data, arg1, arg2) {\n if (data) {\n this.write(data, arg1, arg2);\n }\n this.destroy();\n};\n\n\nSyncWriteStream.prototype.destroy = function() {\n fs.closeSync(this.fd);\n this.fd = null;\n this.emit('close');\n return true;\n};\n\nSyncWriteStream.prototype.destroySoon = SyncWriteStream.prototype.destroy;\n\n});","sourceLength":45344,"scriptType":2,"compilationType":0,"context":{"ref":65},"text":"fs.js (lines: 1761)"},{"handle":68,"type":"script","name":"events.js","id":18,"lineOffset":0,"columnOffset":0,"lineCount":292,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar domain;\n\nexports.usingDomains = false;\n\nfunction EventEmitter() {\n this.domain = null;\n if (exports.usingDomains) {\n // if there is an active domain, then attach to it.\n domain = domain || require('domain');\n if (domain.active && !(this instanceof domain.Domain)) {\n this.domain = domain.active;\n }\n }\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || defaultMaxListeners;\n}\nexports.EventEmitter = EventEmitter;\n\n// By default EventEmitters will print a warning if more than\n// 10 listeners are added to it. This is a useful default which\n// helps finding memory leaks.\n//\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nvar defaultMaxListeners = 10;\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (typeof n !== 'number' || n < 0)\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (typeof this._events.error === 'object' &&\n !this._events.error.length)) {\n er = arguments[1];\n if (this.domain) {\n if (!er) er = new TypeError('Uncaught, unspecified \"error\" event.');\n er.domainEmitter = this;\n er.domain = this.domain;\n er.domainThrown = false;\n this.domain.emit('error', er);\n } else if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n throw TypeError('Uncaught, unspecified \"error\" event.');\n }\n return false;\n }\n }\n\n handler = this._events[type];\n\n if (typeof handler === 'undefined')\n return false;\n\n if (this.domain && this !== process)\n this.domain.enter();\n\n if (typeof handler === 'function') {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n len = arguments.length;\n args = new Array(len - 1);\n for (i = 1; i < len; i++)\n args[i - 1] = arguments[i];\n handler.apply(this, args);\n }\n } else if (typeof handler === 'object') {\n len = arguments.length;\n args = new Array(len - 1);\n for (i = 1; i < len; i++)\n args[i - 1] = arguments[i];\n\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n if (this.domain && this !== process)\n this.domain.exit();\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (typeof listener !== 'function')\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type, typeof listener.listener === 'function' ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (typeof this._events[type] === 'object')\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (typeof this._events[type] === 'object' && !this._events[type].warned) {\n m = this._maxListeners;\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n console.trace();\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (typeof listener !== 'function')\n throw TypeError('listener must be a function');\n\n function g() {\n this.removeListener(type, g);\n listener.apply(this, arguments);\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (typeof listener !== 'function')\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (typeof list.listener === 'function' && list.listener === listener)) {\n this._events[type] = undefined;\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (typeof list === 'object') {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n this._events[type] = undefined;\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n this._events[type] = undefined;\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n this._events[type] = undefined;\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (typeof this._events[type] === 'function')\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n var ret;\n if (!emitter._events || !emitter._events[type])\n ret = 0;\n else if (typeof emitter._events[type] === 'function')\n ret = 1;\n else\n ret = emitter._events[type].length;\n return ret;\n};\n\n});","sourceLength":8466,"scriptType":2,"compilationType":0,"context":{"ref":67},"text":"events.js (lines: 292)"}],"refs":[{"handle":41,"type":"context","text":"#<ContextMirror>"},{"handle":43,"type":"context","text":"#<ContextMirror>"},{"handle":45,"type":"context","text":"#<ContextMirror>"},{"handle":47,"type":"context","text":"#<ContextMirror>"},{"handle":49,"type":"context","text":"#<ContextMirror>"},{"handle":51,"type":"context","text":"#<ContextMirror>"},{"handle":53,"type":"context","text":"#<ContextMirror>"},{"handle":33,"type":"context","text":"#<ContextMirror>"},{"handle":55,"type":"context","text":"#<ContextMirror>"},{"handle":57,"type":"context","text":"#<ContextMirror>"},{"handle":59,"type":"context","text":"#<ContextMirror>"},{"handle":5,"type":"context","text":"#<ContextMirror>"},{"handle":61,"type":"context","text":"#<ContextMirror>"},{"handle":2,"type":"context","text":"#<ContextMirror>"},{"handle":63,"type":"context","text":"#<ContextMirror>"},{"handle":65,"type":"context","text":"#<ContextMirror>"},{"handle":67,"type":"context","text":"#<ContextMirror>"}],"running":false} | |
{"seq":901,"type":"request","command":"setbreakpoint","arguments":{"enabled":true,"condition":"try {\n (function () {\n const oldStackTraceLimit = Error.stackTraceLimit;\n const oldPrepareStackTrace = Error.prepareStackTrace;\n var stack = null;\n try {\n const dummyObject = {};\n Error.stackTraceLimit = 10;\n Error.prepareStackTrace = function (dummyObject, stackTrace) {\n return stackTrace;\n };\n Error.captureStackTrace(dummyObject);\n stack = dummyObject.stack;\n }\n finally {\n Error.stackTraceLimit = oldStackTraceLimit;\n Error.prepareStackTrace = oldPrepareStackTrace;\n }\n\n var filename;\n for (var i = 0, n = stack.length; i < n; i++) {\n var frame = stack[i];\n if (!frame.isNative() && (filename = frame.getFileName())) {\n break;\n }\n }\n\n if (filename.indexOf('\/') === -1 && filename.indexOf('\\\\') === -1) {\n \/\/console.log(\"Skip core module \" + filename);\n return false;\n }\n\n if (!filename) {\n console.error(\"Cannot determinate script filename\");\n return false;\n }\n const fs = process.mainModule.require('fs');\n var fd = fs.openSync(filename, 'r');\n try {\n const size = fs.fstatSync(fd).size;\n if (size < 25) {\n return false;\n }\n\n const start = size < 4096 ? 0 : (size - 4096);\n const end = size - 1;\n coff | |
nst buffer = new Buffer(end - start);\n var count = 0;\n while (count < buffer.length) {\n const bytesRead = fs.readSync(fd, buffer, count, buffer.length - count, start + count);\n if (bytesRead <= 0) {\n break;\n }\n count += bytesRead;\n }\n return buffer.toString().lastIndexOf('sourceMappingURL=') != -1;\n }\n finally {\n fs.close(fd, function () {\n });\n }\n })()\n}\ncatch (e) {\n console.error(e);\n}","target":"\\.js$","line":0,"type":"scriptRegExp"}} | |
{"seq":6,"request_seq":901,"type":"response","command":"setbreakpoint","success":true,"body":{"type":"scriptRegExp","breakpoint":5,"script_regexp":"\\.js$","line":0,"column":null,"actual_locations":[{"line":0,"column":0,"script_id":4},{"line":0,"column":0,"script_id":17},{"line":0,"column":0,"script_id":8},{"line":0,"column":0,"script_id":7},{"line":0,"column":0,"script_id":11},{"line":0,"column":0,"script_id":12},{"line":0,"column":0,"script_id":22},{"line":0,"column":0,"script_id":20},{"line":0,"column":0,"script_id":16},{"line":0,"column":0,"script_id":19},{"line":0,"column":0,"script_id":14},{"line":0,"column":0,"script_id":31},{"line":0,"column":0,"script_id":21},{"line":0,"column":0,"script_id":25},{"line":0,"column":0,"script_id":3},{"line":0,"column":0,"script_id":24},{"line":0,"column":0,"script_id":27},{"line":0,"column":0,"script_id":10},{"line":0,"column":0,"script_id":13},{"line":0,"column":0,"script_id":32},{"line":0,"column":0,"script_id":30},{"line":0,"column":0,"script_id":23},{"line":0,"column":0,"script_id":28},{"line":0,"column":0,"script_id":33},{"line":0,"column":0,"script_id":29},{"line":0,"column":0,"script_id":5},{"line":0,"column":0,"script_id":15},{"line":0,"column":0,"script_id":26},{"line":0,"column":0,"script_id":6},{"line":0,"column":0,"script_id":18},{"line":0,"column":0,"script_id":9}]},"refs":[],"running":false} | |
{"seq":902,"type":"request","command":"continue"} | |
{"seq":7,"request_seq":902,"type":"response","command":"continue","success":true,"running":true} | |
Process finished with exit code 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment