--- /dev/null
+/*\r
+ * Copyright 2016 ZTE Corporation.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+var require = function (file, cwd) {\r
+ var resolved = require.resolve(file, cwd || '/');\r
+ var mod = require.modules[resolved];\r
+ if (!mod) throw new Error(\r
+ 'Failed to resolve module ' + file + ', tried ' + resolved\r
+ );\r
+ var res = mod._cached ? mod._cached : mod();\r
+ return res;\r
+}\r
+\r
+require.paths = [];\r
+require.modules = {};\r
+require.extensions = [".js",".coffee"];\r
+\r
+require._core = {\r
+ 'assert': true,\r
+ 'events': true,\r
+ 'fs': true,\r
+ 'path': true,\r
+ 'vm': true\r
+};\r
+\r
+require.resolve = (function () {\r
+ return function (x, cwd) {\r
+ if (!cwd) cwd = '/';\r
+ \r
+ if (require._core[x]) return x;\r
+ var path = require.modules.path();\r
+ var y = cwd || '.';\r
+ \r
+ if (x.match(/^(?:\.\.?\/|\/)/)) {\r
+ var m = loadAsFileSync(path.resolve(y, x))\r
+ || loadAsDirectorySync(path.resolve(y, x));\r
+ if (m) return m;\r
+ }\r
+ \r
+ var n = loadNodeModulesSync(x, y);\r
+ if (n) return n;\r
+ \r
+ throw new Error("Cannot find module '" + x + "'");\r
+ \r
+ function loadAsFileSync (x) {\r
+ if (require.modules[x]) {\r
+ return x;\r
+ }\r
+ \r
+ for (var i = 0; i < require.extensions.length; i++) {\r
+ var ext = require.extensions[i];\r
+ if (require.modules[x + ext]) return x + ext;\r
+ }\r
+ }\r
+ \r
+ function loadAsDirectorySync (x) {\r
+ x = x.replace(/\/+$/, '');\r
+ var pkgfile = x + '/package.json';\r
+ if (require.modules[pkgfile]) {\r
+ var pkg = require.modules[pkgfile]();\r
+ var b = pkg.browserify;\r
+ if (typeof b === 'object' && b.main) {\r
+ var m = loadAsFileSync(path.resolve(x, b.main));\r
+ if (m) return m;\r
+ }\r
+ else if (typeof b === 'string') {\r
+ var m = loadAsFileSync(path.resolve(x, b));\r
+ if (m) return m;\r
+ }\r
+ else if (pkg.main) {\r
+ var m = loadAsFileSync(path.resolve(x, pkg.main));\r
+ if (m) return m;\r
+ }\r
+ }\r
+ \r
+ return loadAsFileSync(x + '/index');\r
+ }\r
+ \r
+ function loadNodeModulesSync (x, start) {\r
+ var dirs = nodeModulesPathsSync(start);\r
+ for (var i = 0; i < dirs.length; i++) {\r
+ var dir = dirs[i];\r
+ var m = loadAsFileSync(dir + '/' + x);\r
+ if (m) return m;\r
+ var n = loadAsDirectorySync(dir + '/' + x);\r
+ if (n) return n;\r
+ }\r
+ \r
+ var m = loadAsFileSync(x);\r
+ if (m) return m;\r
+ }\r
+ \r
+ function nodeModulesPathsSync (start) {\r
+ var parts;\r
+ if (start === '/') parts = [ '' ];\r
+ else parts = path.normalize(start).split('/');\r
+ \r
+ var dirs = [];\r
+ for (var i = parts.length - 1; i >= 0; i--) {\r
+ if (parts[i] === 'node_modules') continue;\r
+ var dir = parts.slice(0, i + 1).join('/') + '/node_modules';\r
+ dirs.push(dir);\r
+ }\r
+ \r
+ return dirs;\r
+ }\r
+ };\r
+})();\r
+\r
+require.alias = function (from, to) {\r
+ var path = require.modules.path();\r
+ var res = null;\r
+ try {\r
+ res = require.resolve(from + '/package.json', '/');\r
+ }\r
+ catch (err) {\r
+ res = require.resolve(from, '/');\r
+ }\r
+ var basedir = path.dirname(res);\r
+ \r
+ var keys = (Object.keys || function (obj) {\r
+ var res = [];\r
+ for (var key in obj) res.push(key)\r
+ return res;\r
+ })(require.modules);\r
+ \r
+ for (var i = 0; i < keys.length; i++) {\r
+ var key = keys[i];\r
+ if (key.slice(0, basedir.length + 1) === basedir + '/') {\r
+ var f = key.slice(basedir.length);\r
+ require.modules[to + f] = require.modules[basedir + f];\r
+ }\r
+ else if (key === basedir) {\r
+ require.modules[to] = require.modules[basedir];\r
+ }\r
+ }\r
+};\r
+\r
+require.define = function (filename, fn) {\r
+ var dirname = require._core[filename]\r
+ ? ''\r
+ : require.modules.path().dirname(filename)\r
+ ;\r
+ \r
+ var require_ = function (file) {\r
+ return require(file, dirname)\r
+ };\r
+ require_.resolve = function (name) {\r
+ return require.resolve(name, dirname);\r
+ };\r
+ require_.modules = require.modules;\r
+ require_.define = require.define;\r
+ var module_ = { exports : {} };\r
+ \r
+ require.modules[filename] = function () {\r
+ require.modules[filename]._cached = module_.exports;\r
+ fn.call(\r
+ module_.exports,\r
+ require_,\r
+ module_,\r
+ module_.exports,\r
+ dirname,\r
+ filename\r
+ );\r
+ require.modules[filename]._cached = module_.exports;\r
+ return module_.exports;\r
+ };\r
+};\r
+\r
+if (typeof process === 'undefined') process = {};\r
+\r
+if (!process.nextTick) process.nextTick = (function () {\r
+ var queue = [];\r
+ var canPost = typeof window !== 'undefined'\r
+ && window.postMessage && window.addEventListener\r
+ ;\r
+ \r
+ if (canPost) {\r
+ window.addEventListener('message', function (ev) {\r
+ if (ev.source === window && ev.data === 'browserify-tick') {\r
+ ev.stopPropagation();\r
+ if (queue.length > 0) {\r
+ var fn = queue.shift();\r
+ fn();\r
+ }\r
+ }\r
+ }, true);\r
+ }\r
+ \r
+ return function (fn) {\r
+ if (canPost) {\r
+ queue.push(fn);\r
+ window.postMessage('browserify-tick', '*');\r
+ }\r
+ else setTimeout(fn, 0);\r
+ };\r
+})();\r
+\r
+if (!process.title) process.title = 'browser';\r
+\r
+if (!process.binding) process.binding = function (name) {\r
+ if (name === 'evals') return require('vm')\r
+ else throw new Error('No such module')\r
+};\r
+\r
+if (!process.cwd) process.cwd = function () { return '.' };\r
+\r
+require.define("path", function (require, module, exports, __dirname, __filename) {\r
+ function filter (xs, fn) {\r
+ var res = [];\r
+ for (var i = 0; i < xs.length; i++) {\r
+ if (fn(xs[i], i, xs)) res.push(xs[i]);\r
+ }\r
+ return res;\r
+}\r
+\r
+// resolves . and .. elements in a path array with directory names there\r
+// must be no slashes, empty elements, or device names (c:\) in the array\r
+// (so also no leading and trailing slashes - it does not distinguish\r
+// relative and absolute paths)\r
+function normalizeArray(parts, allowAboveRoot) {\r
+ // if the path tries to go above the root, `up` ends up > 0\r
+ var up = 0;\r
+ for (var i = parts.length; i >= 0; i--) {\r
+ var last = parts[i];\r
+ if (last == '.') {\r
+ parts.splice(i, 1);\r
+ } else if (last === '..') {\r
+ parts.splice(i, 1);\r
+ up++;\r
+ } else if (up) {\r
+ parts.splice(i, 1);\r
+ up--;\r
+ }\r
+ }\r
+\r
+ // if the path is allowed to go above the root, restore leading ..s\r
+ if (allowAboveRoot) {\r
+ for (; up--; up) {\r
+ parts.unshift('..');\r
+ }\r
+ }\r
+\r
+ return parts;\r
+}\r
+\r
+// Regex to split a filename into [*, dir, basename, ext]\r
+// posix version\r
+var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/;\r
+\r
+// path.resolve([from ...], to)\r
+// posix version\r
+exports.resolve = function() {\r
+var resolvedPath = '',\r
+ resolvedAbsolute = false;\r
+\r
+for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) {\r
+ var path = (i >= 0)\r
+ ? arguments[i]\r
+ : process.cwd();\r
+\r
+ // Skip empty and invalid entries\r
+ if (typeof path !== 'string' || !path) {\r
+ continue;\r
+ }\r
+\r
+ resolvedPath = path + '/' + resolvedPath;\r
+ resolvedAbsolute = path.charAt(0) === '/';\r
+}\r
+\r
+// At this point the path should be resolved to a full absolute path, but\r
+// handle relative paths to be safe (might happen when process.cwd() fails)\r
+\r
+// Normalize the path\r
+resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\r
+ return !!p;\r
+ }), !resolvedAbsolute).join('/');\r
+\r
+ return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\r
+};\r
+\r
+// path.normalize(path)\r
+// posix version\r
+exports.normalize = function(path) {\r
+var isAbsolute = path.charAt(0) === '/',\r
+ trailingSlash = path.slice(-1) === '/';\r
+\r
+// Normalize the path\r
+path = normalizeArray(filter(path.split('/'), function(p) {\r
+ return !!p;\r
+ }), !isAbsolute).join('/');\r
+\r
+ if (!path && !isAbsolute) {\r
+ path = '.';\r
+ }\r
+ if (path && trailingSlash) {\r
+ path += '/';\r
+ }\r
+ \r
+ return (isAbsolute ? '/' : '') + path;\r
+};\r
+\r
+\r
+// posix version\r
+exports.join = function() {\r
+ var paths = Array.prototype.slice.call(arguments, 0);\r
+ return exports.normalize(filter(paths, function(p, index) {\r
+ return p && typeof p === 'string';\r
+ }).join('/'));\r
+};\r
+\r
+\r
+exports.dirname = function(path) {\r
+ var dir = splitPathRe.exec(path)[1] || '';\r
+ var isWindows = false;\r
+ if (!dir) {\r
+ // No dirname\r
+ return '.';\r
+ } else if (dir.length === 1 ||\r
+ (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) {\r
+ // It is just a slash or a drive letter with a slash\r
+ return dir;\r
+ } else {\r
+ // It is a full dirname, strip trailing slash\r
+ return dir.substring(0, dir.length - 1);\r
+ }\r
+};\r
+\r
+\r
+exports.basename = function(path, ext) {\r
+ var f = splitPathRe.exec(path)[2] || '';\r
+ // TODO: make this comparison case-insensitive on windows?\r
+ if (ext && f.substr(-1 * ext.length) === ext) {\r
+ f = f.substr(0, f.length - ext.length);\r
+ }\r
+ return f;\r
+};\r
+\r
+\r
+exports.extname = function(path) {\r
+ return splitPathRe.exec(path)[3] || '';\r
+};\r
+\r
+});\r
+\r
+require.define("/shred.js", function (require, module, exports, __dirname, __filename) {\r
+ // Shred is an HTTP client library intended to simplify the use of Node's\r
+// built-in HTTP library. In particular, we wanted to make it easier to interact\r
+// with HTTP-based APIs.\r
+// \r
+// See the [examples](./examples.html) for more details.\r
+\r
+// Ax is a nice logging library we wrote. You can use any logger, providing it\r
+// has `info`, `warn`, `debug`, and `error` methods that take a string.\r
+var Ax = require("ax")\r
+ , CookieJarLib = require( "cookiejar" )\r
+ , CookieJar = CookieJarLib.CookieJar\r
+;\r
+\r
+// Shred takes some options, including a logger and request defaults.\r
+\r
+var Shred = function(options) {\r
+ options = (options||{});\r
+ this.agent = options.agent;\r
+ this.defaults = options.defaults||{};\r
+ this.log = options.logger||(new Ax({ level: "info" }));\r
+ this._sharedCookieJar = new CookieJar();\r
+ this.logCurl = options.logCurl || false;\r
+};\r
+\r
+// Most of the real work is done in the request and reponse classes.\r
+ \r
+Shred.Request = require("./shred/request");\r
+Shred.Response = require("./shred/response");\r
+\r
+// The `request` method kicks off a new request, instantiating a new `Request`\r
+// object and passing along whatever default options we were given.\r
+\r
+Shred.prototype = {\r
+ request: function(options) {\r
+ options.logger = this.log;\r
+ options.logCurl = options.logCurl || this.logCurl;\r
+ options.cookieJar = ( 'cookieJar' in options ) ? options.cookieJar : this._sharedCookieJar; // let them set cookieJar = null\r
+ options.agent = options.agent || this.agent;\r
+ // fill in default options\r
+ for (var key in this.defaults) {\r
+ if (this.defaults.hasOwnProperty(key) && !options[key]) {\r
+ options[key] = this.defaults[key]\r
+ }\r
+ }\r
+ return new Shred.Request(options);\r
+ }\r
+};\r
+\r
+// Define a bunch of convenience methods so that you don't have to include\r
+// a `method` property in your request options.\r
+\r
+"get put post delete".split(" ").forEach(function(method) {\r
+ Shred.prototype[method] = function(options) {\r
+ options.method = method;\r
+ return this.request(options);\r
+ };\r
+});\r
+\r
+\r
+module.exports = Shred;\r
+\r
+});\r
+\r
+require.define("/node_modules/ax/package.json", function (require, module, exports, __dirname, __filename) {\r
+ module.exports = {"main":"./lib/ax.js"}\r
+});\r
+\r
+require.define("/node_modules/ax/lib/ax.js", function (require, module, exports, __dirname, __filename) {\r
+ var inspect = require("util").inspect\r
+ , fs = require("fs")\r
+;\r
+\r
+\r
+// this is a quick-and-dirty logger. there are other nicer loggers out there\r
+// but the ones i found were also somewhat involved. this one has a Ruby\r
+// logger type interface\r
+//\r
+// we can easily replace this, provide the info, debug, etc. methods are the\r
+// same. or, we can change Haiku to use a more standard node.js interface\r
+\r
+var format = function(level,message) {\r
+ var debug = (level=="debug"||level=="error");\r
+ if (!message) { return message.toString(); }\r
+ if (typeof(message) == "object") {\r
+ if (message instanceof Error && debug) {\r
+ return message.stack;\r
+ } else {\r
+ return inspect(message);\r
+ }\r
+ } else {\r
+ return message.toString();\r
+ }\r
+};\r
+\r
+var noOp = function(message) { return this; }\r
+var makeLogger = function(level,fn) {\r
+ return function(message) { \r
+ this.stream.write(this.format(level, message)+"\n");\r
+ return this;\r
+ }\r
+};\r
+\r
+var Logger = function(options) {\r
+ var logger = this;\r
+ var options = options||{};\r
+\r
+ // Default options\r
+ options.level = options.level || "info";\r
+ options.timestamp = options.timestamp || true;\r
+ options.prefix = options.prefix || "";\r
+ logger.options = options;\r
+\r
+ // Allows a prefix to be added to the message.\r
+ //\r
+ // var logger = new Ax({ module: 'Haiku' })\r
+ // logger.warn('this is going to be awesome!');\r
+ // //=> Haiku: this is going to be awesome!\r
+ //\r
+ if (logger.options.module){\r
+ logger.options.prefix = logger.options.module;\r
+ }\r
+\r
+ // Write to stderr or a file\r
+ if (logger.options.file){\r
+ logger.stream = fs.createWriteStream(logger.options.file, {"flags": "a"});\r
+ } else {\r
+ if(process.title === "node")\r
+ logger.stream = process.stderr;\r
+ else if(process.title === "browser")\r
+ logger.stream = function () {\r
+ // Work around weird console context issue: http://code.google.com/p/chromium/issues/detail?id=48662\r
+ return console[logger.options.level].apply(console, arguments);\r
+ };\r
+ }\r
+\r
+ switch(logger.options.level){\r
+ case 'debug':\r
+ ['debug', 'info', 'warn'].forEach(function (level) {\r
+ logger[level] = Logger.writer(level);\r
+ });\r
+ case 'info':\r
+ ['info', 'warn'].forEach(function (level) {\r
+ logger[level] = Logger.writer(level);\r
+ });\r
+ case 'warn':\r
+ logger.warn = Logger.writer('warn');\r
+ }\r
+}\r
+\r
+// Used to define logger methods\r
+Logger.writer = function(level){\r
+ return function(message){\r
+ var logger = this;\r
+\r
+ if(process.title === "node")\r
+ logger.stream.write(logger.format(level, message) + '\n');\r
+ else if(process.title === "browser")\r
+ logger.stream(logger.format(level, message) + '\n');\r
+\r
+ };\r
+}\r
+\r
+\r
+Logger.prototype = {\r
+ info: function(){},\r
+ debug: function(){},\r
+ warn: function(){},\r
+ error: Logger.writer('error'),\r
+ format: function(level, message){\r
+ if (! message) return '';\r
+\r
+ var logger = this\r
+ , prefix = logger.options.prefix\r
+ , timestamp = logger.options.timestamp ? " " + (new Date().toISOString()) : ""\r
+ ;\r
+\r
+ return (prefix + timestamp + ": " + message);\r
+ }\r
+};\r
+\r
+module.exports = Logger;\r
+\r
+});\r
+\r
+require.define("util", function (require, module, exports, __dirname, __filename) {\r
+ // todo\r
+\r
+});\r
+\r
+require.define("fs", function (require, module, exports, __dirname, __filename) {\r
+ // nothing to see here... no file methods for the browser\r
+\r
+});\r
+\r
+require.define("/node_modules/cookiejar/package.json", function (require, module, exports, __dirname, __filename) {\r
+ module.exports = {"main":"cookiejar.js"}\r
+});\r
+\r
+require.define("/node_modules/cookiejar/cookiejar.js", function (require, module, exports, __dirname, __filename) {\r
+ exports.CookieAccessInfo=CookieAccessInfo=function CookieAccessInfo(domain,path,secure,script) {\r
+ if(this instanceof CookieAccessInfo) {\r
+ this.domain=domain||undefined;\r
+ this.path=path||"/";\r
+ this.secure=!!secure;\r
+ this.script=!!script;\r
+ return this;\r
+ }\r
+ else {\r
+ return new CookieAccessInfo(domain,path,secure,script) \r
+ }\r
+}\r
+\r
+exports.Cookie=Cookie=function Cookie(cookiestr) {\r
+ if(cookiestr instanceof Cookie) {\r
+ return cookiestr;\r
+ }\r
+ else {\r
+ if(this instanceof Cookie) {\r
+ this.name = null;\r
+ this.value = null;\r
+ this.expiration_date = Infinity;\r
+ this.path = "/";\r
+ this.domain = null;\r
+ this.secure = false; //how to define?\r
+ this.noscript = false; //httponly\r
+ if(cookiestr) {\r
+ this.parse(cookiestr)\r
+ }\r
+ return this;\r
+ }\r
+ return new Cookie(cookiestr)\r
+ }\r
+}\r
+\r
+Cookie.prototype.toString = function toString() {\r
+ var str=[this.name+"="+this.value];\r
+ if(this.expiration_date !== Infinity) {\r
+ str.push("expires="+(new Date(this.expiration_date)).toGMTString());\r
+ }\r
+ if(this.domain) {\r
+ str.push("domain="+this.domain);\r
+ }\r
+ if(this.path) {\r
+ str.push("path="+this.path);\r
+ }\r
+ if(this.secure) {\r
+ str.push("secure");\r
+ }\r
+ if(this.noscript) {\r
+ str.push("httponly");\r
+ }\r
+ return str.join("; ");\r
+}\r
+\r
+Cookie.prototype.toValueString = function toValueString() {\r
+ return this.name+"="+this.value;\r
+}\r
+\r
+var cookie_str_splitter=/[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g\r
+Cookie.prototype.parse = function parse(str) {\r
+ if(this instanceof Cookie) {\r
+ var parts=str.split(";")\r
+ , pair=parts[0].match(/([^=]+)=((?:.|\n)*)/)\r
+ , key=pair[1]\r
+ , value=pair[2];\r
+ this.name = key;\r
+ this.value = value;\r
+ \r
+ for(var i=1;i<parts.length;i++) {\r
+ pair=parts[i].match(/([^=]+)(?:=((?:.|\n)*))?/)\r
+ , key=pair[1].trim().toLowerCase()\r
+ , value=pair[2];\r
+ switch(key) {\r
+ case "httponly":\r
+ this.noscript = true;\r
+ break;\r
+ case "expires":\r
+ this.expiration_date = value\r
+ ? Number(Date.parse(value))\r
+ : Infinity;\r
+ break;\r
+ case "path":\r
+ this.path = value\r
+ ? value.trim()\r
+ : "";\r
+ break;\r
+ case "domain":\r
+ this.domain = value\r
+ ? value.trim()\r
+ : "";\r
+ break;\r
+ case "secure":\r
+ this.secure = true;\r
+ break\r
+ }\r
+ }\r
+ \r
+ return this;\r
+ }\r
+ return new Cookie().parse(str)\r
+}\r
+\r
+Cookie.prototype.matches = function matches(access_info) {\r
+ if(this.noscript && access_info.script\r
+ || this.secure && !access_info.secure\r
+ || !this.collidesWith(access_info)) {\r
+ return false\r
+ }\r
+ return true;\r
+}\r
+\r
+Cookie.prototype.collidesWith = function collidesWith(access_info) {\r
+ if((this.path && !access_info.path) || (this.domain && !access_info.domain)) {\r
+ return false\r
+ }\r
+ if(this.path && access_info.path.indexOf(this.path) !== 0) {\r
+ return false;\r
+ }\r
+ if (this.domain===access_info.domain) {\r
+ return true;\r
+ }\r
+ else if(this.domain && this.domain.charAt(0)===".")\r
+ {\r
+ var wildcard=access_info.domain.indexOf(this.domain.slice(1))\r
+ if(wildcard===-1 || wildcard!==access_info.domain.length-this.domain.length+1) {\r
+ return false;\r
+ }\r
+ }\r
+ else if(this.domain){\r
+ return false\r
+ }\r
+ return true;\r
+}\r
+\r
+exports.CookieJar=CookieJar=function CookieJar() {\r
+ if(this instanceof CookieJar) {\r
+ var cookies = {} //name: [Cookie]\r
+ \r
+ this.setCookie = function setCookie(cookie) {\r
+ cookie = Cookie(cookie);\r
+ //Delete the cookie if the set is past the current time\r
+ var remove = cookie.expiration_date <= Date.now();\r
+ if(cookie.name in cookies) {\r
+ var cookies_list = cookies[cookie.name];\r
+ for(var i=0;i<cookies_list.length;i++) {\r
+ var collidable_cookie = cookies_list[i];\r
+ if(collidable_cookie.collidesWith(cookie)) {\r
+ if(remove) {\r
+ cookies_list.splice(i,1);\r
+ if(cookies_list.length===0) {\r
+ delete cookies[cookie.name]\r
+ }\r
+ return false;\r
+ }\r
+ else {\r
+ return cookies_list[i]=cookie;\r
+ }\r
+ }\r
+ }\r
+ if(remove) {\r
+ return false;\r
+ }\r
+ cookies_list.push(cookie);\r
+ return cookie;\r
+ }\r
+ else if(remove){\r
+ return false;\r
+ }\r
+ else {\r
+ return cookies[cookie.name]=[cookie];\r
+ }\r
+ }\r
+ //returns a cookie\r
+ this.getCookie = function getCookie(cookie_name,access_info) {\r
+ var cookies_list = cookies[cookie_name];\r
+ for(var i=0;i<cookies_list.length;i++) {\r
+ var cookie = cookies_list[i];\r
+ if(cookie.expiration_date <= Date.now()) {\r
+ if(cookies_list.length===0) {\r
+ delete cookies[cookie.name]\r
+ }\r
+ continue;\r
+ }\r
+ if(cookie.matches(access_info)) {\r
+ return cookie;\r
+ }\r
+ }\r
+ }\r
+ //returns a list of cookies\r
+ this.getCookies = function getCookies(access_info) {\r
+ var matches=[];\r
+ for(var cookie_name in cookies) {\r
+ var cookie=this.getCookie(cookie_name,access_info);\r
+ if (cookie) {\r
+ matches.push(cookie);\r
+ }\r
+ }\r
+ matches.toString=function toString(){return matches.join(":");}\r
+ matches.toValueString=function() {return matches.map(function(c){return c.toValueString();}).join(';');}\r
+ return matches;\r
+ }\r
+ \r
+ return this;\r
+ }\r
+ return new CookieJar()\r
+}\r
+\r
+\r
+//returns list of cookies that were set correctly\r
+CookieJar.prototype.setCookies = function setCookies(cookies) {\r
+ cookies=Array.isArray(cookies)\r
+ ?cookies\r
+ :cookies.split(cookie_str_splitter);\r
+ var successful=[]\r
+ for(var i=0;i<cookies.length;i++) {\r
+ var cookie = Cookie(cookies[i]);\r
+ if(this.setCookie(cookie)) {\r
+ successful.push(cookie);\r
+ }\r
+ }\r
+ return successful;\r
+}\r
+\r
+});\r
+\r
+require.define("/shred/request.js", function (require, module, exports, __dirname, __filename) {\r
+ // The request object encapsulates a request, creating a Node.js HTTP request and\r
+// then handling the response.\r
+\r
+var HTTP = require("http")\r
+ , HTTPS = require("https")\r
+ , parseUri = require("./parseUri")\r
+ , Emitter = require('events').EventEmitter\r
+ , sprintf = require("sprintf").sprintf\r
+ , Response = require("./response")\r
+ , HeaderMixins = require("./mixins/headers")\r
+ , Content = require("./content")\r
+;\r
+\r
+var STATUS_CODES = HTTP.STATUS_CODES || {\r
+ 100 : 'Continue',\r
+ 101 : 'Switching Protocols',\r
+ 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918\r
+ 200 : 'OK',\r
+ 201 : 'Created',\r
+ 202 : 'Accepted',\r
+ 203 : 'Non-Authoritative Information',\r
+ 204 : 'No Content',\r
+ 205 : 'Reset Content',\r
+ 206 : 'Partial Content',\r
+ 207 : 'Multi-Status', // RFC 4918\r
+ 300 : 'Multiple Choices',\r
+ 301 : 'Moved Permanently',\r
+ 302 : 'Moved Temporarily',\r
+ 303 : 'See Other',\r
+ 304 : 'Not Modified',\r
+ 305 : 'Use Proxy',\r
+ 307 : 'Temporary Redirect',\r
+ 400 : 'Bad Request',\r
+ 401 : 'Unauthorized',\r
+ 402 : 'Payment Required',\r
+ 403 : 'Forbidden',\r
+ 404 : 'Not Found',\r
+ 405 : 'Method Not Allowed',\r
+ 406 : 'Not Acceptable',\r
+ 407 : 'Proxy Authentication Required',\r
+ 408 : 'Request Time-out',\r
+ 409 : 'Conflict',\r
+ 410 : 'Gone',\r
+ 411 : 'Length Required',\r
+ 412 : 'Precondition Failed',\r
+ 413 : 'Request Entity Too Large',\r
+ 414 : 'Request-URI Too Large',\r
+ 415 : 'Unsupported Media Type',\r
+ 416 : 'Requested Range Not Satisfiable',\r
+ 417 : 'Expectation Failed',\r
+ 418 : 'I\'m a teapot', // RFC 2324\r
+ 422 : 'Unprocessable Entity', // RFC 4918\r
+ 423 : 'Locked', // RFC 4918\r
+ 424 : 'Failed Dependency', // RFC 4918\r
+ 425 : 'Unordered Collection', // RFC 4918\r
+ 426 : 'Upgrade Required', // RFC 2817\r
+ 500 : 'Internal Server Error',\r
+ 501 : 'Not Implemented',\r
+ 502 : 'Bad Gateway',\r
+ 503 : 'Service Unavailable',\r
+ 504 : 'Gateway Time-out',\r
+ 505 : 'HTTP Version not supported',\r
+ 506 : 'Variant Also Negotiates', // RFC 2295\r
+ 507 : 'Insufficient Storage', // RFC 4918\r
+ 509 : 'Bandwidth Limit Exceeded',\r
+ 510 : 'Not Extended' // RFC 2774\r
+};\r
+\r
+// The Shred object itself constructs the `Request` object. You should rarely\r
+// need to do this directly.\r
+\r
+var Request = function(options) {\r
+ this.log = options.logger;\r
+ this.cookieJar = options.cookieJar;\r
+ this.encoding = options.encoding;\r
+ this.logCurl = options.logCurl;\r
+ processOptions(this,options||{});\r
+ createRequest(this);\r
+};\r
+\r
+// A `Request` has a number of properties, many of which help with details like\r
+// URL parsing or defaulting the port for the request.\r
+\r
+Object.defineProperties(Request.prototype, {\r
+\r
+// - **url**. You can set the `url` property with a valid URL string and all the\r
+// URL-related properties (host, port, etc.) will be automatically set on the\r
+// request object.\r
+\r
+ url: {\r
+ get: function() {\r
+ if (!this.scheme) { return null; }\r
+ return sprintf("%s://%s:%s%s",\r
+ this.scheme, this.host, this.port,\r
+ (this.proxy ? "/" : this.path) +\r
+ (this.query ? ("?" + this.query) : ""));\r
+ },\r
+ set: function(_url) {\r
+ _url = parseUri(_url);\r
+ this.scheme = _url.protocol;\r
+ this.host = _url.host;\r
+ this.port = _url.port;\r
+ this.path = _url.path;\r
+ this.query = _url.query;\r
+ return this;\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **headers**. Returns a hash representing the request headers. You can't set\r
+// this directly, only get it. You can add or modify headers by using the\r
+// `setHeader` or `setHeaders` method. This ensures that the headers are\r
+// normalized - that is, you don't accidentally send `Content-Type` and\r
+// `content-type` headers. Keep in mind that if you modify the returned hash,\r
+// it will *not* modify the request headers.\r
+\r
+ headers: {\r
+ get: function() {\r
+ return this.getHeaders();\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **port**. Unless you set the `port` explicitly or include it in the URL, it\r
+// will default based on the scheme.\r
+\r
+ port: {\r
+ get: function() {\r
+ if (!this._port) {\r
+ switch(this.scheme) {\r
+ case "https": return this._port = 443;\r
+ case "http":\r
+ default: return this._port = 80;\r
+ }\r
+ }\r
+ return this._port;\r
+ },\r
+ set: function(value) { this._port = value; return this; },\r
+ enumerable: true\r
+ },\r
+\r
+// - **method**. The request method - `get`, `put`, `post`, etc. that will be\r
+// used to make the request. Defaults to `get`.\r
+\r
+ method: {\r
+ get: function() {\r
+ return this._method = (this._method||"GET");\r
+ },\r
+ set: function(value) {\r
+ this._method = value; return this;\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **query**. Can be set either with a query string or a hash (object). Get\r
+// will always return a properly escaped query string or null if there is no\r
+// query component for the request.\r
+\r
+ query: {\r
+ get: function() {return this._query;},\r
+ set: function(value) {\r
+ var stringify = function (hash) {\r
+ var query = "";\r
+ for (var key in hash) {\r
+ query += encodeURIComponent(key) + '=' + encodeURIComponent(hash[key]) + '&';\r
+ }\r
+ // Remove the last '&'\r
+ query = query.slice(0, -1);\r
+ return query;\r
+ }\r
+\r
+ if (value) {\r
+ if (typeof value === 'object') {\r
+ value = stringify(value);\r
+ }\r
+ this._query = value;\r
+ } else {\r
+ this._query = "";\r
+ }\r
+ return this;\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **parameters**. This will return the query parameters in the form of a hash\r
+// (object).\r
+\r
+ parameters: {\r
+ get: function() { return QueryString.parse(this._query||""); },\r
+ enumerable: true\r
+ },\r
+\r
+// - **content**. (Aliased as `body`.) Set this to add a content entity to the\r
+// request. Attempts to use the `content-type` header to determine what to do\r
+// with the content value. Get this to get back a [`Content`\r
+// object](./content.html).\r
+\r
+ body: {\r
+ get: function() { return this._body; },\r
+ set: function(value) {\r
+ this._body = new Content({\r
+ data: value,\r
+ type: this.getHeader("Content-Type")\r
+ });\r
+ this.setHeader("Content-Type",this.content.type);\r
+ this.setHeader("Content-Length",this.content.length);\r
+ return this;\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **timeout**. Used to determine how long to wait for a response. Does not\r
+// distinguish between connect timeouts versus request timeouts. Set either in\r
+// milliseconds or with an object with temporal attributes (hours, minutes,\r
+// seconds) and convert it into milliseconds. Get will always return\r
+// milliseconds.\r
+\r
+ timeout: {\r
+ get: function() { return this._timeout; }, // in milliseconds\r
+ set: function(timeout) {\r
+ var request = this\r
+ , milliseconds = 0;\r
+ ;\r
+ if (!timeout) return this;\r
+ if (typeof timeout==="number") { milliseconds = timeout; }\r
+ else {\r
+ milliseconds = (timeout.milliseconds||0) +\r
+ (1000 * ((timeout.seconds||0) +\r
+ (60 * ((timeout.minutes||0) +\r
+ (60 * (timeout.hours||0))))));\r
+ }\r
+ this._timeout = milliseconds;\r
+ return this;\r
+ },\r
+ enumerable: true\r
+ }\r
+});\r
+\r
+// Alias `body` property to `content`. Since the [content object](./content.html)\r
+// has a `body` attribute, it's preferable to use `content` since you can then\r
+// access the raw content data using `content.body`.\r
+\r
+Object.defineProperty(Request.prototype,"content",\r
+ Object.getOwnPropertyDescriptor(Request.prototype, "body"));\r
+\r
+// The `Request` object can be pretty overwhelming to view using the built-in\r
+// Node.js inspect method. We want to make it a bit more manageable. This\r
+// probably goes [too far in the other\r
+// direction](https://github.com/spire-io/shred/issues/2).\r
+\r
+Request.prototype.inspect = function () {\r
+ var request = this;\r
+ var headers = this.format_headers();\r
+ var summary = ["<Shred Request> ", request.method.toUpperCase(),\r
+ request.url].join(" ")\r
+ return [ summary, "- Headers:", headers].join("\n");\r
+};\r
+\r
+Request.prototype.format_headers = function () {\r
+ var array = []\r
+ var headers = this._headers\r
+ for (var key in headers) {\r
+ if (headers.hasOwnProperty(key)) {\r
+ var value = headers[key]\r
+ array.push("\t" + key + ": " + value);\r
+ }\r
+ }\r
+ return array.join("\n");\r
+};\r
+\r
+// Allow chainable 'on's: shred.get({ ... }).on( ... ). You can pass in a\r
+// single function, a pair (event, function), or a hash:\r
+// { event: function, event: function }\r
+Request.prototype.on = function (eventOrHash, listener) {\r
+ var emitter = this.emitter;\r
+ // Pass in a single argument as a function then make it the default response handler\r
+ if (arguments.length === 1 && typeof(eventOrHash) === 'function') {\r
+ emitter.on('response', eventOrHash);\r
+ } else if (arguments.length === 1 && typeof(eventOrHash) === 'object') {\r
+ for (var key in eventOrHash) {\r
+ if (eventOrHash.hasOwnProperty(key)) {\r
+ emitter.on(key, eventOrHash[key]);\r
+ }\r
+ }\r
+ } else {\r
+ emitter.on(eventOrHash, listener);\r
+ }\r
+ return this;\r
+};\r
+\r
+// Add in the header methods. Again, these ensure we don't get the same header\r
+// multiple times with different case conventions.\r
+HeaderMixins.gettersAndSetters(Request);\r
+\r
+// `processOptions` is called from the constructor to handle all the work\r
+// associated with making sure we do our best to ensure we have a valid request.\r
+\r
+var processOptions = function(request,options) {\r
+\r
+ request.log.debug("Processing request options ..");\r
+\r
+ // We'll use `request.emitter` to manage the `on` event handlers.\r
+ request.emitter = (new Emitter);\r
+\r
+ request.agent = options.agent;\r
+\r
+ // Set up the handlers ...\r
+ if (options.on) {\r
+ for (var key in options.on) {\r
+ if (options.on.hasOwnProperty(key)) {\r
+ request.emitter.on(key, options.on[key]);\r
+ }\r
+ }\r
+ }\r
+\r
+ // Make sure we were give a URL or a host\r
+ if (!options.url && !options.host) {\r
+ request.emitter.emit("request_error",\r
+ new Error("No url or url options (host, port, etc.)"));\r
+ return;\r
+ }\r
+\r
+ // Allow for the [use of a proxy](http://www.jmarshall.com/easy/http/#proxies).\r
+\r
+ if (options.url) {\r
+ if (options.proxy) {\r
+ request.url = options.proxy;\r
+ request.path = options.url;\r
+ } else {\r
+ request.url = options.url;\r
+ }\r
+ }\r
+\r
+ // Set the remaining options.\r
+ request.query = options.query||options.parameters||request.query ;\r
+ request.method = options.method;\r
+ request.setHeader("user-agent",options.agent||"Shred");\r
+ request.setHeaders(options.headers);\r
+\r
+ if (request.cookieJar) {\r
+ var cookies = request.cookieJar.getCookies( CookieAccessInfo( request.host, request.path ) );\r
+ if (cookies.length) {\r
+ var cookieString = request.getHeader('cookie')||'';\r
+ for (var cookieIndex = 0; cookieIndex < cookies.length; ++cookieIndex) {\r
+ if ( cookieString.length && cookieString[ cookieString.length - 1 ] != ';' )\r
+ {\r
+ cookieString += ';';\r
+ }\r
+ cookieString += cookies[ cookieIndex ].name + '=' + cookies[ cookieIndex ].value + ';';\r
+ }\r
+ request.setHeader("cookie", cookieString);\r
+ }\r
+ }\r
+ \r
+ // The content entity can be set either using the `body` or `content` attributes.\r
+ if (options.body||options.content) {\r
+ request.content = options.body||options.content;\r
+ }\r
+ request.timeout = options.timeout;\r
+\r
+};\r
+\r
+// `createRequest` is also called by the constructor, after `processOptions`.\r
+// This actually makes the request and processes the response, so `createRequest`\r
+// is a bit of a misnomer.\r
+\r
+var createRequest = function(request) {\r
+ var timeout ;\r
+\r
+ request.log.debug("Creating request ..");\r
+ request.log.debug(request);\r
+\r
+ var reqParams = {\r
+ host: request.host,\r
+ port: request.port,\r
+ method: request.method,\r
+ path: request.path + (request.query ? '?'+request.query : ""),\r
+ headers: request.getHeaders(),\r
+ // Node's HTTP/S modules will ignore this, but we are using the\r
+ // browserify-http module in the browser for both HTTP and HTTPS, and this\r
+ // is how you differentiate the two.\r
+ scheme: request.scheme,\r
+ // Use a provided agent. 'Undefined' is the default, which uses a global\r
+ // agent.\r
+ agent: request.agent\r
+ };\r
+\r
+ if (request.logCurl) {\r
+ logCurl(request);\r
+ }\r
+\r
+ var http = request.scheme == "http" ? HTTP : HTTPS;\r
+\r
+ // Set up the real request using the selected library. The request won't be\r
+ // sent until we call `.end()`.\r
+ request._raw = http.request(reqParams, function(response) {\r
+ request.log.debug("Received response ..");\r
+\r
+ // We haven't timed out and we have a response, so make sure we clear the\r
+ // timeout so it doesn't fire while we're processing the response.\r
+ clearTimeout(timeout);\r
+\r
+ // Construct a Shred `Response` object from the response. This will stream\r
+ // the response, thus the need for the callback. We can access the response\r
+ // entity safely once we're in the callback.\r
+ response = new Response(response, request, function(response) {\r
+\r
+ // Set up some event magic. The precedence is given first to\r
+ // status-specific handlers, then to responses for a given event, and then\r
+ // finally to the more general `response` handler. In the last case, we\r
+ // need to first make sure we're not dealing with a a redirect.\r
+ var emit = function(event) {\r
+ var emitter = request.emitter;\r
+ var textStatus = STATUS_CODES[response.status] ? STATUS_CODES[response.status].toLowerCase() : null;\r
+ if (emitter.listeners(response.status).length > 0 || emitter.listeners(textStatus).length > 0) {\r
+ emitter.emit(response.status, response);\r
+ emitter.emit(textStatus, response);\r
+ } else {\r
+ if (emitter.listeners(event).length>0) {\r
+ emitter.emit(event, response);\r
+ } else if (!response.isRedirect) {\r
+ emitter.emit("response", response);\r
+ //console.warn("Request has no event listener for status code " + response.status);\r
+ }\r
+ }\r
+ };\r
+\r
+ // Next, check for a redirect. We simply repeat the request with the URL\r
+ // given in the `Location` header. We fire a `redirect` event.\r
+ if (response.isRedirect) {\r
+ request.log.debug("Redirecting to "\r
+ + response.getHeader("Location"));\r
+ request.url = response.getHeader("Location");\r
+ emit("redirect");\r
+ createRequest(request);\r
+\r
+ // Okay, it's not a redirect. Is it an error of some kind?\r
+ } else if (response.isError) {\r
+ emit("error");\r
+ } else {\r
+ // It looks like we're good shape. Trigger the `success` event.\r
+ emit("success");\r
+ }\r
+ });\r
+ });\r
+\r
+ // We're still setting up the request. Next, we're going to handle error cases\r
+ // where we have no response. We don't emit an error event because that event\r
+ // takes a response. We don't response handlers to have to check for a null\r
+ // value. However, we [should introduce a different event\r
+ // type](https://github.com/spire-io/shred/issues/3) for this type of error.\r
+ request._raw.on("error", function(error) {\r
+ request.emitter.emit("request_error", error);\r
+ });\r
+\r
+ request._raw.on("socket", function(socket) {\r
+ request.emitter.emit("socket", socket);\r
+ });\r
+\r
+ // TCP timeouts should also trigger the "response_error" event.\r
+ request._raw.on('socket', function () {\r
+ request._raw.socket.on('timeout', function () {\r
+ // This should trigger the "error" event on the raw request, which will\r
+ // trigger the "response_error" on the shred request.\r
+ request._raw.abort();\r
+ });\r
+ });\r
+\r
+\r
+ // We're almost there. Next, we need to write the request entity to the\r
+ // underlying request object.\r
+ if (request.content) {\r
+ request.log.debug("Streaming body: '" +\r
+ request.content.data.slice(0,59) + "' ... ");\r
+ request._raw.write(request.content.data);\r
+ }\r
+\r
+ // Finally, we need to set up the timeout. We do this last so that we don't\r
+ // start the clock ticking until the last possible moment.\r
+ if (request.timeout) {\r
+ timeout = setTimeout(function() {\r
+ request.log.debug("Timeout fired, aborting request ...");\r
+ request._raw.abort();\r
+ request.emitter.emit("timeout", request);\r
+ },request.timeout);\r
+ }\r
+\r
+ // The `.end()` method will cause the request to fire. Technically, it might\r
+ // have already sent the headers and body.\r
+ request.log.debug("Sending request ...");\r
+ request._raw.end();\r
+};\r
+\r
+// Logs the curl command for the request.\r
+var logCurl = function (req) {\r
+ var headers = req.getHeaders();\r
+ var headerString = "";\r
+\r
+ for (var key in headers) {\r
+ headerString += '-H "' + key + ": " + headers[key] + '" ';\r
+ }\r
+\r
+ var bodyString = ""\r
+\r
+ if (req.content) {\r
+ bodyString += "-d '" + req.content.body + "' ";\r
+ }\r
+\r
+ var query = req.query ? '?' + req.query : "";\r
+\r
+ console.log("curl " +\r
+ "-X " + req.method.toUpperCase() + " " +\r
+ req.scheme + "://" + req.host + ":" + req.port + req.path + query + " " +\r
+ headerString +\r
+ bodyString\r
+ );\r
+};\r
+\r
+\r
+module.exports = Request;\r
+\r
+});\r
+\r
+require.define("http", function (require, module, exports, __dirname, __filename) {\r
+ // todo\r
+\r
+});\r
+\r
+require.define("https", function (require, module, exports, __dirname, __filename) {\r
+ // todo\r
+\r
+});\r
+\r
+require.define("/shred/parseUri.js", function (require, module, exports, __dirname, __filename) {\r
+ // parseUri 1.2.2\r
+// (c) Steven Levithan <stevenlevithan.com>\r
+// MIT License\r
+\r
+function parseUri (str) {\r
+ var o = parseUri.options,\r
+ m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),\r
+ uri = {},\r
+ i = 14;\r
+\r
+ while (i--) uri[o.key[i]] = m[i] || "";\r
+\r
+ uri[o.q.name] = {};\r
+ uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {\r
+ if ($1) uri[o.q.name][$1] = $2;\r
+ });\r
+\r
+ return uri;\r
+};\r
+\r
+parseUri.options = {\r
+ strictMode: false,\r
+ key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],\r
+ q: {\r
+ name: "queryKey",\r
+ parser: /(?:^|&)([^&=]*)=?([^&]*)/g\r
+ },\r
+ parser: {\r
+ strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,\r
+ loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/\r
+ }\r
+};\r
+\r
+module.exports = parseUri;\r
+\r
+});\r
+\r
+require.define("events", function (require, module, exports, __dirname, __filename) {\r
+ if (!process.EventEmitter) process.EventEmitter = function () {};\r
+\r
+var EventEmitter = exports.EventEmitter = process.EventEmitter;\r
+var isArray = typeof Array.isArray === 'function'\r
+ ? Array.isArray\r
+ : function (xs) {\r
+ return Object.toString.call(xs) === '[object Array]'\r
+ }\r
+;\r
+\r
+// By default EventEmitters will print a warning if more than\r
+// 10 listeners are added to it. This is a useful default which\r
+// helps finding memory leaks.\r
+//\r
+// Obviously not all Emitters should be limited to 10. This function allows\r
+// that to be increased. Set to zero for unlimited.\r
+var defaultMaxListeners = 10;\r
+EventEmitter.prototype.setMaxListeners = function(n) {\r
+ if (!this._events) this._events = {};\r
+ this._events.maxListeners = n;\r
+};\r
+\r
+\r
+EventEmitter.prototype.emit = function(type) {\r
+ // If there is no 'error' event listener then throw.\r
+ if (type === 'error') {\r
+ if (!this._events || !this._events.error ||\r
+ (isArray(this._events.error) && !this._events.error.length))\r
+ {\r
+ if (arguments[1] instanceof Error) {\r
+ throw arguments[1]; // Unhandled 'error' event\r
+ } else {\r
+ throw new Error("Uncaught, unspecified 'error' event.");\r
+ }\r
+ return false;\r
+ }\r
+ }\r
+\r
+ if (!this._events) return false;\r
+ var handler = this._events[type];\r
+ if (!handler) return false;\r
+\r
+ if (typeof handler == 'function') {\r
+ switch (arguments.length) {\r
+ // fast cases\r
+ case 1:\r
+ handler.call(this);\r
+ break;\r
+ case 2:\r
+ handler.call(this, arguments[1]);\r
+ break;\r
+ case 3:\r
+ handler.call(this, arguments[1], arguments[2]);\r
+ break;\r
+ // slower\r
+ default:\r
+ var args = Array.prototype.slice.call(arguments, 1);\r
+ handler.apply(this, args);\r
+ }\r
+ return true;\r
+\r
+ } else if (isArray(handler)) {\r
+ var args = Array.prototype.slice.call(arguments, 1);\r
+\r
+ var listeners = handler.slice();\r
+ for (var i = 0, l = listeners.length; i < l; i++) {\r
+ listeners[i].apply(this, args);\r
+ }\r
+ return true;\r
+\r
+ } else {\r
+ return false;\r
+ }\r
+};\r
+\r
+// EventEmitter is defined in src/node_events.cc\r
+// EventEmitter.prototype.emit() is also defined there.\r
+EventEmitter.prototype.addListener = function(type, listener) {\r
+ if ('function' !== typeof listener) {\r
+ throw new Error('addListener only takes instances of Function');\r
+ }\r
+\r
+ if (!this._events) this._events = {};\r
+\r
+ // To avoid recursion in the case that type == "newListeners"! Before\r
+ // adding it to the listeners, first emit "newListeners".\r
+ this.emit('newListener', type, listener);\r
+\r
+ if (!this._events[type]) {\r
+ // Optimize the case of one listener. Don't need the extra array object.\r
+ this._events[type] = listener;\r
+ } else if (isArray(this._events[type])) {\r
+\r
+ // Check for listener leak\r
+ if (!this._events[type].warned) {\r
+ var m;\r
+ if (this._events.maxListeners !== undefined) {\r
+ m = this._events.maxListeners;\r
+ } else {\r
+ m = defaultMaxListeners;\r
+ }\r
+\r
+ if (m && m > 0 && this._events[type].length > m) {\r
+ this._events[type].warned = true;\r
+ console.error('(node) warning: possible EventEmitter memory ' +\r
+ 'leak detected. %d listeners added. ' +\r
+ 'Use emitter.setMaxListeners() to increase limit.',\r
+ this._events[type].length);\r
+ console.trace();\r
+ }\r
+ }\r
+\r
+ // If we've already got an array, just append.\r
+ this._events[type].push(listener);\r
+ } else {\r
+ // Adding the second element, need to change to array.\r
+ this._events[type] = [this._events[type], listener];\r
+ }\r
+\r
+ return this;\r
+};\r
+\r
+EventEmitter.prototype.on = EventEmitter.prototype.addListener;\r
+\r
+EventEmitter.prototype.once = function(type, listener) {\r
+ var self = this;\r
+ self.on(type, function g() {\r
+ self.removeListener(type, g);\r
+ listener.apply(this, arguments);\r
+ });\r
+\r
+ return this;\r
+};\r
+\r
+EventEmitter.prototype.removeListener = function(type, listener) {\r
+ if ('function' !== typeof listener) {\r
+ throw new Error('removeListener only takes instances of Function');\r
+ }\r
+\r
+ // does not use listeners(), so no side effect of creating _events[type]\r
+ if (!this._events || !this._events[type]) return this;\r
+\r
+ var list = this._events[type];\r
+\r
+ if (isArray(list)) {\r
+ var i = list.indexOf(listener);\r
+ if (i < 0) return this;\r
+ list.splice(i, 1);\r
+ if (list.length == 0)\r
+ delete this._events[type];\r
+ } else if (this._events[type] === listener) {\r
+ delete this._events[type];\r
+ }\r
+\r
+ return this;\r
+};\r
+\r
+EventEmitter.prototype.removeAllListeners = function(type) {\r
+ // does not use listeners(), so no side effect of creating _events[type]\r
+ if (type && this._events && this._events[type]) this._events[type] = null;\r
+ return this;\r
+};\r
+\r
+EventEmitter.prototype.listeners = function(type) {\r
+ if (!this._events) this._events = {};\r
+ if (!this._events[type]) this._events[type] = [];\r
+ if (!isArray(this._events[type])) {\r
+ this._events[type] = [this._events[type]];\r
+ }\r
+ return this._events[type];\r
+};\r
+\r
+});\r
+\r
+require.define("/node_modules/sprintf/package.json", function (require, module, exports, __dirname, __filename) {\r
+ module.exports = {"main":"./lib/sprintf"}\r
+});\r
+\r
+require.define("/node_modules/sprintf/lib/sprintf.js", function (require, module, exports, __dirname, __filename) {\r
+ /**\r
+sprintf() for JavaScript 0.7-beta1\r
+http://www.diveintojavascript.com/projects/javascript-sprintf\r
+\r
+Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>\r
+All rights reserved.\r
+\r
+Redistribution and use in source and binary forms, with or without\r
+modification, are permitted provided that the following conditions are met:\r
+ * Redistributions of source code must retain the above copyright\r
+ notice, this list of conditions and the following disclaimer.\r
+ * Redistributions in binary form must reproduce the above copyright\r
+ notice, this list of conditions and the following disclaimer in the\r
+ documentation and/or other materials provided with the distribution.\r
+ * Neither the name of sprintf() for JavaScript nor the\r
+ names of its contributors may be used to endorse or promote products\r
+ derived from this software without specific prior written permission.\r
+\r
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND\r
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r
+DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY\r
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+\r
+Changelog:\r
+2010.11.07 - 0.7-beta1-node\r
+ - converted it to a node.js compatible module\r
+\r
+2010.09.06 - 0.7-beta1\r
+ - features: vsprintf, support for named placeholders\r
+ - enhancements: format cache, reduced global namespace pollution\r
+\r
+2010.05.22 - 0.6:\r
+ - reverted to 0.4 and fixed the bug regarding the sign of the number 0\r
+ Note:\r
+ Thanks to Raphael Pigulla <raph (at] n3rd [dot) org> (http://www.n3rd.org/)\r
+ who warned me about a bug in 0.5, I discovered that the last update was\r
+ a regress. I appologize for that.\r
+\r
+2010.05.09 - 0.5:\r
+ - bug fix: 0 is now preceeded with a + sign\r
+ - bug fix: the sign was not at the right position on padded results (Kamal Abdali)\r
+ - switched from GPL to BSD license\r
+\r
+2007.10.21 - 0.4:\r
+ - unit test and patch (David Baird)\r
+\r
+2007.09.17 - 0.3:\r
+ - bug fix: no longer throws exception on empty paramenters (Hans Pufal)\r
+\r
+2007.09.11 - 0.2:\r
+ - feature: added argument swapping\r
+\r
+2007.04.03 - 0.1:\r
+ - initial release\r
+**/\r
+\r
+var sprintf = (function() {\r
+ function get_type(variable) {\r
+ return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();\r
+ }\r
+ function str_repeat(input, multiplier) {\r
+ for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}\r
+ return output.join('');\r
+ }\r
+\r
+ var str_format = function() {\r
+ if (!str_format.cache.hasOwnProperty(arguments[0])) {\r
+ str_format.cache[arguments[0]] = str_format.parse(arguments[0]);\r
+ }\r
+ return str_format.format.call(null, str_format.cache[arguments[0]], arguments);\r
+ };\r
+\r
+ str_format.format = function(parse_tree, argv) {\r
+ var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;\r
+ for (i = 0; i < tree_length; i++) {\r
+ node_type = get_type(parse_tree[i]);\r
+ if (node_type === 'string') {\r
+ output.push(parse_tree[i]);\r
+ }\r
+ else if (node_type === 'array') {\r
+ match = parse_tree[i]; // convenience purposes only\r
+ if (match[2]) { // keyword argument\r
+ arg = argv[cursor];\r
+ for (k = 0; k < match[2].length; k++) {\r
+ if (!arg.hasOwnProperty(match[2][k])) {\r
+ throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));\r
+ }\r
+ arg = arg[match[2][k]];\r
+ }\r
+ }\r
+ else if (match[1]) { // positional argument (explicit)\r
+ arg = argv[match[1]];\r
+ }\r
+ else { // positional argument (implicit)\r
+ arg = argv[cursor++];\r
+ }\r
+\r
+ if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {\r
+ throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));\r
+ }\r
+ switch (match[8]) {\r
+ case 'b': arg = arg.toString(2); break;\r
+ case 'c': arg = String.fromCharCode(arg); break;\r
+ case 'd': arg = parseInt(arg, 10); break;\r
+ case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;\r
+ case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;\r
+ case 'o': arg = arg.toString(8); break;\r
+ case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;\r
+ case 'u': arg = Math.abs(arg); break;\r
+ case 'x': arg = arg.toString(16); break;\r
+ case 'X': arg = arg.toString(16).toUpperCase(); break;\r
+ }\r
+ arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);\r
+ pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';\r
+ pad_length = match[6] - String(arg).length;\r
+ pad = match[6] ? str_repeat(pad_character, pad_length) : '';\r
+ output.push(match[5] ? arg + pad : pad + arg);\r
+ }\r
+ }\r
+ return output.join('');\r
+ };\r
+\r
+ str_format.cache = {};\r
+\r
+ str_format.parse = function(fmt) {\r
+ var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;\r
+ while (_fmt) {\r
+ if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {\r
+ parse_tree.push(match[0]);\r
+ }\r
+ else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {\r
+ parse_tree.push('%');\r
+ }\r
+ else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {\r
+ if (match[2]) {\r
+ arg_names |= 1;\r
+ var field_list = [], replacement_field = match[2], field_match = [];\r
+ if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {\r
+ field_list.push(field_match[1]);\r
+ while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {\r
+ if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {\r
+ field_list.push(field_match[1]);\r
+ }\r
+ else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {\r
+ field_list.push(field_match[1]);\r
+ }\r
+ else {\r
+ throw('[sprintf] huh?');\r
+ }\r
+ }\r
+ }\r
+ else {\r
+ throw('[sprintf] huh?');\r
+ }\r
+ match[2] = field_list;\r
+ }\r
+ else {\r
+ arg_names |= 2;\r
+ }\r
+ if (arg_names === 3) {\r
+ throw('[sprintf] mixing positional and named placeholders is not (yet) supported');\r
+ }\r
+ parse_tree.push(match);\r
+ }\r
+ else {\r
+ throw('[sprintf] huh?');\r
+ }\r
+ _fmt = _fmt.substring(match[0].length);\r
+ }\r
+ return parse_tree;\r
+ };\r
+\r
+ return str_format;\r
+})();\r
+\r
+var vsprintf = function(fmt, argv) {\r
+ argv.unshift(fmt);\r
+ return sprintf.apply(null, argv);\r
+};\r
+\r
+exports.sprintf = sprintf;\r
+exports.vsprintf = vsprintf;\r
+});\r
+\r
+require.define("/shred/response.js", function (require, module, exports, __dirname, __filename) {\r
+ // The `Response object` encapsulates a Node.js HTTP response.\r
+\r
+var Content = require("./content")\r
+ , HeaderMixins = require("./mixins/headers")\r
+ , CookieJarLib = require( "cookiejar" )\r
+ , Cookie = CookieJarLib.Cookie\r
+;\r
+\r
+// Browser doesn't have zlib.\r
+var zlib = null;\r
+try {\r
+ zlib = require('zlib');\r
+} catch (e) {\r
+ // console.warn("no zlib library");\r
+}\r
+\r
+// Iconv doesn't work in browser\r
+var Iconv = null;\r
+try {\r
+ Iconv = require('iconv-lite');\r
+} catch (e) {\r
+ // console.warn("no iconv library");\r
+}\r
+\r
+// Construct a `Response` object. You should never have to do this directly. The\r
+// `Request` object handles this, getting the raw response object and passing it\r
+// in here, along with the request. The callback allows us to stream the response\r
+// and then use the callback to let the request know when it's ready.\r
+var Response = function(raw, request, callback) { \r
+ var response = this;\r
+ this._raw = raw;\r
+\r
+ // The `._setHeaders` method is "private"; you can't otherwise set headers on\r
+ // the response.\r
+ this._setHeaders.call(this,raw.headers);\r
+ \r
+ // store any cookies\r
+ if (request.cookieJar && this.getHeader('set-cookie')) {\r
+ var cookieStrings = this.getHeader('set-cookie');\r
+ var cookieObjs = []\r
+ , cookie;\r
+\r
+ for (var i = 0; i < cookieStrings.length; i++) {\r
+ var cookieString = cookieStrings[i];\r
+ if (!cookieString) {\r
+ continue;\r
+ }\r
+\r
+ if (!cookieString.match(/domain\=/i)) {\r
+ cookieString += '; domain=' + request.host;\r
+ }\r
+\r
+ if (!cookieString.match(/path\=/i)) {\r
+ cookieString += '; path=' + request.path;\r
+ }\r
+\r
+ try {\r
+ cookie = new Cookie(cookieString);\r
+ if (cookie) {\r
+ cookieObjs.push(cookie);\r
+ }\r
+ } catch (e) {\r
+ console.warn("Tried to set bad cookie: " + cookieString);\r
+ }\r
+ }\r
+\r
+ request.cookieJar.setCookies(cookieObjs);\r
+ }\r
+\r
+ this.request = request;\r
+ this.client = request.client;\r
+ this.log = this.request.log;\r
+\r
+ // Stream the response content entity and fire the callback when we're done.\r
+ // Store the incoming data in a array of Buffers which we concatinate into one\r
+ // buffer at the end. We need to use buffers instead of strings here in order\r
+ // to preserve binary data.\r
+ var chunkBuffers = [];\r
+ var dataLength = 0;\r
+ raw.on("data", function(chunk) {\r
+ chunkBuffers.push(chunk);\r
+ dataLength += chunk.length;\r
+ });\r
+ raw.on("end", function() {\r
+ var body;\r
+ if (typeof Buffer === 'undefined') {\r
+ // Just concatinate into a string\r
+ body = chunkBuffers.join('');\r
+ } else {\r
+ // Initialize new buffer and add the chunks one-at-a-time.\r
+ body = new Buffer(dataLength);\r
+ for (var i = 0, pos = 0; i < chunkBuffers.length; i++) {\r
+ chunkBuffers[i].copy(body, pos);\r
+ pos += chunkBuffers[i].length;\r
+ }\r
+ }\r
+\r
+ var setBodyAndFinish = function (body) {\r
+ response._body = new Content({ \r
+ body: body,\r
+ type: response.getHeader("Content-Type")\r
+ });\r
+ callback(response);\r
+ }\r
+\r
+ if (zlib && response.getHeader("Content-Encoding") === 'gzip'){\r
+ zlib.gunzip(body, function (err, gunzippedBody) {\r
+ if (Iconv && response.request.encoding){\r
+ body = Iconv.fromEncoding(gunzippedBody,response.request.encoding);\r
+ } else {\r
+ body = gunzippedBody.toString();\r
+ }\r
+ setBodyAndFinish(body);\r
+ })\r
+ }\r
+ else{\r
+ if (response.request.encoding){\r
+ body = Iconv.fromEncoding(body,response.request.encoding);\r
+ } \r
+ setBodyAndFinish(body);\r
+ }\r
+ });\r
+};\r
+\r
+// The `Response` object can be pretty overwhelming to view using the built-in\r
+// Node.js inspect method. We want to make it a bit more manageable. This\r
+// probably goes [too far in the other\r
+// direction](https://github.com/spire-io/shred/issues/2).\r
+\r
+Response.prototype = {\r
+ inspect: function() {\r
+ var response = this;\r
+ var headers = this.format_headers();\r
+ var summary = ["<Shred Response> ", response.status].join(" ")\r
+ return [ summary, "- Headers:", headers].join("\n");\r
+ },\r
+ format_headers: function () {\r
+ var array = []\r
+ var headers = this._headers\r
+ for (var key in headers) {\r
+ if (headers.hasOwnProperty(key)) {\r
+ var value = headers[key]\r
+ array.push("\t" + key + ": " + value);\r
+ }\r
+ }\r
+ return array.join("\n");\r
+ }\r
+};\r
+\r
+// `Response` object properties, all of which are read-only:\r
+Object.defineProperties(Response.prototype, {\r
+ \r
+// - **status**. The HTTP status code for the response. \r
+ status: {\r
+ get: function() { return this._raw.statusCode; },\r
+ enumerable: true\r
+ },\r
+\r
+// - **content**. The HTTP content entity, if any. Provided as a [content\r
+// object](./content.html), which will attempt to convert the entity based upon\r
+// the `content-type` header. The converted value is available as\r
+// `content.data`. The original raw content entity is available as\r
+// `content.body`.\r
+ body: {\r
+ get: function() { return this._body; }\r
+ },\r
+ content: {\r
+ get: function() { return this.body; },\r
+ enumerable: true\r
+ },\r
+\r
+// - **isRedirect**. Is the response a redirect? These are responses with 3xx\r
+// status and a `Location` header.\r
+ isRedirect: {\r
+ get: function() {\r
+ return (this.status>299\r
+ &&this.status<400\r
+ &&this.getHeader("Location"));\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **isError**. Is the response an error? These are responses with status of\r
+// 400 or greater.\r
+ isError: {\r
+ get: function() {\r
+ return (this.status === 0 || this.status > 399)\r
+ },\r
+ enumerable: true\r
+ }\r
+});\r
+\r
+// Add in the [getters for accessing the normalized headers](./headers.js).\r
+HeaderMixins.getters(Response);\r
+HeaderMixins.privateSetters(Response);\r
+\r
+// Work around Mozilla bug #608735 [https://bugzil.la/608735], which causes\r
+// getAllResponseHeaders() to return {} if the response is a CORS request.\r
+// xhr.getHeader still works correctly.\r
+var getHeader = Response.prototype.getHeader;\r
+Response.prototype.getHeader = function (name) {\r
+ return (getHeader.call(this,name) ||\r
+ (typeof this._raw.getHeader === 'function' && this._raw.getHeader(name)));\r
+};\r
+\r
+module.exports = Response;\r
+\r
+});\r
+\r
+require.define("/shred/content.js", function (require, module, exports, __dirname, __filename) {\r
+ \r
+// The purpose of the `Content` object is to abstract away the data conversions\r
+// to and from raw content entities as strings. For example, you want to be able\r
+// to pass in a Javascript object and have it be automatically converted into a\r
+// JSON string if the `content-type` is set to a JSON-based media type.\r
+// Conversely, you want to be able to transparently get back a Javascript object\r
+// in the response if the `content-type` is a JSON-based media-type.\r
+\r
+// One limitation of the current implementation is that it [assumes the `charset` is UTF-8](https://github.com/spire-io/shred/issues/5).\r
+\r
+// The `Content` constructor takes an options object, which *must* have either a\r
+// `body` or `data` property and *may* have a `type` property indicating the\r
+// media type. If there is no `type` attribute, a default will be inferred.\r
+var Content = function(options) {\r
+ this.body = options.body;\r
+ this.data = options.data;\r
+ this.type = options.type;\r
+};\r
+\r
+Content.prototype = {\r
+ // Treat `toString()` as asking for the `content.body`. That is, the raw content entity.\r
+ //\r
+ // toString: function() { return this.body; }\r
+ //\r
+ // Commented out, but I've forgotten why. :/\r
+};\r
+\r
+\r
+// `Content` objects have the following attributes:\r
+Object.defineProperties(Content.prototype,{\r
+ \r
+// - **type**. Typically accessed as `content.type`, reflects the `content-type`\r
+// header associated with the request or response. If not passed as an options\r
+// to the constructor or set explicitly, it will infer the type the `data`\r
+// attribute, if possible, and, failing that, will default to `text/plain`.\r
+ type: {\r
+ get: function() {\r
+ if (this._type) {\r
+ return this._type;\r
+ } else {\r
+ if (this._data) {\r
+ switch(typeof this._data) {\r
+ case "string": return "text/plain";\r
+ case "object": return "application/json";\r
+ }\r
+ }\r
+ }\r
+ return "text/plain";\r
+ },\r
+ set: function(value) {\r
+ this._type = value;\r
+ return this;\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **data**. Typically accessed as `content.data`, reflects the content entity\r
+// converted into Javascript data. This can be a string, if the `type` is, say,\r
+// `text/plain`, but can also be a Javascript object. The conversion applied is\r
+// based on the `processor` attribute. The `data` attribute can also be set\r
+// directly, in which case the conversion will be done the other way, to infer\r
+// the `body` attribute.\r
+ data: {\r
+ get: function() {\r
+ if (this._body) {\r
+ return this.processor.parser(this._body);\r
+ } else {\r
+ return this._data;\r
+ }\r
+ },\r
+ set: function(data) {\r
+ if (this._body&&data) Errors.setDataWithBody(this);\r
+ this._data = data;\r
+ return this;\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **body**. Typically accessed as `content.body`, reflects the content entity\r
+// as a UTF-8 string. It is the mirror of the `data` attribute. If you set the\r
+// `data` attribute, the `body` attribute will be inferred and vice-versa. If\r
+// you attempt to set both, an exception is raised.\r
+ body: {\r
+ get: function() {\r
+ if (this._data) {\r
+ return this.processor.stringify(this._data);\r
+ } else {\r
+ return this.processor.stringify(this._body);\r
+ }\r
+ },\r
+ set: function(body) {\r
+ if (this._data&&body) Errors.setBodyWithData(this);\r
+ this._body = body;\r
+ return this;\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **processor**. The functions that will be used to convert to/from `data` and\r
+// `body` attributes. You can add processors. The two that are built-in are for\r
+// `text/plain`, which is basically an identity transformation and\r
+// `application/json` and other JSON-based media types (including custom media\r
+// types with `+json`). You can add your own processors. See below.\r
+ processor: {\r
+ get: function() {\r
+ var processor = Content.processors[this.type];\r
+ if (processor) {\r
+ return processor;\r
+ } else {\r
+ // Return the first processor that matches any part of the\r
+ // content type. ex: application/vnd.foobar.baz+json will match json.\r
+ var main = this.type.split(";")[0];\r
+ var parts = main.split(/\+|\//);\r
+ for (var i=0, l=parts.length; i < l; i++) {\r
+ processor = Content.processors[parts[i]]\r
+ }\r
+ return processor || {parser:identity,stringify:toString};\r
+ }\r
+ },\r
+ enumerable: true\r
+ },\r
+\r
+// - **length**. Typically accessed as `content.length`, returns the length in\r
+// bytes of the raw content entity.\r
+ length: {\r
+ get: function() {\r
+ if (typeof Buffer !== 'undefined') {\r
+ return Buffer.byteLength(this.body);\r
+ }\r
+ return this.body.length;\r
+ }\r
+ }\r
+});\r
+\r
+Content.processors = {};\r
+\r
+// The `registerProcessor` function allows you to add your own processors to\r
+// convert content entities. Each processor consists of a Javascript object with\r
+// two properties:\r
+// - **parser**. The function used to parse a raw content entity and convert it\r
+// into a Javascript data type.\r
+// - **stringify**. The function used to convert a Javascript data type into a\r
+// raw content entity.\r
+Content.registerProcessor = function(types,processor) {\r
+ \r
+// You can pass an array of types that will trigger this processor, or just one.\r
+// We determine the array via duck-typing here.\r
+ if (types.forEach) {\r
+ types.forEach(function(type) {\r
+ Content.processors[type] = processor;\r
+ });\r
+ } else {\r
+ // If you didn't pass an array, we just use what you pass in.\r
+ Content.processors[types] = processor;\r
+ }\r
+};\r
+\r
+// Register the identity processor, which is used for text-based media types.\r
+var identity = function(x) { return x; }\r
+ , toString = function(x) { return x.toString(); }\r
+Content.registerProcessor(\r
+ ["text/html","text/plain","text"],\r
+ { parser: identity, stringify: toString });\r
+\r
+// Register the JSON processor, which is used for JSON-based media types.\r
+Content.registerProcessor(\r
+ ["application/json; charset=utf-8","application/json","json"],\r
+ {\r
+ parser: function(string) {\r
+ return JSON.parse(string);\r
+ },\r
+ stringify: function(data) {\r
+ return JSON.stringify(data); }});\r
+\r
+// Error functions are defined separately here in an attempt to make the code\r
+// easier to read.\r
+var Errors = {\r
+ setDataWithBody: function(object) {\r
+ throw new Error("Attempt to set data attribute of a content object " +\r
+ "when the body attributes was already set.");\r
+ },\r
+ setBodyWithData: function(object) {\r
+ throw new Error("Attempt to set body attribute of a content object " +\r
+ "when the data attributes was already set.");\r
+ }\r
+}\r
+module.exports = Content;\r
+\r
+});\r
+\r
+require.define("/shred/mixins/headers.js", function (require, module, exports, __dirname, __filename) {\r
+ // The header mixins allow you to add HTTP header support to any object. This\r
+// might seem pointless: why not simply use a hash? The main reason is that, per\r
+// the [HTTP spec](http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2),\r
+// headers are case-insensitive. So, for example, `content-type` is the same as\r
+// `CONTENT-TYPE` which is the same as `Content-Type`. Since there is no way to\r
+// overload the index operator in Javascript, using a hash to represent the\r
+// headers means it's possible to have two conflicting values for a single\r
+// header.\r
+// \r
+// The solution to this is to provide explicit methods to set or get headers.\r
+// This also has the benefit of allowing us to introduce additional variations,\r
+// including snake case, which we automatically convert to what Matthew King has\r
+// dubbed "corset case" - the hyphen-separated names with initial caps:\r
+// `Content-Type`. We use corset-case just in case we're dealing with servers\r
+// that haven't properly implemented the spec.\r
+\r
+// Convert headers to corset-case. **Example:** `CONTENT-TYPE` will be converted\r
+// to `Content-Type`.\r
+\r
+var corsetCase = function(string) {\r
+ return string;//.toLowerCase()\r
+ //.replace("_","-")\r
+ // .replace(/(^|-)(\w)/g, \r
+ // function(s) { return s.toUpperCase(); });\r
+};\r
+\r
+// We suspect that `initializeHeaders` was once more complicated ...\r
+var initializeHeaders = function(object) {\r
+ return {};\r
+};\r
+\r
+// Access the `_headers` property using lazy initialization. **Warning:** If you\r
+// mix this into an object that is using the `_headers` property already, you're\r
+// going to have trouble.\r
+var $H = function(object) {\r
+ return object._headers||(object._headers=initializeHeaders(object));\r
+};\r
+\r
+// Hide the implementations as private functions, separate from how we expose them.\r
+\r
+// The "real" `getHeader` function: get the header after normalizing the name.\r
+var getHeader = function(object,name) {\r
+ return $H(object)[corsetCase(name)];\r
+};\r
+\r
+// The "real" `getHeader` function: get one or more headers, or all of them\r
+// if you don't ask for any specifics. \r
+var getHeaders = function(object,names) {\r
+ var keys = (names && names.length>0) ? names : Object.keys($H(object));\r
+ var hash = keys.reduce(function(hash,key) {\r
+ hash[key] = getHeader(object,key);\r
+ return hash;\r
+ },{});\r
+ // Freeze the resulting hash so you don't mistakenly think you're modifying\r
+ // the real headers.\r
+ Object.freeze(hash);\r
+ return hash;\r
+};\r
+\r
+// The "real" `setHeader` function: set a header, after normalizing the name.\r
+var setHeader = function(object,name,value) {\r
+ $H(object)[corsetCase(name)] = value;\r
+ return object;\r
+};\r
+\r
+// The "real" `setHeaders` function: set multiple headers based on a hash.\r
+var setHeaders = function(object,hash) {\r
+ for( var key in hash ) { setHeader(object,key,hash[key]); };\r
+ return this;\r
+};\r
+\r
+// Here's where we actually bind the functionality to an object. These mixins work by\r
+// exposing mixin functions. Each function mixes in a specific batch of features.\r
+module.exports = {\r
+ \r
+ // Add getters.\r
+ getters: function(constructor) {\r
+ constructor.prototype.getHeader = function(name) { return getHeader(this,name); };\r
+ constructor.prototype.getHeaders = function() { return getHeaders(this,arguments); };\r
+ },\r
+ // Add setters but as "private" methods.\r
+ privateSetters: function(constructor) {\r
+ constructor.prototype._setHeader = function(key,value) { return setHeader(this,key,value); };\r
+ constructor.prototype._setHeaders = function(hash) { return setHeaders(this,hash); };\r
+ },\r
+ // Add setters.\r
+ setters: function(constructor) {\r
+ constructor.prototype.setHeader = function(key,value) { return setHeader(this,key,value); };\r
+ constructor.prototype.setHeaders = function(hash) { return setHeaders(this,hash); };\r
+ },\r
+ // Add both getters and setters.\r
+ gettersAndSetters: function(constructor) {\r
+ constructor.prototype.getHeader = function(name) { return getHeader(this,name); };\r
+ constructor.prototype.getHeaders = function() { return getHeaders(this,arguments); };\r
+ constructor.prototype.setHeader = function(key,value) { return setHeader(this,key,value); };\r
+ constructor.prototype.setHeaders = function(hash) { return setHeaders(this,hash); };\r
+ }\r
+};\r
+\r
+});\r
+\r
+require.define("/node_modules/iconv-lite/package.json", function (require, module, exports, __dirname, __filename) {\r
+ module.exports = {}\r
+});\r
+\r
+require.define("/node_modules/iconv-lite/index.js", function (require, module, exports, __dirname, __filename) {\r
+ // Module exports\r
+var iconv = module.exports = {\r
+ toEncoding: function(str, encoding) {\r
+ return iconv.getCodec(encoding).toEncoding(str);\r
+ },\r
+ fromEncoding: function(buf, encoding) {\r
+ return iconv.getCodec(encoding).fromEncoding(buf);\r
+ },\r
+ \r
+ defaultCharUnicode: '�',\r
+ defaultCharSingleByte: '?',\r
+ \r
+ // Get correct codec for given encoding.\r
+ getCodec: function(encoding) {\r
+ var enc = encoding || "utf8";\r
+ var codecOptions = undefined;\r
+ while (1) {\r
+ if (getType(enc) === "String")\r
+ enc = enc.replace(/[- ]/g, "").toLowerCase();\r
+ var codec = iconv.encodings[enc];\r
+ var type = getType(codec);\r
+ if (type === "String") {\r
+ // Link to other encoding.\r
+ codecOptions = {originalEncoding: enc};\r
+ enc = codec;\r
+ }\r
+ else if (type === "Object" && codec.type != undefined) {\r
+ // Options for other encoding.\r
+ codecOptions = codec;\r
+ enc = codec.type;\r
+ } \r
+ else if (type === "Function")\r
+ // Codec itself.\r
+ return codec(codecOptions);\r
+ else\r
+ throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");\r
+ }\r
+ },\r
+ \r
+ // Define basic encodings\r
+ encodings: {\r
+ internal: function(options) {\r
+ return {\r
+ toEncoding: function(str) {\r
+ return new Buffer(ensureString(str), options.originalEncoding);\r
+ },\r
+ fromEncoding: function(buf) {\r
+ return ensureBuffer(buf).toString(options.originalEncoding);\r
+ }\r
+ };\r
+ },\r
+ utf8: "internal",\r
+ ucs2: "internal",\r
+ binary: "internal",\r
+ ascii: "internal",\r
+ base64: "internal",\r
+ \r
+ // Codepage single-byte encodings.\r
+ singlebyte: function(options) {\r
+ // Prepare chars if needed\r
+ if (!options.chars || (options.chars.length !== 128 && options.chars.length !== 256))\r
+ throw new Error("Encoding '"+options.type+"' has incorrect 'chars' (must be of len 128 or 256)");\r
+ \r
+ if (options.chars.length === 128)\r
+ options.chars = asciiString + options.chars;\r
+ \r
+ if (!options.charsBuf) {\r
+ options.charsBuf = new Buffer(options.chars, 'ucs2');\r
+ }\r
+ \r
+ if (!options.revCharsBuf) {\r
+ options.revCharsBuf = new Buffer(65536);\r
+ var defChar = iconv.defaultCharSingleByte.charCodeAt(0);\r
+ for (var i = 0; i < options.revCharsBuf.length; i++)\r
+ options.revCharsBuf[i] = defChar;\r
+ for (var i = 0; i < options.chars.length; i++)\r
+ options.revCharsBuf[options.chars.charCodeAt(i)] = i;\r
+ }\r
+ \r
+ return {\r
+ toEncoding: function(str) {\r
+ str = ensureString(str);\r
+ \r
+ var buf = new Buffer(str.length);\r
+ var revCharsBuf = options.revCharsBuf;\r
+ for (var i = 0; i < str.length; i++)\r
+ buf[i] = revCharsBuf[str.charCodeAt(i)];\r
+ \r
+ return buf;\r
+ },\r
+ fromEncoding: function(buf) {\r
+ buf = ensureBuffer(buf);\r
+ \r
+ // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.\r
+ var charsBuf = options.charsBuf;\r
+ var newBuf = new Buffer(buf.length*2);\r
+ var idx1 = 0, idx2 = 0;\r
+ for (var i = 0, _len = buf.length; i < _len; i++) {\r
+ idx1 = buf[i]*2; idx2 = i*2;\r
+ newBuf[idx2] = charsBuf[idx1];\r
+ newBuf[idx2+1] = charsBuf[idx1+1];\r
+ }\r
+ return newBuf.toString('ucs2');\r
+ }\r
+ };\r
+ },\r
+\r
+ // Codepage double-byte encodings.\r
+ table: function(options) {\r
+ var table = options.table, key, revCharsTable = options.revCharsTable;\r
+ if (!table) {\r
+ throw new Error("Encoding '" + options.type +"' has incorect 'table' option");\r
+ }\r
+ if(!revCharsTable) {\r
+ revCharsTable = options.revCharsTable = {};\r
+ for (key in table) {\r
+ revCharsTable[table[key]] = parseInt(key);\r
+ }\r
+ }\r
+ \r
+ return {\r
+ toEncoding: function(str) {\r
+ str = ensureString(str);\r
+ var strLen = str.length;\r
+ var bufLen = strLen;\r
+ for (var i = 0; i < strLen; i++)\r
+ if (str.charCodeAt(i) >> 7)\r
+ bufLen++;\r
+\r
+ var newBuf = new Buffer(bufLen), gbkcode, unicode, \r
+ defaultChar = revCharsTable[iconv.defaultCharUnicode.charCodeAt(0)];\r
+\r
+ for (var i = 0, j = 0; i < strLen; i++) {\r
+ unicode = str.charCodeAt(i);\r
+ if (unicode >> 7) {\r
+ gbkcode = revCharsTable[unicode] || defaultChar;\r
+ newBuf[j++] = gbkcode >> 8; //high byte;\r
+ newBuf[j++] = gbkcode & 0xFF; //low byte\r
+ } else {//ascii\r
+ newBuf[j++] = unicode;\r
+ }\r
+ }\r
+ return newBuf;\r
+ },\r
+ fromEncoding: function(buf) {\r
+ buf = ensureBuffer(buf);\r
+ var bufLen = buf.length, strLen = 0;\r
+ for (var i = 0; i < bufLen; i++) {\r
+ strLen++;\r
+ if (buf[i] & 0x80) //the high bit is 1, so this byte is gbkcode's high byte.skip next byte\r
+ i++;\r
+ }\r
+ var newBuf = new Buffer(strLen*2), unicode, gbkcode,\r
+ defaultChar = iconv.defaultCharUnicode.charCodeAt(0);\r
+ \r
+ for (var i = 0, j = 0; i < bufLen; i++, j+=2) {\r
+ gbkcode = buf[i];\r
+ if (gbkcode & 0x80) {\r
+ gbkcode = (gbkcode << 8) + buf[++i];\r
+ unicode = table[gbkcode] || defaultChar;\r
+ } else {\r
+ unicode = gbkcode;\r
+ }\r
+ newBuf[j] = unicode & 0xFF; //low byte\r
+ newBuf[j+1] = unicode >> 8; //high byte\r
+ }\r
+ return newBuf.toString('ucs2');\r
+ }\r
+ }\r
+ }\r
+ }\r
+};\r
+\r
+// Add aliases to convert functions\r
+iconv.encode = iconv.toEncoding;\r
+iconv.decode = iconv.fromEncoding;\r
+\r
+// Load other encodings from files in /encodings dir.\r
+var encodingsDir = __dirname+"/encodings/",\r
+ fs = require('fs');\r
+fs.readdirSync(encodingsDir).forEach(function(file) {\r
+ if(fs.statSync(encodingsDir + file).isDirectory()) return;\r
+ var encodings = require(encodingsDir + file)\r
+ for (var key in encodings)\r
+ iconv.encodings[key] = encodings[key]\r
+});\r
+\r
+// Utilities\r
+var asciiString = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'+\r
+ ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f';\r
+\r
+var ensureBuffer = function(buf) {\r
+ buf = buf || new Buffer(0);\r
+ return (buf instanceof Buffer) ? buf : new Buffer(buf.toString(), "utf8");\r
+}\r
+\r
+var ensureString = function(str) {\r
+ str = str || "";\r
+ return (str instanceof String) ? str : str.toString((str instanceof Buffer) ? 'utf8' : undefined);\r
+}\r
+\r
+var getType = function(obj) {\r
+ return Object.prototype.toString.call(obj).slice(8, -1);\r
+}\r
+\r
+\r
+});\r
+\r
+require.define("/node_modules/http-browserify/package.json", function (require, module, exports, __dirname, __filename) {\r
+ module.exports = {"main":"index.js","browserify":"browser.js"}\r
+});\r
+\r
+require.define("/node_modules/http-browserify/browser.js", function (require, module, exports, __dirname, __filename) {\r
+ var http = module.exports;\r
+var EventEmitter = require('events').EventEmitter;\r
+var Request = require('./lib/request');\r
+\r
+http.request = function (params, cb) {\r
+ if (!params) params = {};\r
+ if (!params.host) params.host = window.location.host.split(':')[0];\r
+ if (!params.port) params.port = window.location.port;\r
+ \r
+ var req = new Request(new xhrHttp, params);\r
+ if (cb) req.on('response', cb);\r
+ return req;\r
+};\r
+\r
+http.get = function (params, cb) {\r
+ params.method = 'GET';\r
+ var req = http.request(params, cb);\r
+ req.end();\r
+ return req;\r
+};\r
+\r
+var xhrHttp = (function () {\r
+ if (typeof window === 'undefined') {\r
+ throw new Error('no window object present');\r
+ }\r
+ else if (window.XMLHttpRequest) {\r
+ return window.XMLHttpRequest;\r
+ }\r
+ else if (window.ActiveXObject) {\r
+ var axs = [\r
+ 'Msxml2.XMLHTTP.6.0',\r
+ 'Msxml2.XMLHTTP.3.0',\r
+ 'Microsoft.XMLHTTP'\r
+ ];\r
+ for (var i = 0; i < axs.length; i++) {\r
+ try {\r
+ var ax = new(window.ActiveXObject)(axs[i]);\r
+ return function () {\r
+ if (ax) {\r
+ var ax_ = ax;\r
+ ax = null;\r
+ return ax_;\r
+ }\r
+ else {\r
+ return new(window.ActiveXObject)(axs[i]);\r
+ }\r
+ };\r
+ }\r
+ catch (e) {}\r
+ }\r
+ throw new Error('ajax not supported in this browser')\r
+ }\r
+ else {\r
+ throw new Error('ajax not supported in this browser');\r
+ }\r
+})();\r
+\r
+http.STATUS_CODES = {\r
+ 100 : 'Continue',\r
+ 101 : 'Switching Protocols',\r
+ 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918\r
+ 200 : 'OK',\r
+ 201 : 'Created',\r
+ 202 : 'Accepted',\r
+ 203 : 'Non-Authoritative Information',\r
+ 204 : 'No Content',\r
+ 205 : 'Reset Content',\r
+ 206 : 'Partial Content',\r
+ 207 : 'Multi-Status', // RFC 4918\r
+ 300 : 'Multiple Choices',\r
+ 301 : 'Moved Permanently',\r
+ 302 : 'Moved Temporarily',\r
+ 303 : 'See Other',\r
+ 304 : 'Not Modified',\r
+ 305 : 'Use Proxy',\r
+ 307 : 'Temporary Redirect',\r
+ 400 : 'Bad Request',\r
+ 401 : 'Unauthorized',\r
+ 402 : 'Payment Required',\r
+ 403 : 'Forbidden',\r
+ 404 : 'Not Found',\r
+ 405 : 'Method Not Allowed',\r
+ 406 : 'Not Acceptable',\r
+ 407 : 'Proxy Authentication Required',\r
+ 408 : 'Request Time-out',\r
+ 409 : 'Conflict',\r
+ 410 : 'Gone',\r
+ 411 : 'Length Required',\r
+ 412 : 'Precondition Failed',\r
+ 413 : 'Request Entity Too Large',\r
+ 414 : 'Request-URI Too Large',\r
+ 415 : 'Unsupported Media Type',\r
+ 416 : 'Requested Range Not Satisfiable',\r
+ 417 : 'Expectation Failed',\r
+ 418 : 'I\'m a teapot', // RFC 2324\r
+ 422 : 'Unprocessable Entity', // RFC 4918\r
+ 423 : 'Locked', // RFC 4918\r
+ 424 : 'Failed Dependency', // RFC 4918\r
+ 425 : 'Unordered Collection', // RFC 4918\r
+ 426 : 'Upgrade Required', // RFC 2817\r
+ 500 : 'Internal Server Error',\r
+ 501 : 'Not Implemented',\r
+ 502 : 'Bad Gateway',\r
+ 503 : 'Service Unavailable',\r
+ 504 : 'Gateway Time-out',\r
+ 505 : 'HTTP Version not supported',\r
+ 506 : 'Variant Also Negotiates', // RFC 2295\r
+ 507 : 'Insufficient Storage', // RFC 4918\r
+ 509 : 'Bandwidth Limit Exceeded',\r
+ 510 : 'Not Extended' // RFC 2774\r
+};\r
+\r
+});\r
+\r
+require.define("/node_modules/http-browserify/lib/request.js", function (require, module, exports, __dirname, __filename) {\r
+ var EventEmitter = require('events').EventEmitter;\r
+var Response = require('./response');\r
+var isSafeHeader = require('./isSafeHeader');\r
+\r
+var Request = module.exports = function (xhr, params) {\r
+ var self = this;\r
+ self.xhr = xhr;\r
+ self.body = '';\r
+ \r
+ var uri = params.host + ':' + params.port + (params.path || '/');\r
+ \r
+ xhr.open(\r
+ params.method || 'GET',\r
+ (params.scheme || 'http') + '://' + uri,\r
+ true\r
+ );\r
+ \r
+ if (params.headers) {\r
+ Object.keys(params.headers).forEach(function (key) {\r
+ if (!isSafeHeader(key)) return;\r
+ var value = params.headers[key];\r
+ if (Array.isArray(value)) {\r
+ value.forEach(function (v) {\r
+ xhr.setRequestHeader(key, v);\r
+ });\r
+ }\r
+ else xhr.setRequestHeader(key, value)\r
+ });\r
+ }\r
+ \r
+ var res = new Response(xhr);\r
+ res.on('ready', function () {\r
+ self.emit('response', res);\r
+ });\r
+ \r
+ xhr.onreadystatechange = function () {\r
+ res.handle(xhr);\r
+ };\r
+};\r
+\r
+Request.prototype = new EventEmitter;\r
+\r
+Request.prototype.setHeader = function (key, value) {\r
+ if ((Array.isArray && Array.isArray(value))\r
+ || value instanceof Array) {\r
+ for (var i = 0; i < value.length; i++) {\r
+ this.xhr.setRequestHeader(key, value[i]);\r
+ }\r
+ }\r
+ else {\r
+ this.xhr.setRequestHeader(key, value);\r
+ }\r
+};\r
+\r
+Request.prototype.write = function (s) {\r
+ this.body += s;\r
+};\r
+\r
+Request.prototype.end = function (s) {\r
+ if (s !== undefined) this.write(s);\r
+ this.xhr.send(this.body);\r
+};\r
+\r
+});\r
+\r
+require.define("/node_modules/http-browserify/lib/response.js", function (require, module, exports, __dirname, __filename) {\r
+ var EventEmitter = require('events').EventEmitter;\r
+var isSafeHeader = require('./isSafeHeader');\r
+\r
+var Response = module.exports = function (xhr) {\r
+ this.xhr = xhr;\r
+ this.offset = 0;\r
+};\r
+\r
+Response.prototype = new EventEmitter;\r
+\r
+var capable = {\r
+ streaming : true,\r
+ status2 : true\r
+};\r
+\r
+function parseHeaders (xhr) {\r
+ var lines = xhr.getAllResponseHeaders().split(/\r?\n/);\r
+ var headers = {};\r
+ for (var i = 0; i < lines.length; i++) {\r
+ var line = lines[i];\r
+ if (line === '') continue;\r
+ \r
+ var m = line.match(/^([^:]+):\s*(.*)/);\r
+ if (m) {\r
+ var key = m[1].toLowerCase(), value = m[2];\r
+ \r
+ if (headers[key] !== undefined) {\r
+ if ((Array.isArray && Array.isArray(headers[key]))\r
+ || headers[key] instanceof Array) {\r
+ headers[key].push(value);\r
+ }\r
+ else {\r
+ headers[key] = [ headers[key], value ];\r
+ }\r
+ }\r
+ else {\r
+ headers[key] = value;\r
+ }\r
+ }\r
+ else {\r
+ headers[line] = true;\r
+ }\r
+ }\r
+ return headers;\r
+}\r
+\r
+Response.prototype.getHeader = function (key) {\r
+ var header = this.headers ? this.headers[key.toLowerCase()] : null;\r
+ if (header) return header;\r
+\r
+ // Work around Mozilla bug #608735 [https://bugzil.la/608735], which causes\r
+ // getAllResponseHeaders() to return {} if the response is a CORS request.\r
+ // xhr.getHeader still works correctly.\r
+ if (isSafeHeader(key)) {\r
+ return this.xhr.getResponseHeader(key);\r
+ }\r
+ return null;\r
+};\r
+\r
+Response.prototype.handle = function () {\r
+ var xhr = this.xhr;\r
+ if (xhr.readyState === 2 && capable.status2) {\r
+ try {\r
+ this.statusCode = xhr.status;\r
+ this.headers = parseHeaders(xhr);\r
+ }\r
+ catch (err) {\r
+ capable.status2 = false;\r
+ }\r
+ \r
+ if (capable.status2) {\r
+ this.emit('ready');\r
+ }\r
+ }\r
+ else if (capable.streaming && xhr.readyState === 3) {\r
+ try {\r
+ if (!this.statusCode) {\r
+ this.statusCode = xhr.status;\r
+ this.headers = parseHeaders(xhr);\r
+ this.emit('ready');\r
+ }\r
+ }\r
+ catch (err) {}\r
+ \r
+ try {\r
+ this.write();\r
+ }\r
+ catch (err) {\r
+ capable.streaming = false;\r
+ }\r
+ }\r
+ else if (xhr.readyState === 4) {\r
+ if (!this.statusCode) {\r
+ this.statusCode = xhr.status;\r
+ this.emit('ready');\r
+ }\r
+ this.write();\r
+ \r
+ if (xhr.error) {\r
+ this.emit('error', xhr.responseText);\r
+ }\r
+ else this.emit('end');\r
+ }\r
+};\r
+\r
+Response.prototype.write = function () {\r
+ var xhr = this.xhr;\r
+ if (xhr.responseText.length > this.offset) {\r
+ this.emit('data', xhr.responseText.slice(this.offset));\r
+ this.offset = xhr.responseText.length;\r
+ }\r
+};\r
+\r
+});\r
+\r
+require.define("/node_modules/http-browserify/lib/isSafeHeader.js", function (require, module, exports, __dirname, __filename) {\r
+ // Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html\r
+var unsafeHeaders = [\r
+ "accept-charset",\r
+ "accept-encoding",\r
+ "access-control-request-headers",\r
+ "access-control-request-method",\r
+ "connection",\r
+ "content-length",\r
+ "cookie",\r
+ "cookie2",\r
+ "content-transfer-encoding",\r
+ "date",\r
+ "expect",\r
+ "host",\r
+ "keep-alive",\r
+ "origin",\r
+ "referer",\r
+ "set-cookie",\r
+ "te",\r
+ "trailer",\r
+ "transfer-encoding",\r
+ "upgrade",\r
+ "user-agent",\r
+ "via"\r
+];\r
+\r
+module.exports = function (headerName) {\r
+ if (!headerName) return false;\r
+ return (unsafeHeaders.indexOf(headerName.toLowerCase()) === -1)\r
+};\r
+\r
+});\r
+\r
+require.alias("http-browserify", "/node_modules/http");\r
+\r
+require.alias("http-browserify", "/node_modules/https");
\ No newline at end of file