Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

2765 rindas
86 KiB

  1. var require = function (file, cwd) {
  2. var resolved = require.resolve(file, cwd || '/');
  3. var mod = require.modules[resolved];
  4. if (!mod) throw new Error(
  5. 'Failed to resolve module ' + file + ', tried ' + resolved
  6. );
  7. var res = mod._cached ? mod._cached : mod();
  8. return res;
  9. }
  10. require.paths = [];
  11. require.modules = {};
  12. require.extensions = [".js",".coffee"];
  13. require._core = {
  14. 'assert': true,
  15. 'events': true,
  16. 'fs': true,
  17. 'path': true,
  18. 'vm': true
  19. };
  20. require.resolve = (function () {
  21. return function (x, cwd) {
  22. if (!cwd) cwd = '/';
  23. if (require._core[x]) return x;
  24. var path = require.modules.path();
  25. var y = cwd || '.';
  26. if (x.match(/^(?:\.\.?\/|\/)/)) {
  27. var m = loadAsFileSync(path.resolve(y, x))
  28. || loadAsDirectorySync(path.resolve(y, x));
  29. if (m) return m;
  30. }
  31. var n = loadNodeModulesSync(x, y);
  32. if (n) return n;
  33. throw new Error("Cannot find module '" + x + "'");
  34. function loadAsFileSync (x) {
  35. if (require.modules[x]) {
  36. return x;
  37. }
  38. for (var i = 0; i < require.extensions.length; i++) {
  39. var ext = require.extensions[i];
  40. if (require.modules[x + ext]) return x + ext;
  41. }
  42. }
  43. function loadAsDirectorySync (x) {
  44. x = x.replace(/\/+$/, '');
  45. var pkgfile = x + '/package.json';
  46. if (require.modules[pkgfile]) {
  47. var pkg = require.modules[pkgfile]();
  48. var b = pkg.browserify;
  49. if (typeof b === 'object' && b.main) {
  50. var m = loadAsFileSync(path.resolve(x, b.main));
  51. if (m) return m;
  52. }
  53. else if (typeof b === 'string') {
  54. var m = loadAsFileSync(path.resolve(x, b));
  55. if (m) return m;
  56. }
  57. else if (pkg.main) {
  58. var m = loadAsFileSync(path.resolve(x, pkg.main));
  59. if (m) return m;
  60. }
  61. }
  62. return loadAsFileSync(x + '/index');
  63. }
  64. function loadNodeModulesSync (x, start) {
  65. var dirs = nodeModulesPathsSync(start);
  66. for (var i = 0; i < dirs.length; i++) {
  67. var dir = dirs[i];
  68. var m = loadAsFileSync(dir + '/' + x);
  69. if (m) return m;
  70. var n = loadAsDirectorySync(dir + '/' + x);
  71. if (n) return n;
  72. }
  73. var m = loadAsFileSync(x);
  74. if (m) return m;
  75. }
  76. function nodeModulesPathsSync (start) {
  77. var parts;
  78. if (start === '/') parts = [ '' ];
  79. else parts = path.normalize(start).split('/');
  80. var dirs = [];
  81. for (var i = parts.length - 1; i >= 0; i--) {
  82. if (parts[i] === 'node_modules') continue;
  83. var dir = parts.slice(0, i + 1).join('/') + '/node_modules';
  84. dirs.push(dir);
  85. }
  86. return dirs;
  87. }
  88. };
  89. })();
  90. require.alias = function (from, to) {
  91. var path = require.modules.path();
  92. var res = null;
  93. try {
  94. res = require.resolve(from + '/package.json', '/');
  95. }
  96. catch (err) {
  97. res = require.resolve(from, '/');
  98. }
  99. var basedir = path.dirname(res);
  100. var keys = (Object.keys || function (obj) {
  101. var res = [];
  102. for (var key in obj) res.push(key)
  103. return res;
  104. })(require.modules);
  105. for (var i = 0; i < keys.length; i++) {
  106. var key = keys[i];
  107. if (key.slice(0, basedir.length + 1) === basedir + '/') {
  108. var f = key.slice(basedir.length);
  109. require.modules[to + f] = require.modules[basedir + f];
  110. }
  111. else if (key === basedir) {
  112. require.modules[to] = require.modules[basedir];
  113. }
  114. }
  115. };
  116. require.define = function (filename, fn) {
  117. var dirname = require._core[filename]
  118. ? ''
  119. : require.modules.path().dirname(filename)
  120. ;
  121. var require_ = function (file) {
  122. return require(file, dirname)
  123. };
  124. require_.resolve = function (name) {
  125. return require.resolve(name, dirname);
  126. };
  127. require_.modules = require.modules;
  128. require_.define = require.define;
  129. var module_ = { exports : {} };
  130. require.modules[filename] = function () {
  131. require.modules[filename]._cached = module_.exports;
  132. fn.call(
  133. module_.exports,
  134. require_,
  135. module_,
  136. module_.exports,
  137. dirname,
  138. filename
  139. );
  140. require.modules[filename]._cached = module_.exports;
  141. return module_.exports;
  142. };
  143. };
  144. if (typeof process === 'undefined') process = {};
  145. if (!process.nextTick) process.nextTick = (function () {
  146. var queue = [];
  147. var canPost = typeof window !== 'undefined'
  148. && window.postMessage && window.addEventListener
  149. ;
  150. if (canPost) {
  151. window.addEventListener('message', function (ev) {
  152. if (ev.source === window && ev.data === 'browserify-tick') {
  153. ev.stopPropagation();
  154. if (queue.length > 0) {
  155. var fn = queue.shift();
  156. fn();
  157. }
  158. }
  159. }, true);
  160. }
  161. return function (fn) {
  162. if (canPost) {
  163. queue.push(fn);
  164. window.postMessage('browserify-tick', '*');
  165. }
  166. else setTimeout(fn, 0);
  167. };
  168. })();
  169. if (!process.title) process.title = 'browser';
  170. if (!process.binding) process.binding = function (name) {
  171. if (name === 'evals') return require('vm')
  172. else throw new Error('No such module')
  173. };
  174. if (!process.cwd) process.cwd = function () { return '.' };
  175. require.define("path", function (require, module, exports, __dirname, __filename) {
  176. function filter (xs, fn) {
  177. var res = [];
  178. for (var i = 0; i < xs.length; i++) {
  179. if (fn(xs[i], i, xs)) res.push(xs[i]);
  180. }
  181. return res;
  182. }
  183. // resolves . and .. elements in a path array with directory names there
  184. // must be no slashes, empty elements, or device names (c:\) in the array
  185. // (so also no leading and trailing slashes - it does not distinguish
  186. // relative and absolute paths)
  187. function normalizeArray(parts, allowAboveRoot) {
  188. // if the path tries to go above the root, `up` ends up > 0
  189. var up = 0;
  190. for (var i = parts.length; i >= 0; i--) {
  191. var last = parts[i];
  192. if (last == '.') {
  193. parts.splice(i, 1);
  194. } else if (last === '..') {
  195. parts.splice(i, 1);
  196. up++;
  197. } else if (up) {
  198. parts.splice(i, 1);
  199. up--;
  200. }
  201. }
  202. // if the path is allowed to go above the root, restore leading ..s
  203. if (allowAboveRoot) {
  204. for (; up--; up) {
  205. parts.unshift('..');
  206. }
  207. }
  208. return parts;
  209. }
  210. // Regex to split a filename into [*, dir, basename, ext]
  211. // posix version
  212. var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/;
  213. // path.resolve([from ...], to)
  214. // posix version
  215. exports.resolve = function() {
  216. var resolvedPath = '',
  217. resolvedAbsolute = false;
  218. for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) {
  219. var path = (i >= 0)
  220. ? arguments[i]
  221. : process.cwd();
  222. // Skip empty and invalid entries
  223. if (typeof path !== 'string' || !path) {
  224. continue;
  225. }
  226. resolvedPath = path + '/' + resolvedPath;
  227. resolvedAbsolute = path.charAt(0) === '/';
  228. }
  229. // At this point the path should be resolved to a full absolute path, but
  230. // handle relative paths to be safe (might happen when process.cwd() fails)
  231. // Normalize the path
  232. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  233. return !!p;
  234. }), !resolvedAbsolute).join('/');
  235. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  236. };
  237. // path.normalize(path)
  238. // posix version
  239. exports.normalize = function(path) {
  240. var isAbsolute = path.charAt(0) === '/',
  241. trailingSlash = path.slice(-1) === '/';
  242. // Normalize the path
  243. path = normalizeArray(filter(path.split('/'), function(p) {
  244. return !!p;
  245. }), !isAbsolute).join('/');
  246. if (!path && !isAbsolute) {
  247. path = '.';
  248. }
  249. if (path && trailingSlash) {
  250. path += '/';
  251. }
  252. return (isAbsolute ? '/' : '') + path;
  253. };
  254. // posix version
  255. exports.join = function() {
  256. var paths = Array.prototype.slice.call(arguments, 0);
  257. return exports.normalize(filter(paths, function(p, index) {
  258. return p && typeof p === 'string';
  259. }).join('/'));
  260. };
  261. exports.dirname = function(path) {
  262. var dir = splitPathRe.exec(path)[1] || '';
  263. var isWindows = false;
  264. if (!dir) {
  265. // No dirname
  266. return '.';
  267. } else if (dir.length === 1 ||
  268. (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) {
  269. // It is just a slash or a drive letter with a slash
  270. return dir;
  271. } else {
  272. // It is a full dirname, strip trailing slash
  273. return dir.substring(0, dir.length - 1);
  274. }
  275. };
  276. exports.basename = function(path, ext) {
  277. var f = splitPathRe.exec(path)[2] || '';
  278. // TODO: make this comparison case-insensitive on windows?
  279. if (ext && f.substr(-1 * ext.length) === ext) {
  280. f = f.substr(0, f.length - ext.length);
  281. }
  282. return f;
  283. };
  284. exports.extname = function(path) {
  285. return splitPathRe.exec(path)[3] || '';
  286. };
  287. });
  288. require.define("/shred.js", function (require, module, exports, __dirname, __filename) {
  289. // Shred is an HTTP client library intended to simplify the use of Node's
  290. // built-in HTTP library. In particular, we wanted to make it easier to interact
  291. // with HTTP-based APIs.
  292. //
  293. // See the [examples](./examples.html) for more details.
  294. // Ax is a nice logging library we wrote. You can use any logger, providing it
  295. // has `info`, `warn`, `debug`, and `error` methods that take a string.
  296. var Ax = require("ax")
  297. , CookieJarLib = require( "cookiejar" )
  298. , CookieJar = CookieJarLib.CookieJar
  299. ;
  300. // Shred takes some options, including a logger and request defaults.
  301. var Shred = function(options) {
  302. options = (options||{});
  303. this.agent = options.agent;
  304. this.defaults = options.defaults||{};
  305. this.log = options.logger||(new Ax({ level: "info" }));
  306. this._sharedCookieJar = new CookieJar();
  307. this.logCurl = options.logCurl || false;
  308. };
  309. // Most of the real work is done in the request and reponse classes.
  310. Shred.Request = require("./shred/request");
  311. Shred.Response = require("./shred/response");
  312. // The `request` method kicks off a new request, instantiating a new `Request`
  313. // object and passing along whatever default options we were given.
  314. Shred.prototype = {
  315. request: function(options) {
  316. options.logger = this.log;
  317. options.logCurl = options.logCurl || this.logCurl;
  318. options.cookieJar = ( 'cookieJar' in options ) ? options.cookieJar : this._sharedCookieJar; // let them set cookieJar = null
  319. options.agent = options.agent || this.agent;
  320. // fill in default options
  321. for (var key in this.defaults) {
  322. if (this.defaults.hasOwnProperty(key) && !options[key]) {
  323. options[key] = this.defaults[key]
  324. }
  325. }
  326. return new Shred.Request(options);
  327. }
  328. };
  329. // Define a bunch of convenience methods so that you don't have to include
  330. // a `method` property in your request options.
  331. "get put post delete".split(" ").forEach(function(method) {
  332. Shred.prototype[method] = function(options) {
  333. options.method = method;
  334. return this.request(options);
  335. };
  336. });
  337. module.exports = Shred;
  338. });
  339. require.define("/node_modules/ax/package.json", function (require, module, exports, __dirname, __filename) {
  340. module.exports = {"main":"./lib/ax.js"}
  341. });
  342. require.define("/node_modules/ax/lib/ax.js", function (require, module, exports, __dirname, __filename) {
  343. var inspect = require("util").inspect
  344. , fs = require("fs")
  345. ;
  346. // this is a quick-and-dirty logger. there are other nicer loggers out there
  347. // but the ones i found were also somewhat involved. this one has a Ruby
  348. // logger type interface
  349. //
  350. // we can easily replace this, provide the info, debug, etc. methods are the
  351. // same. or, we can change Haiku to use a more standard node.js interface
  352. var format = function(level,message) {
  353. var debug = (level=="debug"||level=="error");
  354. if (!message) { return message.toString(); }
  355. if (typeof(message) == "object") {
  356. if (message instanceof Error && debug) {
  357. return message.stack;
  358. } else {
  359. return inspect(message);
  360. }
  361. } else {
  362. return message.toString();
  363. }
  364. };
  365. var noOp = function(message) { return this; }
  366. var makeLogger = function(level,fn) {
  367. return function(message) {
  368. this.stream.write(this.format(level, message)+"\n");
  369. return this;
  370. }
  371. };
  372. var Logger = function(options) {
  373. var logger = this;
  374. var options = options||{};
  375. // Default options
  376. options.level = options.level || "info";
  377. options.timestamp = options.timestamp || true;
  378. options.prefix = options.prefix || "";
  379. logger.options = options;
  380. // Allows a prefix to be added to the message.
  381. //
  382. // var logger = new Ax({ module: 'Haiku' })
  383. // logger.warn('this is going to be awesome!');
  384. // //=> Haiku: this is going to be awesome!
  385. //
  386. if (logger.options.module){
  387. logger.options.prefix = logger.options.module;
  388. }
  389. // Write to stderr or a file
  390. if (logger.options.file){
  391. logger.stream = fs.createWriteStream(logger.options.file, {"flags": "a"});
  392. } else {
  393. if(process.title === "node")
  394. logger.stream = process.stderr;
  395. else if(process.title === "browser")
  396. logger.stream = function () {
  397. // Work around weird console context issue: http://code.google.com/p/chromium/issues/detail?id=48662
  398. return console[logger.options.level].apply(console, arguments);
  399. };
  400. }
  401. switch(logger.options.level){
  402. case 'debug':
  403. ['debug', 'info', 'warn'].forEach(function (level) {
  404. logger[level] = Logger.writer(level);
  405. });
  406. case 'info':
  407. ['info', 'warn'].forEach(function (level) {
  408. logger[level] = Logger.writer(level);
  409. });
  410. case 'warn':
  411. logger.warn = Logger.writer('warn');
  412. }
  413. }
  414. // Used to define logger methods
  415. Logger.writer = function(level){
  416. return function(message){
  417. var logger = this;
  418. if(process.title === "node")
  419. logger.stream.write(logger.format(level, message) + '\n');
  420. else if(process.title === "browser")
  421. logger.stream(logger.format(level, message) + '\n');
  422. };
  423. }
  424. Logger.prototype = {
  425. info: function(){},
  426. debug: function(){},
  427. warn: function(){},
  428. error: Logger.writer('error'),
  429. format: function(level, message){
  430. if (! message) return '';
  431. var logger = this
  432. , prefix = logger.options.prefix
  433. , timestamp = logger.options.timestamp ? " " + (new Date().toISOString()) : ""
  434. ;
  435. return (prefix + timestamp + ": " + message);
  436. }
  437. };
  438. module.exports = Logger;
  439. });
  440. require.define("util", function (require, module, exports, __dirname, __filename) {
  441. // todo
  442. });
  443. require.define("fs", function (require, module, exports, __dirname, __filename) {
  444. // nothing to see here... no file methods for the browser
  445. });
  446. require.define("/node_modules/cookiejar/package.json", function (require, module, exports, __dirname, __filename) {
  447. module.exports = {"main":"cookiejar.js"}
  448. });
  449. require.define("/node_modules/cookiejar/cookiejar.js", function (require, module, exports, __dirname, __filename) {
  450. exports.CookieAccessInfo=CookieAccessInfo=function CookieAccessInfo(domain,path,secure,script) {
  451. if(this instanceof CookieAccessInfo) {
  452. this.domain=domain||undefined;
  453. this.path=path||"/";
  454. this.secure=!!secure;
  455. this.script=!!script;
  456. return this;
  457. }
  458. else {
  459. return new CookieAccessInfo(domain,path,secure,script)
  460. }
  461. }
  462. exports.Cookie=Cookie=function Cookie(cookiestr) {
  463. if(cookiestr instanceof Cookie) {
  464. return cookiestr;
  465. }
  466. else {
  467. if(this instanceof Cookie) {
  468. this.name = null;
  469. this.value = null;
  470. this.expiration_date = Infinity;
  471. this.path = "/";
  472. this.domain = null;
  473. this.secure = false; //how to define?
  474. this.noscript = false; //httponly
  475. if(cookiestr) {
  476. this.parse(cookiestr)
  477. }
  478. return this;
  479. }
  480. return new Cookie(cookiestr)
  481. }
  482. }
  483. Cookie.prototype.toString = function toString() {
  484. var str=[this.name+"="+this.value];
  485. if(this.expiration_date !== Infinity) {
  486. str.push("expires="+(new Date(this.expiration_date)).toGMTString());
  487. }
  488. if(this.domain) {
  489. str.push("domain="+this.domain);
  490. }
  491. if(this.path) {
  492. str.push("path="+this.path);
  493. }
  494. if(this.secure) {
  495. str.push("secure");
  496. }
  497. if(this.noscript) {
  498. str.push("httponly");
  499. }
  500. return str.join("; ");
  501. }
  502. Cookie.prototype.toValueString = function toValueString() {
  503. return this.name+"="+this.value;
  504. }
  505. var cookie_str_splitter=/[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g
  506. Cookie.prototype.parse = function parse(str) {
  507. if(this instanceof Cookie) {
  508. var parts=str.split(";")
  509. , pair=parts[0].match(/([^=]+)=((?:.|\n)*)/)
  510. , key=pair[1]
  511. , value=pair[2];
  512. this.name = key;
  513. this.value = value;
  514. for(var i=1;i<parts.length;i++) {
  515. pair=parts[i].match(/([^=]+)(?:=((?:.|\n)*))?/)
  516. , key=pair[1].trim().toLowerCase()
  517. , value=pair[2];
  518. switch(key) {
  519. case "httponly":
  520. this.noscript = true;
  521. break;
  522. case "expires":
  523. this.expiration_date = value
  524. ? Number(Date.parse(value))
  525. : Infinity;
  526. break;
  527. case "path":
  528. this.path = value
  529. ? value.trim()
  530. : "";
  531. break;
  532. case "domain":
  533. this.domain = value
  534. ? value.trim()
  535. : "";
  536. break;
  537. case "secure":
  538. this.secure = true;
  539. break
  540. }
  541. }
  542. return this;
  543. }
  544. return new Cookie().parse(str)
  545. }
  546. Cookie.prototype.matches = function matches(access_info) {
  547. if(this.noscript && access_info.script
  548. || this.secure && !access_info.secure
  549. || !this.collidesWith(access_info)) {
  550. return false
  551. }
  552. return true;
  553. }
  554. Cookie.prototype.collidesWith = function collidesWith(access_info) {
  555. if((this.path && !access_info.path) || (this.domain && !access_info.domain)) {
  556. return false
  557. }
  558. if(this.path && access_info.path.indexOf(this.path) !== 0) {
  559. return false;
  560. }
  561. if (this.domain===access_info.domain) {
  562. return true;
  563. }
  564. else if(this.domain && this.domain.charAt(0)===".")
  565. {
  566. var wildcard=access_info.domain.indexOf(this.domain.slice(1))
  567. if(wildcard===-1 || wildcard!==access_info.domain.length-this.domain.length+1) {
  568. return false;
  569. }
  570. }
  571. else if(this.domain){
  572. return false
  573. }
  574. return true;
  575. }
  576. exports.CookieJar=CookieJar=function CookieJar() {
  577. if(this instanceof CookieJar) {
  578. var cookies = {} //name: [Cookie]
  579. this.setCookie = function setCookie(cookie) {
  580. cookie = Cookie(cookie);
  581. //Delete the cookie if the set is past the current time
  582. var remove = cookie.expiration_date <= Date.now();
  583. if(cookie.name in cookies) {
  584. var cookies_list = cookies[cookie.name];
  585. for(var i=0;i<cookies_list.length;i++) {
  586. var collidable_cookie = cookies_list[i];
  587. if(collidable_cookie.collidesWith(cookie)) {
  588. if(remove) {
  589. cookies_list.splice(i,1);
  590. if(cookies_list.length===0) {
  591. delete cookies[cookie.name]
  592. }
  593. return false;
  594. }
  595. else {
  596. return cookies_list[i]=cookie;
  597. }
  598. }
  599. }
  600. if(remove) {
  601. return false;
  602. }
  603. cookies_list.push(cookie);
  604. return cookie;
  605. }
  606. else if(remove){
  607. return false;
  608. }
  609. else {
  610. return cookies[cookie.name]=[cookie];
  611. }
  612. }
  613. //returns a cookie
  614. this.getCookie = function getCookie(cookie_name,access_info) {
  615. var cookies_list = cookies[cookie_name];
  616. for(var i=0;i<cookies_list.length;i++) {
  617. var cookie = cookies_list[i];
  618. if(cookie.expiration_date <= Date.now()) {
  619. if(cookies_list.length===0) {
  620. delete cookies[cookie.name]
  621. }
  622. continue;
  623. }
  624. if(cookie.matches(access_info)) {
  625. return cookie;
  626. }
  627. }
  628. }
  629. //returns a list of cookies
  630. this.getCookies = function getCookies(access_info) {
  631. var matches=[];
  632. for(var cookie_name in cookies) {
  633. var cookie=this.getCookie(cookie_name,access_info);
  634. if (cookie) {
  635. matches.push(cookie);
  636. }
  637. }
  638. matches.toString=function toString(){return matches.join(":");}
  639. matches.toValueString=function() {return matches.map(function(c){return c.toValueString();}).join(';');}
  640. return matches;
  641. }
  642. return this;
  643. }
  644. return new CookieJar()
  645. }
  646. //returns list of cookies that were set correctly
  647. CookieJar.prototype.setCookies = function setCookies(cookies) {
  648. cookies=Array.isArray(cookies)
  649. ?cookies
  650. :cookies.split(cookie_str_splitter);
  651. var successful=[]
  652. for(var i=0;i<cookies.length;i++) {
  653. var cookie = Cookie(cookies[i]);
  654. if(this.setCookie(cookie)) {
  655. successful.push(cookie);
  656. }
  657. }
  658. return successful;
  659. }
  660. });
  661. require.define("/shred/request.js", function (require, module, exports, __dirname, __filename) {
  662. // The request object encapsulates a request, creating a Node.js HTTP request and
  663. // then handling the response.
  664. var HTTP = require("http")
  665. , HTTPS = require("https")
  666. , parseUri = require("./parseUri")
  667. , Emitter = require('events').EventEmitter
  668. , sprintf = require("sprintf").sprintf
  669. , Response = require("./response")
  670. , HeaderMixins = require("./mixins/headers")
  671. , Content = require("./content")
  672. ;
  673. var STATUS_CODES = HTTP.STATUS_CODES || {
  674. 100 : 'Continue',
  675. 101 : 'Switching Protocols',
  676. 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
  677. 200 : 'OK',
  678. 201 : 'Created',
  679. 202 : 'Accepted',
  680. 203 : 'Non-Authoritative Information',
  681. 204 : 'No Content',
  682. 205 : 'Reset Content',
  683. 206 : 'Partial Content',
  684. 207 : 'Multi-Status', // RFC 4918
  685. 300 : 'Multiple Choices',
  686. 301 : 'Moved Permanently',
  687. 302 : 'Moved Temporarily',
  688. 303 : 'See Other',
  689. 304 : 'Not Modified',
  690. 305 : 'Use Proxy',
  691. 307 : 'Temporary Redirect',
  692. 400 : 'Bad Request',
  693. 401 : 'Unauthorized',
  694. 402 : 'Payment Required',
  695. 403 : 'Forbidden',
  696. 404 : 'Not Found',
  697. 405 : 'Method Not Allowed',
  698. 406 : 'Not Acceptable',
  699. 407 : 'Proxy Authentication Required',
  700. 408 : 'Request Time-out',
  701. 409 : 'Conflict',
  702. 410 : 'Gone',
  703. 411 : 'Length Required',
  704. 412 : 'Precondition Failed',
  705. 413 : 'Request Entity Too Large',
  706. 414 : 'Request-URI Too Large',
  707. 415 : 'Unsupported Media Type',
  708. 416 : 'Requested Range Not Satisfiable',
  709. 417 : 'Expectation Failed',
  710. 418 : 'I\'m a teapot', // RFC 2324
  711. 422 : 'Unprocessable Entity', // RFC 4918
  712. 423 : 'Locked', // RFC 4918
  713. 424 : 'Failed Dependency', // RFC 4918
  714. 425 : 'Unordered Collection', // RFC 4918
  715. 426 : 'Upgrade Required', // RFC 2817
  716. 500 : 'Internal Server Error',
  717. 501 : 'Not Implemented',
  718. 502 : 'Bad Gateway',
  719. 503 : 'Service Unavailable',
  720. 504 : 'Gateway Time-out',
  721. 505 : 'HTTP Version not supported',
  722. 506 : 'Variant Also Negotiates', // RFC 2295
  723. 507 : 'Insufficient Storage', // RFC 4918
  724. 509 : 'Bandwidth Limit Exceeded',
  725. 510 : 'Not Extended' // RFC 2774
  726. };
  727. // The Shred object itself constructs the `Request` object. You should rarely
  728. // need to do this directly.
  729. var Request = function(options) {
  730. this.log = options.logger;
  731. this.cookieJar = options.cookieJar;
  732. this.encoding = options.encoding;
  733. this.logCurl = options.logCurl;
  734. processOptions(this,options||{});
  735. createRequest(this);
  736. };
  737. // A `Request` has a number of properties, many of which help with details like
  738. // URL parsing or defaulting the port for the request.
  739. Object.defineProperties(Request.prototype, {
  740. // - **url**. You can set the `url` property with a valid URL string and all the
  741. // URL-related properties (host, port, etc.) will be automatically set on the
  742. // request object.
  743. url: {
  744. get: function() {
  745. if (!this.scheme) { return null; }
  746. return sprintf("%s://%s:%s%s",
  747. this.scheme, this.host, this.port,
  748. (this.proxy ? "/" : this.path) +
  749. (this.query ? ("?" + this.query) : ""));
  750. },
  751. set: function(_url) {
  752. _url = parseUri(_url);
  753. this.scheme = _url.protocol;
  754. this.host = _url.host;
  755. this.port = _url.port;
  756. this.path = _url.path;
  757. this.query = _url.query;
  758. return this;
  759. },
  760. enumerable: true
  761. },
  762. // - **headers**. Returns a hash representing the request headers. You can't set
  763. // this directly, only get it. You can add or modify headers by using the
  764. // `setHeader` or `setHeaders` method. This ensures that the headers are
  765. // normalized - that is, you don't accidentally send `Content-Type` and
  766. // `content-type` headers. Keep in mind that if you modify the returned hash,
  767. // it will *not* modify the request headers.
  768. headers: {
  769. get: function() {
  770. return this.getHeaders();
  771. },
  772. enumerable: true
  773. },
  774. // - **port**. Unless you set the `port` explicitly or include it in the URL, it
  775. // will default based on the scheme.
  776. port: {
  777. get: function() {
  778. if (!this._port) {
  779. switch(this.scheme) {
  780. case "https": return this._port = 443;
  781. case "http":
  782. default: return this._port = 80;
  783. }
  784. }
  785. return this._port;
  786. },
  787. set: function(value) { this._port = value; return this; },
  788. enumerable: true
  789. },
  790. // - **method**. The request method - `get`, `put`, `post`, etc. that will be
  791. // used to make the request. Defaults to `get`.
  792. method: {
  793. get: function() {
  794. return this._method = (this._method||"GET");
  795. },
  796. set: function(value) {
  797. this._method = value; return this;
  798. },
  799. enumerable: true
  800. },
  801. // - **query**. Can be set either with a query string or a hash (object). Get
  802. // will always return a properly escaped query string or null if there is no
  803. // query component for the request.
  804. query: {
  805. get: function() {return this._query;},
  806. set: function(value) {
  807. var stringify = function (hash) {
  808. var query = "";
  809. for (var key in hash) {
  810. query += encodeURIComponent(key) + '=' + encodeURIComponent(hash[key]) + '&';
  811. }
  812. // Remove the last '&'
  813. query = query.slice(0, -1);
  814. return query;
  815. }
  816. if (value) {
  817. if (typeof value === 'object') {
  818. value = stringify(value);
  819. }
  820. this._query = value;
  821. } else {
  822. this._query = "";
  823. }
  824. return this;
  825. },
  826. enumerable: true
  827. },
  828. // - **parameters**. This will return the query parameters in the form of a hash
  829. // (object).
  830. parameters: {
  831. get: function() { return QueryString.parse(this._query||""); },
  832. enumerable: true
  833. },
  834. // - **content**. (Aliased as `body`.) Set this to add a content entity to the
  835. // request. Attempts to use the `content-type` header to determine what to do
  836. // with the content value. Get this to get back a [`Content`
  837. // object](./content.html).
  838. body: {
  839. get: function() { return this._body; },
  840. set: function(value) {
  841. this._body = new Content({
  842. data: value,
  843. type: this.getHeader("Content-Type")
  844. });
  845. this.setHeader("Content-Type",this.content.type);
  846. this.setHeader("Content-Length",this.content.length);
  847. return this;
  848. },
  849. enumerable: true
  850. },
  851. // - **timeout**. Used to determine how long to wait for a response. Does not
  852. // distinguish between connect timeouts versus request timeouts. Set either in
  853. // milliseconds or with an object with temporal attributes (hours, minutes,
  854. // seconds) and convert it into milliseconds. Get will always return
  855. // milliseconds.
  856. timeout: {
  857. get: function() { return this._timeout; }, // in milliseconds
  858. set: function(timeout) {
  859. var request = this
  860. , milliseconds = 0;
  861. ;
  862. if (!timeout) return this;
  863. if (typeof timeout==="number") { milliseconds = timeout; }
  864. else {
  865. milliseconds = (timeout.milliseconds||0) +
  866. (1000 * ((timeout.seconds||0) +
  867. (60 * ((timeout.minutes||0) +
  868. (60 * (timeout.hours||0))))));
  869. }
  870. this._timeout = milliseconds;
  871. return this;
  872. },
  873. enumerable: true
  874. }
  875. });
  876. // Alias `body` property to `content`. Since the [content object](./content.html)
  877. // has a `body` attribute, it's preferable to use `content` since you can then
  878. // access the raw content data using `content.body`.
  879. Object.defineProperty(Request.prototype,"content",
  880. Object.getOwnPropertyDescriptor(Request.prototype, "body"));
  881. // The `Request` object can be pretty overwhelming to view using the built-in
  882. // Node.js inspect method. We want to make it a bit more manageable. This
  883. // probably goes [too far in the other
  884. // direction](https://github.com/spire-io/shred/issues/2).
  885. Request.prototype.inspect = function () {
  886. var request = this;
  887. var headers = this.format_headers();
  888. var summary = ["<Shred Request> ", request.method.toUpperCase(),
  889. request.url].join(" ")
  890. return [ summary, "- Headers:", headers].join("\n");
  891. };
  892. Request.prototype.format_headers = function () {
  893. var array = []
  894. var headers = this._headers
  895. for (var key in headers) {
  896. if (headers.hasOwnProperty(key)) {
  897. var value = headers[key]
  898. array.push("\t" + key + ": " + value);
  899. }
  900. }
  901. return array.join("\n");
  902. };
  903. // Allow chainable 'on's: shred.get({ ... }).on( ... ). You can pass in a
  904. // single function, a pair (event, function), or a hash:
  905. // { event: function, event: function }
  906. Request.prototype.on = function (eventOrHash, listener) {
  907. var emitter = this.emitter;
  908. // Pass in a single argument as a function then make it the default response handler
  909. if (arguments.length === 1 && typeof(eventOrHash) === 'function') {
  910. emitter.on('response', eventOrHash);
  911. } else if (arguments.length === 1 && typeof(eventOrHash) === 'object') {
  912. for (var key in eventOrHash) {
  913. if (eventOrHash.hasOwnProperty(key)) {
  914. emitter.on(key, eventOrHash[key]);
  915. }
  916. }
  917. } else {
  918. emitter.on(eventOrHash, listener);
  919. }
  920. return this;
  921. };
  922. // Add in the header methods. Again, these ensure we don't get the same header
  923. // multiple times with different case conventions.
  924. HeaderMixins.gettersAndSetters(Request);
  925. // `processOptions` is called from the constructor to handle all the work
  926. // associated with making sure we do our best to ensure we have a valid request.
  927. var processOptions = function(request,options) {
  928. request.log.debug("Processing request options ..");
  929. // We'll use `request.emitter` to manage the `on` event handlers.
  930. request.emitter = (new Emitter);
  931. request.agent = options.agent;
  932. // Set up the handlers ...
  933. if (options.on) {
  934. for (var key in options.on) {
  935. if (options.on.hasOwnProperty(key)) {
  936. request.emitter.on(key, options.on[key]);
  937. }
  938. }
  939. }
  940. // Make sure we were give a URL or a host
  941. if (!options.url && !options.host) {
  942. request.emitter.emit("request_error",
  943. new Error("No url or url options (host, port, etc.)"));
  944. return;
  945. }
  946. // Allow for the [use of a proxy](http://www.jmarshall.com/easy/http/#proxies).
  947. if (options.url) {
  948. if (options.proxy) {
  949. request.url = options.proxy;
  950. request.path = options.url;
  951. } else {
  952. request.url = options.url;
  953. }
  954. }
  955. // Set the remaining options.
  956. request.query = options.query||options.parameters||request.query ;
  957. request.method = options.method;
  958. request.setHeader("user-agent",options.agent||"Shred");
  959. request.setHeaders(options.headers);
  960. if (request.cookieJar) {
  961. var cookies = request.cookieJar.getCookies( CookieAccessInfo( request.host, request.path ) );
  962. if (cookies.length) {
  963. var cookieString = request.getHeader('cookie')||'';
  964. for (var cookieIndex = 0; cookieIndex < cookies.length; ++cookieIndex) {
  965. if ( cookieString.length && cookieString[ cookieString.length - 1 ] != ';' )
  966. {
  967. cookieString += ';';
  968. }
  969. cookieString += cookies[ cookieIndex ].name + '=' + cookies[ cookieIndex ].value + ';';
  970. }
  971. request.setHeader("cookie", cookieString);
  972. }
  973. }
  974. // The content entity can be set either using the `body` or `content` attributes.
  975. if (options.body||options.content) {
  976. request.content = options.body||options.content;
  977. }
  978. request.timeout = options.timeout;
  979. };
  980. // `createRequest` is also called by the constructor, after `processOptions`.
  981. // This actually makes the request and processes the response, so `createRequest`
  982. // is a bit of a misnomer.
  983. var createRequest = function(request) {
  984. var timeout ;
  985. request.log.debug("Creating request ..");
  986. request.log.debug(request);
  987. var reqParams = {
  988. host: request.host,
  989. port: request.port,
  990. method: request.method,
  991. path: request.path + (request.query ? '?'+request.query : ""),
  992. headers: request.getHeaders(),
  993. // Node's HTTP/S modules will ignore this, but we are using the
  994. // browserify-http module in the browser for both HTTP and HTTPS, and this
  995. // is how you differentiate the two.
  996. scheme: request.scheme,
  997. // Use a provided agent. 'Undefined' is the default, which uses a global
  998. // agent.
  999. agent: request.agent
  1000. };
  1001. if (request.logCurl) {
  1002. logCurl(request);
  1003. }
  1004. var http = request.scheme == "http" ? HTTP : HTTPS;
  1005. // Set up the real request using the selected library. The request won't be
  1006. // sent until we call `.end()`.
  1007. request._raw = http.request(reqParams, function(response) {
  1008. request.log.debug("Received response ..");
  1009. // We haven't timed out and we have a response, so make sure we clear the
  1010. // timeout so it doesn't fire while we're processing the response.
  1011. clearTimeout(timeout);
  1012. // Construct a Shred `Response` object from the response. This will stream
  1013. // the response, thus the need for the callback. We can access the response
  1014. // entity safely once we're in the callback.
  1015. response = new Response(response, request, function(response) {
  1016. // Set up some event magic. The precedence is given first to
  1017. // status-specific handlers, then to responses for a given event, and then
  1018. // finally to the more general `response` handler. In the last case, we
  1019. // need to first make sure we're not dealing with a a redirect.
  1020. var emit = function(event) {
  1021. var emitter = request.emitter;
  1022. var textStatus = STATUS_CODES[response.status] ? STATUS_CODES[response.status].toLowerCase() : null;
  1023. if (emitter.listeners(response.status).length > 0 || emitter.listeners(textStatus).length > 0) {
  1024. emitter.emit(response.status, response);
  1025. emitter.emit(textStatus, response);
  1026. } else {
  1027. if (emitter.listeners(event).length>0) {
  1028. emitter.emit(event, response);
  1029. } else if (!response.isRedirect) {
  1030. emitter.emit("response", response);
  1031. //console.warn("Request has no event listener for status code " + response.status);
  1032. }
  1033. }
  1034. };
  1035. // Next, check for a redirect. We simply repeat the request with the URL
  1036. // given in the `Location` header. We fire a `redirect` event.
  1037. if (response.isRedirect) {
  1038. request.log.debug("Redirecting to "
  1039. + response.getHeader("Location"));
  1040. request.url = response.getHeader("Location");
  1041. emit("redirect");
  1042. createRequest(request);
  1043. // Okay, it's not a redirect. Is it an error of some kind?
  1044. } else if (response.isError) {
  1045. emit("error");
  1046. } else {
  1047. // It looks like we're good shape. Trigger the `success` event.
  1048. emit("success");
  1049. }
  1050. });
  1051. });
  1052. // We're still setting up the request. Next, we're going to handle error cases
  1053. // where we have no response. We don't emit an error event because that event
  1054. // takes a response. We don't response handlers to have to check for a null
  1055. // value. However, we [should introduce a different event
  1056. // type](https://github.com/spire-io/shred/issues/3) for this type of error.
  1057. request._raw.on("error", function(error) {
  1058. request.emitter.emit("request_error", error);
  1059. });
  1060. request._raw.on("socket", function(socket) {
  1061. request.emitter.emit("socket", socket);
  1062. });
  1063. // TCP timeouts should also trigger the "response_error" event.
  1064. request._raw.on('socket', function () {
  1065. request._raw.socket.on('timeout', function () {
  1066. // This should trigger the "error" event on the raw request, which will
  1067. // trigger the "response_error" on the shred request.
  1068. request._raw.abort();
  1069. });
  1070. });
  1071. // We're almost there. Next, we need to write the request entity to the
  1072. // underlying request object.
  1073. if (request.content) {
  1074. request.log.debug("Streaming body: '" +
  1075. request.content.data.slice(0,59) + "' ... ");
  1076. request._raw.write(request.content.data);
  1077. }
  1078. // Finally, we need to set up the timeout. We do this last so that we don't
  1079. // start the clock ticking until the last possible moment.
  1080. if (request.timeout) {
  1081. timeout = setTimeout(function() {
  1082. request.log.debug("Timeout fired, aborting request ...");
  1083. request._raw.abort();
  1084. request.emitter.emit("timeout", request);
  1085. },request.timeout);
  1086. }
  1087. // The `.end()` method will cause the request to fire. Technically, it might
  1088. // have already sent the headers and body.
  1089. request.log.debug("Sending request ...");
  1090. request._raw.end();
  1091. };
  1092. // Logs the curl command for the request.
  1093. var logCurl = function (req) {
  1094. var headers = req.getHeaders();
  1095. var headerString = "";
  1096. for (var key in headers) {
  1097. headerString += '-H "' + key + ": " + headers[key] + '" ';
  1098. }
  1099. var bodyString = ""
  1100. if (req.content) {
  1101. bodyString += "-d '" + req.content.body + "' ";
  1102. }
  1103. var query = req.query ? '?' + req.query : "";
  1104. console.log("curl " +
  1105. "-X " + req.method.toUpperCase() + " " +
  1106. req.scheme + "://" + req.host + ":" + req.port + req.path + query + " " +
  1107. headerString +
  1108. bodyString
  1109. );
  1110. };
  1111. module.exports = Request;
  1112. });
  1113. require.define("http", function (require, module, exports, __dirname, __filename) {
  1114. // todo
  1115. });
  1116. require.define("https", function (require, module, exports, __dirname, __filename) {
  1117. // todo
  1118. });
  1119. require.define("/shred/parseUri.js", function (require, module, exports, __dirname, __filename) {
  1120. // parseUri 1.2.2
  1121. // (c) Steven Levithan <stevenlevithan.com>
  1122. // MIT License
  1123. function parseUri (str) {
  1124. var o = parseUri.options,
  1125. m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
  1126. uri = {},
  1127. i = 14;
  1128. while (i--) uri[o.key[i]] = m[i] || "";
  1129. uri[o.q.name] = {};
  1130. uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
  1131. if ($1) uri[o.q.name][$1] = $2;
  1132. });
  1133. return uri;
  1134. };
  1135. parseUri.options = {
  1136. strictMode: false,
  1137. key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
  1138. q: {
  1139. name: "queryKey",
  1140. parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  1141. },
  1142. parser: {
  1143. strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
  1144. loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  1145. }
  1146. };
  1147. module.exports = parseUri;
  1148. });
  1149. require.define("events", function (require, module, exports, __dirname, __filename) {
  1150. if (!process.EventEmitter) process.EventEmitter = function () {};
  1151. var EventEmitter = exports.EventEmitter = process.EventEmitter;
  1152. var isArray = typeof Array.isArray === 'function'
  1153. ? Array.isArray
  1154. : function (xs) {
  1155. return Object.toString.call(xs) === '[object Array]'
  1156. }
  1157. ;
  1158. // By default EventEmitters will print a warning if more than
  1159. // 10 listeners are added to it. This is a useful default which
  1160. // helps finding memory leaks.
  1161. //
  1162. // Obviously not all Emitters should be limited to 10. This function allows
  1163. // that to be increased. Set to zero for unlimited.
  1164. var defaultMaxListeners = 10;
  1165. EventEmitter.prototype.setMaxListeners = function(n) {
  1166. if (!this._events) this._events = {};
  1167. this._events.maxListeners = n;
  1168. };
  1169. EventEmitter.prototype.emit = function(type) {
  1170. // If there is no 'error' event listener then throw.
  1171. if (type === 'error') {
  1172. if (!this._events || !this._events.error ||
  1173. (isArray(this._events.error) && !this._events.error.length))
  1174. {
  1175. if (arguments[1] instanceof Error) {
  1176. throw arguments[1]; // Unhandled 'error' event
  1177. } else {
  1178. throw new Error("Uncaught, unspecified 'error' event.");
  1179. }
  1180. return false;
  1181. }
  1182. }
  1183. if (!this._events) return false;
  1184. var handler = this._events[type];
  1185. if (!handler) return false;
  1186. if (typeof handler == 'function') {
  1187. switch (arguments.length) {
  1188. // fast cases
  1189. case 1:
  1190. handler.call(this);
  1191. break;
  1192. case 2:
  1193. handler.call(this, arguments[1]);
  1194. break;
  1195. case 3:
  1196. handler.call(this, arguments[1], arguments[2]);
  1197. break;
  1198. // slower
  1199. default:
  1200. var args = Array.prototype.slice.call(arguments, 1);
  1201. handler.apply(this, args);
  1202. }
  1203. return true;
  1204. } else if (isArray(handler)) {
  1205. var args = Array.prototype.slice.call(arguments, 1);
  1206. var listeners = handler.slice();
  1207. for (var i = 0, l = listeners.length; i < l; i++) {
  1208. listeners[i].apply(this, args);
  1209. }
  1210. return true;
  1211. } else {
  1212. return false;
  1213. }
  1214. };
  1215. // EventEmitter is defined in src/node_events.cc
  1216. // EventEmitter.prototype.emit() is also defined there.
  1217. EventEmitter.prototype.addListener = function(type, listener) {
  1218. if ('function' !== typeof listener) {
  1219. throw new Error('addListener only takes instances of Function');
  1220. }
  1221. if (!this._events) this._events = {};
  1222. // To avoid recursion in the case that type == "newListeners"! Before
  1223. // adding it to the listeners, first emit "newListeners".
  1224. this.emit('newListener', type, listener);
  1225. if (!this._events[type]) {
  1226. // Optimize the case of one listener. Don't need the extra array object.
  1227. this._events[type] = listener;
  1228. } else if (isArray(this._events[type])) {
  1229. // Check for listener leak
  1230. if (!this._events[type].warned) {
  1231. var m;
  1232. if (this._events.maxListeners !== undefined) {
  1233. m = this._events.maxListeners;
  1234. } else {
  1235. m = defaultMaxListeners;
  1236. }
  1237. if (m && m > 0 && this._events[type].length > m) {
  1238. this._events[type].warned = true;
  1239. console.error('(node) warning: possible EventEmitter memory ' +
  1240. 'leak detected. %d listeners added. ' +
  1241. 'Use emitter.setMaxListeners() to increase limit.',
  1242. this._events[type].length);
  1243. console.trace();
  1244. }
  1245. }
  1246. // If we've already got an array, just append.
  1247. this._events[type].push(listener);
  1248. } else {
  1249. // Adding the second element, need to change to array.
  1250. this._events[type] = [this._events[type], listener];
  1251. }
  1252. return this;
  1253. };
  1254. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  1255. EventEmitter.prototype.once = function(type, listener) {
  1256. var self = this;
  1257. self.on(type, function g() {
  1258. self.removeListener(type, g);
  1259. listener.apply(this, arguments);
  1260. });
  1261. return this;
  1262. };
  1263. EventEmitter.prototype.removeListener = function(type, listener) {
  1264. if ('function' !== typeof listener) {
  1265. throw new Error('removeListener only takes instances of Function');
  1266. }
  1267. // does not use listeners(), so no side effect of creating _events[type]
  1268. if (!this._events || !this._events[type]) return this;
  1269. var list = this._events[type];
  1270. if (isArray(list)) {
  1271. var i = list.indexOf(listener);
  1272. if (i < 0) return this;
  1273. list.splice(i, 1);
  1274. if (list.length == 0)
  1275. delete this._events[type];
  1276. } else if (this._events[type] === listener) {
  1277. delete this._events[type];
  1278. }
  1279. return this;
  1280. };
  1281. EventEmitter.prototype.removeAllListeners = function(type) {
  1282. // does not use listeners(), so no side effect of creating _events[type]
  1283. if (type && this._events && this._events[type]) this._events[type] = null;
  1284. return this;
  1285. };
  1286. EventEmitter.prototype.listeners = function(type) {
  1287. if (!this._events) this._events = {};
  1288. if (!this._events[type]) this._events[type] = [];
  1289. if (!isArray(this._events[type])) {
  1290. this._events[type] = [this._events[type]];
  1291. }
  1292. return this._events[type];
  1293. };
  1294. });
  1295. require.define("/node_modules/sprintf/package.json", function (require, module, exports, __dirname, __filename) {
  1296. module.exports = {"main":"./lib/sprintf"}
  1297. });
  1298. require.define("/node_modules/sprintf/lib/sprintf.js", function (require, module, exports, __dirname, __filename) {
  1299. /**
  1300. sprintf() for JavaScript 0.7-beta1
  1301. http://www.diveintojavascript.com/projects/javascript-sprintf
  1302. Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
  1303. All rights reserved.
  1304. Redistribution and use in source and binary forms, with or without
  1305. modification, are permitted provided that the following conditions are met:
  1306. * Redistributions of source code must retain the above copyright
  1307. notice, this list of conditions and the following disclaimer.
  1308. * Redistributions in binary form must reproduce the above copyright
  1309. notice, this list of conditions and the following disclaimer in the
  1310. documentation and/or other materials provided with the distribution.
  1311. * Neither the name of sprintf() for JavaScript nor the
  1312. names of its contributors may be used to endorse or promote products
  1313. derived from this software without specific prior written permission.
  1314. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  1315. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  1316. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  1317. DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY
  1318. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  1319. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  1320. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  1321. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1322. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  1323. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1324. Changelog:
  1325. 2010.11.07 - 0.7-beta1-node
  1326. - converted it to a node.js compatible module
  1327. 2010.09.06 - 0.7-beta1
  1328. - features: vsprintf, support for named placeholders
  1329. - enhancements: format cache, reduced global namespace pollution
  1330. 2010.05.22 - 0.6:
  1331. - reverted to 0.4 and fixed the bug regarding the sign of the number 0
  1332. Note:
  1333. Thanks to Raphael Pigulla <raph (at] n3rd [dot) org> (http://www.n3rd.org/)
  1334. who warned me about a bug in 0.5, I discovered that the last update was
  1335. a regress. I appologize for that.
  1336. 2010.05.09 - 0.5:
  1337. - bug fix: 0 is now preceeded with a + sign
  1338. - bug fix: the sign was not at the right position on padded results (Kamal Abdali)
  1339. - switched from GPL to BSD license
  1340. 2007.10.21 - 0.4:
  1341. - unit test and patch (David Baird)
  1342. 2007.09.17 - 0.3:
  1343. - bug fix: no longer throws exception on empty paramenters (Hans Pufal)
  1344. 2007.09.11 - 0.2:
  1345. - feature: added argument swapping
  1346. 2007.04.03 - 0.1:
  1347. - initial release
  1348. **/
  1349. var sprintf = (function() {
  1350. function get_type(variable) {
  1351. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  1352. }
  1353. function str_repeat(input, multiplier) {
  1354. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  1355. return output.join('');
  1356. }
  1357. var str_format = function() {
  1358. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  1359. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  1360. }
  1361. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  1362. };
  1363. str_format.format = function(parse_tree, argv) {
  1364. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  1365. for (i = 0; i < tree_length; i++) {
  1366. node_type = get_type(parse_tree[i]);
  1367. if (node_type === 'string') {
  1368. output.push(parse_tree[i]);
  1369. }
  1370. else if (node_type === 'array') {
  1371. match = parse_tree[i]; // convenience purposes only
  1372. if (match[2]) { // keyword argument
  1373. arg = argv[cursor];
  1374. for (k = 0; k < match[2].length; k++) {
  1375. if (!arg.hasOwnProperty(match[2][k])) {
  1376. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  1377. }
  1378. arg = arg[match[2][k]];
  1379. }
  1380. }
  1381. else if (match[1]) { // positional argument (explicit)
  1382. arg = argv[match[1]];
  1383. }
  1384. else { // positional argument (implicit)
  1385. arg = argv[cursor++];
  1386. }
  1387. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  1388. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  1389. }
  1390. switch (match[8]) {
  1391. case 'b': arg = arg.toString(2); break;
  1392. case 'c': arg = String.fromCharCode(arg); break;
  1393. case 'd': arg = parseInt(arg, 10); break;
  1394. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  1395. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  1396. case 'o': arg = arg.toString(8); break;
  1397. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  1398. case 'u': arg = Math.abs(arg); break;
  1399. case 'x': arg = arg.toString(16); break;
  1400. case 'X': arg = arg.toString(16).toUpperCase(); break;
  1401. }
  1402. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  1403. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  1404. pad_length = match[6] - String(arg).length;
  1405. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  1406. output.push(match[5] ? arg + pad : pad + arg);
  1407. }
  1408. }
  1409. return output.join('');
  1410. };
  1411. str_format.cache = {};
  1412. str_format.parse = function(fmt) {
  1413. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  1414. while (_fmt) {
  1415. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  1416. parse_tree.push(match[0]);
  1417. }
  1418. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  1419. parse_tree.push('%');
  1420. }
  1421. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  1422. if (match[2]) {
  1423. arg_names |= 1;
  1424. var field_list = [], replacement_field = match[2], field_match = [];
  1425. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  1426. field_list.push(field_match[1]);
  1427. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  1428. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  1429. field_list.push(field_match[1]);
  1430. }
  1431. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  1432. field_list.push(field_match[1]);
  1433. }
  1434. else {
  1435. throw('[sprintf] huh?');
  1436. }
  1437. }
  1438. }
  1439. else {
  1440. throw('[sprintf] huh?');
  1441. }
  1442. match[2] = field_list;
  1443. }
  1444. else {
  1445. arg_names |= 2;
  1446. }
  1447. if (arg_names === 3) {
  1448. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  1449. }
  1450. parse_tree.push(match);
  1451. }
  1452. else {
  1453. throw('[sprintf] huh?');
  1454. }
  1455. _fmt = _fmt.substring(match[0].length);
  1456. }
  1457. return parse_tree;
  1458. };
  1459. return str_format;
  1460. })();
  1461. var vsprintf = function(fmt, argv) {
  1462. argv.unshift(fmt);
  1463. return sprintf.apply(null, argv);
  1464. };
  1465. exports.sprintf = sprintf;
  1466. exports.vsprintf = vsprintf;
  1467. });
  1468. require.define("/shred/response.js", function (require, module, exports, __dirname, __filename) {
  1469. // The `Response object` encapsulates a Node.js HTTP response.
  1470. var Content = require("./content")
  1471. , HeaderMixins = require("./mixins/headers")
  1472. , CookieJarLib = require( "cookiejar" )
  1473. , Cookie = CookieJarLib.Cookie
  1474. ;
  1475. // Browser doesn't have zlib.
  1476. var zlib = null;
  1477. try {
  1478. zlib = require('zlib');
  1479. } catch (e) {
  1480. console.warn("no zlib library");
  1481. }
  1482. // Iconv doesn't work in browser
  1483. var Iconv = null;
  1484. try {
  1485. Iconv = require('iconv-lite');
  1486. } catch (e) {
  1487. console.warn("no iconv library");
  1488. }
  1489. // Construct a `Response` object. You should never have to do this directly. The
  1490. // `Request` object handles this, getting the raw response object and passing it
  1491. // in here, along with the request. The callback allows us to stream the response
  1492. // and then use the callback to let the request know when it's ready.
  1493. var Response = function(raw, request, callback) {
  1494. var response = this;
  1495. this._raw = raw;
  1496. // The `._setHeaders` method is "private"; you can't otherwise set headers on
  1497. // the response.
  1498. this._setHeaders.call(this,raw.headers);
  1499. // store any cookies
  1500. if (request.cookieJar && this.getHeader('set-cookie')) {
  1501. var cookieStrings = this.getHeader('set-cookie');
  1502. var cookieObjs = []
  1503. , cookie;
  1504. for (var i = 0; i < cookieStrings.length; i++) {
  1505. var cookieString = cookieStrings[i];
  1506. if (!cookieString) {
  1507. continue;
  1508. }
  1509. if (!cookieString.match(/domain\=/i)) {
  1510. cookieString += '; domain=' + request.host;
  1511. }
  1512. if (!cookieString.match(/path\=/i)) {
  1513. cookieString += '; path=' + request.path;
  1514. }
  1515. try {
  1516. cookie = new Cookie(cookieString);
  1517. if (cookie) {
  1518. cookieObjs.push(cookie);
  1519. }
  1520. } catch (e) {
  1521. console.warn("Tried to set bad cookie: " + cookieString);
  1522. }
  1523. }
  1524. request.cookieJar.setCookies(cookieObjs);
  1525. }
  1526. this.request = request;
  1527. this.client = request.client;
  1528. this.log = this.request.log;
  1529. // Stream the response content entity and fire the callback when we're done.
  1530. // Store the incoming data in a array of Buffers which we concatinate into one
  1531. // buffer at the end. We need to use buffers instead of strings here in order
  1532. // to preserve binary data.
  1533. var chunkBuffers = [];
  1534. var dataLength = 0;
  1535. raw.on("data", function(chunk) {
  1536. chunkBuffers.push(chunk);
  1537. dataLength += chunk.length;
  1538. });
  1539. raw.on("end", function() {
  1540. var body;
  1541. if (typeof Buffer === 'undefined') {
  1542. // Just concatinate into a string
  1543. body = chunkBuffers.join('');
  1544. } else {
  1545. // Initialize new buffer and add the chunks one-at-a-time.
  1546. body = new Buffer(dataLength);
  1547. for (var i = 0, pos = 0; i < chunkBuffers.length; i++) {
  1548. chunkBuffers[i].copy(body, pos);
  1549. pos += chunkBuffers[i].length;
  1550. }
  1551. }
  1552. var setBodyAndFinish = function (body) {
  1553. response._body = new Content({
  1554. body: body,
  1555. type: response.getHeader("Content-Type")
  1556. });
  1557. callback(response);
  1558. }
  1559. if (zlib && response.getHeader("Content-Encoding") === 'gzip'){
  1560. zlib.gunzip(body, function (err, gunzippedBody) {
  1561. if (Iconv && response.request.encoding){
  1562. body = Iconv.fromEncoding(gunzippedBody,response.request.encoding);
  1563. } else {
  1564. body = gunzippedBody.toString();
  1565. }
  1566. setBodyAndFinish(body);
  1567. })
  1568. }
  1569. else{
  1570. if (response.request.encoding){
  1571. body = Iconv.fromEncoding(body,response.request.encoding);
  1572. }
  1573. setBodyAndFinish(body);
  1574. }
  1575. });
  1576. };
  1577. // The `Response` object can be pretty overwhelming to view using the built-in
  1578. // Node.js inspect method. We want to make it a bit more manageable. This
  1579. // probably goes [too far in the other
  1580. // direction](https://github.com/spire-io/shred/issues/2).
  1581. Response.prototype = {
  1582. inspect: function() {
  1583. var response = this;
  1584. var headers = this.format_headers();
  1585. var summary = ["<Shred Response> ", response.status].join(" ")
  1586. return [ summary, "- Headers:", headers].join("\n");
  1587. },
  1588. format_headers: function () {
  1589. var array = []
  1590. var headers = this._headers
  1591. for (var key in headers) {
  1592. if (headers.hasOwnProperty(key)) {
  1593. var value = headers[key]
  1594. array.push("\t" + key + ": " + value);
  1595. }
  1596. }
  1597. return array.join("\n");
  1598. }
  1599. };
  1600. // `Response` object properties, all of which are read-only:
  1601. Object.defineProperties(Response.prototype, {
  1602. // - **status**. The HTTP status code for the response.
  1603. status: {
  1604. get: function() { return this._raw.statusCode; },
  1605. enumerable: true
  1606. },
  1607. // - **content**. The HTTP content entity, if any. Provided as a [content
  1608. // object](./content.html), which will attempt to convert the entity based upon
  1609. // the `content-type` header. The converted value is available as
  1610. // `content.data`. The original raw content entity is available as
  1611. // `content.body`.
  1612. body: {
  1613. get: function() { return this._body; }
  1614. },
  1615. content: {
  1616. get: function() { return this.body; },
  1617. enumerable: true
  1618. },
  1619. // - **isRedirect**. Is the response a redirect? These are responses with 3xx
  1620. // status and a `Location` header.
  1621. isRedirect: {
  1622. get: function() {
  1623. return (this.status>299
  1624. &&this.status<400
  1625. &&this.getHeader("Location"));
  1626. },
  1627. enumerable: true
  1628. },
  1629. // - **isError**. Is the response an error? These are responses with status of
  1630. // 400 or greater.
  1631. isError: {
  1632. get: function() {
  1633. return (this.status === 0 || this.status > 399)
  1634. },
  1635. enumerable: true
  1636. }
  1637. });
  1638. // Add in the [getters for accessing the normalized headers](./headers.js).
  1639. HeaderMixins.getters(Response);
  1640. HeaderMixins.privateSetters(Response);
  1641. // Work around Mozilla bug #608735 [https://bugzil.la/608735], which causes
  1642. // getAllResponseHeaders() to return {} if the response is a CORS request.
  1643. // xhr.getHeader still works correctly.
  1644. var getHeader = Response.prototype.getHeader;
  1645. Response.prototype.getHeader = function (name) {
  1646. return (getHeader.call(this,name) ||
  1647. (typeof this._raw.getHeader === 'function' && this._raw.getHeader(name)));
  1648. };
  1649. module.exports = Response;
  1650. });
  1651. require.define("/shred/content.js", function (require, module, exports, __dirname, __filename) {
  1652. // The purpose of the `Content` object is to abstract away the data conversions
  1653. // to and from raw content entities as strings. For example, you want to be able
  1654. // to pass in a Javascript object and have it be automatically converted into a
  1655. // JSON string if the `content-type` is set to a JSON-based media type.
  1656. // Conversely, you want to be able to transparently get back a Javascript object
  1657. // in the response if the `content-type` is a JSON-based media-type.
  1658. // One limitation of the current implementation is that it [assumes the `charset` is UTF-8](https://github.com/spire-io/shred/issues/5).
  1659. // The `Content` constructor takes an options object, which *must* have either a
  1660. // `body` or `data` property and *may* have a `type` property indicating the
  1661. // media type. If there is no `type` attribute, a default will be inferred.
  1662. var Content = function(options) {
  1663. this.body = options.body;
  1664. this.data = options.data;
  1665. this.type = options.type;
  1666. };
  1667. Content.prototype = {
  1668. // Treat `toString()` as asking for the `content.body`. That is, the raw content entity.
  1669. //
  1670. // toString: function() { return this.body; }
  1671. //
  1672. // Commented out, but I've forgotten why. :/
  1673. };
  1674. // `Content` objects have the following attributes:
  1675. Object.defineProperties(Content.prototype,{
  1676. // - **type**. Typically accessed as `content.type`, reflects the `content-type`
  1677. // header associated with the request or response. If not passed as an options
  1678. // to the constructor or set explicitly, it will infer the type the `data`
  1679. // attribute, if possible, and, failing that, will default to `text/plain`.
  1680. type: {
  1681. get: function() {
  1682. if (this._type) {
  1683. return this._type;
  1684. } else {
  1685. if (this._data) {
  1686. switch(typeof this._data) {
  1687. case "string": return "text/plain";
  1688. case "object": return "application/json";
  1689. }
  1690. }
  1691. }
  1692. return "text/plain";
  1693. },
  1694. set: function(value) {
  1695. this._type = value;
  1696. return this;
  1697. },
  1698. enumerable: true
  1699. },
  1700. // - **data**. Typically accessed as `content.data`, reflects the content entity
  1701. // converted into Javascript data. This can be a string, if the `type` is, say,
  1702. // `text/plain`, but can also be a Javascript object. The conversion applied is
  1703. // based on the `processor` attribute. The `data` attribute can also be set
  1704. // directly, in which case the conversion will be done the other way, to infer
  1705. // the `body` attribute.
  1706. data: {
  1707. get: function() {
  1708. if (this._body) {
  1709. return this.processor.parser(this._body);
  1710. } else {
  1711. return this._data;
  1712. }
  1713. },
  1714. set: function(data) {
  1715. if (this._body&&data) Errors.setDataWithBody(this);
  1716. this._data = data;
  1717. return this;
  1718. },
  1719. enumerable: true
  1720. },
  1721. // - **body**. Typically accessed as `content.body`, reflects the content entity
  1722. // as a UTF-8 string. It is the mirror of the `data` attribute. If you set the
  1723. // `data` attribute, the `body` attribute will be inferred and vice-versa. If
  1724. // you attempt to set both, an exception is raised.
  1725. body: {
  1726. get: function() {
  1727. if (this._data) {
  1728. return this.processor.stringify(this._data);
  1729. } else {
  1730. return this.processor.stringify(this._body);
  1731. }
  1732. },
  1733. set: function(body) {
  1734. if (this._data&&body) Errors.setBodyWithData(this);
  1735. this._body = body;
  1736. return this;
  1737. },
  1738. enumerable: true
  1739. },
  1740. // - **processor**. The functions that will be used to convert to/from `data` and
  1741. // `body` attributes. You can add processors. The two that are built-in are for
  1742. // `text/plain`, which is basically an identity transformation and
  1743. // `application/json` and other JSON-based media types (including custom media
  1744. // types with `+json`). You can add your own processors. See below.
  1745. processor: {
  1746. get: function() {
  1747. var processor = Content.processors[this.type];
  1748. if (processor) {
  1749. return processor;
  1750. } else {
  1751. // Return the first processor that matches any part of the
  1752. // content type. ex: application/vnd.foobar.baz+json will match json.
  1753. var main = this.type.split(";")[0];
  1754. var parts = main.split(/\+|\//);
  1755. for (var i=0, l=parts.length; i < l; i++) {
  1756. processor = Content.processors[parts[i]]
  1757. }
  1758. return processor || {parser:identity,stringify:toString};
  1759. }
  1760. },
  1761. enumerable: true
  1762. },
  1763. // - **length**. Typically accessed as `content.length`, returns the length in
  1764. // bytes of the raw content entity.
  1765. length: {
  1766. get: function() {
  1767. if (typeof Buffer !== 'undefined') {
  1768. return Buffer.byteLength(this.body);
  1769. }
  1770. return this.body.length;
  1771. }
  1772. }
  1773. });
  1774. Content.processors = {};
  1775. // The `registerProcessor` function allows you to add your own processors to
  1776. // convert content entities. Each processor consists of a Javascript object with
  1777. // two properties:
  1778. // - **parser**. The function used to parse a raw content entity and convert it
  1779. // into a Javascript data type.
  1780. // - **stringify**. The function used to convert a Javascript data type into a
  1781. // raw content entity.
  1782. Content.registerProcessor = function(types,processor) {
  1783. // You can pass an array of types that will trigger this processor, or just one.
  1784. // We determine the array via duck-typing here.
  1785. if (types.forEach) {
  1786. types.forEach(function(type) {
  1787. Content.processors[type] = processor;
  1788. });
  1789. } else {
  1790. // If you didn't pass an array, we just use what you pass in.
  1791. Content.processors[types] = processor;
  1792. }
  1793. };
  1794. // Register the identity processor, which is used for text-based media types.
  1795. var identity = function(x) { return x; }
  1796. , toString = function(x) { return x.toString(); }
  1797. Content.registerProcessor(
  1798. ["text/html","text/plain","text"],
  1799. { parser: identity, stringify: toString });
  1800. // Register the JSON processor, which is used for JSON-based media types.
  1801. Content.registerProcessor(
  1802. ["application/json; charset=utf-8","application/json","json"],
  1803. {
  1804. parser: function(string) {
  1805. return JSON.parse(string);
  1806. },
  1807. stringify: function(data) {
  1808. return JSON.stringify(data); }});
  1809. // Error functions are defined separately here in an attempt to make the code
  1810. // easier to read.
  1811. var Errors = {
  1812. setDataWithBody: function(object) {
  1813. throw new Error("Attempt to set data attribute of a content object " +
  1814. "when the body attributes was already set.");
  1815. },
  1816. setBodyWithData: function(object) {
  1817. throw new Error("Attempt to set body attribute of a content object " +
  1818. "when the data attributes was already set.");
  1819. }
  1820. }
  1821. module.exports = Content;
  1822. });
  1823. require.define("/shred/mixins/headers.js", function (require, module, exports, __dirname, __filename) {
  1824. // The header mixins allow you to add HTTP header support to any object. This
  1825. // might seem pointless: why not simply use a hash? The main reason is that, per
  1826. // the [HTTP spec](http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2),
  1827. // headers are case-insensitive. So, for example, `content-type` is the same as
  1828. // `CONTENT-TYPE` which is the same as `Content-Type`. Since there is no way to
  1829. // overload the index operator in Javascript, using a hash to represent the
  1830. // headers means it's possible to have two conflicting values for a single
  1831. // header.
  1832. //
  1833. // The solution to this is to provide explicit methods to set or get headers.
  1834. // This also has the benefit of allowing us to introduce additional variations,
  1835. // including snake case, which we automatically convert to what Matthew King has
  1836. // dubbed "corset case" - the hyphen-separated names with initial caps:
  1837. // `Content-Type`. We use corset-case just in case we're dealing with servers
  1838. // that haven't properly implemented the spec.
  1839. // Convert headers to corset-case. **Example:** `CONTENT-TYPE` will be converted
  1840. // to `Content-Type`.
  1841. var corsetCase = function(string) {
  1842. return string.toLowerCase()
  1843. //.replace("_","-")
  1844. .replace(/(^|-)(\w)/g,
  1845. function(s) { return s.toUpperCase(); });
  1846. };
  1847. // We suspect that `initializeHeaders` was once more complicated ...
  1848. var initializeHeaders = function(object) {
  1849. return {};
  1850. };
  1851. // Access the `_headers` property using lazy initialization. **Warning:** If you
  1852. // mix this into an object that is using the `_headers` property already, you're
  1853. // going to have trouble.
  1854. var $H = function(object) {
  1855. return object._headers||(object._headers=initializeHeaders(object));
  1856. };
  1857. // Hide the implementations as private functions, separate from how we expose them.
  1858. // The "real" `getHeader` function: get the header after normalizing the name.
  1859. var getHeader = function(object,name) {
  1860. return $H(object)[corsetCase(name)];
  1861. };
  1862. // The "real" `getHeader` function: get one or more headers, or all of them
  1863. // if you don't ask for any specifics.
  1864. var getHeaders = function(object,names) {
  1865. var keys = (names && names.length>0) ? names : Object.keys($H(object));
  1866. var hash = keys.reduce(function(hash,key) {
  1867. hash[key] = getHeader(object,key);
  1868. return hash;
  1869. },{});
  1870. // Freeze the resulting hash so you don't mistakenly think you're modifying
  1871. // the real headers.
  1872. Object.freeze(hash);
  1873. return hash;
  1874. };
  1875. // The "real" `setHeader` function: set a header, after normalizing the name.
  1876. var setHeader = function(object,name,value) {
  1877. $H(object)[corsetCase(name)] = value;
  1878. return object;
  1879. };
  1880. // The "real" `setHeaders` function: set multiple headers based on a hash.
  1881. var setHeaders = function(object,hash) {
  1882. for( var key in hash ) { setHeader(object,key,hash[key]); };
  1883. return this;
  1884. };
  1885. // Here's where we actually bind the functionality to an object. These mixins work by
  1886. // exposing mixin functions. Each function mixes in a specific batch of features.
  1887. module.exports = {
  1888. // Add getters.
  1889. getters: function(constructor) {
  1890. constructor.prototype.getHeader = function(name) { return getHeader(this,name); };
  1891. constructor.prototype.getHeaders = function() { return getHeaders(this,arguments); };
  1892. },
  1893. // Add setters but as "private" methods.
  1894. privateSetters: function(constructor) {
  1895. constructor.prototype._setHeader = function(key,value) { return setHeader(this,key,value); };
  1896. constructor.prototype._setHeaders = function(hash) { return setHeaders(this,hash); };
  1897. },
  1898. // Add setters.
  1899. setters: function(constructor) {
  1900. constructor.prototype.setHeader = function(key,value) { return setHeader(this,key,value); };
  1901. constructor.prototype.setHeaders = function(hash) { return setHeaders(this,hash); };
  1902. },
  1903. // Add both getters and setters.
  1904. gettersAndSetters: function(constructor) {
  1905. constructor.prototype.getHeader = function(name) { return getHeader(this,name); };
  1906. constructor.prototype.getHeaders = function() { return getHeaders(this,arguments); };
  1907. constructor.prototype.setHeader = function(key,value) { return setHeader(this,key,value); };
  1908. constructor.prototype.setHeaders = function(hash) { return setHeaders(this,hash); };
  1909. },
  1910. };
  1911. });
  1912. require.define("/node_modules/iconv-lite/package.json", function (require, module, exports, __dirname, __filename) {
  1913. module.exports = {}
  1914. });
  1915. require.define("/node_modules/iconv-lite/index.js", function (require, module, exports, __dirname, __filename) {
  1916. // Module exports
  1917. var iconv = module.exports = {
  1918. toEncoding: function(str, encoding) {
  1919. return iconv.getCodec(encoding).toEncoding(str);
  1920. },
  1921. fromEncoding: function(buf, encoding) {
  1922. return iconv.getCodec(encoding).fromEncoding(buf);
  1923. },
  1924. defaultCharUnicode: '�',
  1925. defaultCharSingleByte: '?',
  1926. // Get correct codec for given encoding.
  1927. getCodec: function(encoding) {
  1928. var enc = encoding || "utf8";
  1929. var codecOptions = undefined;
  1930. while (1) {
  1931. if (getType(enc) === "String")
  1932. enc = enc.replace(/[- ]/g, "").toLowerCase();
  1933. var codec = iconv.encodings[enc];
  1934. var type = getType(codec);
  1935. if (type === "String") {
  1936. // Link to other encoding.
  1937. codecOptions = {originalEncoding: enc};
  1938. enc = codec;
  1939. }
  1940. else if (type === "Object" && codec.type != undefined) {
  1941. // Options for other encoding.
  1942. codecOptions = codec;
  1943. enc = codec.type;
  1944. }
  1945. else if (type === "Function")
  1946. // Codec itself.
  1947. return codec(codecOptions);
  1948. else
  1949. throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
  1950. }
  1951. },
  1952. // Define basic encodings
  1953. encodings: {
  1954. internal: function(options) {
  1955. return {
  1956. toEncoding: function(str) {
  1957. return new Buffer(ensureString(str), options.originalEncoding);
  1958. },
  1959. fromEncoding: function(buf) {
  1960. return ensureBuffer(buf).toString(options.originalEncoding);
  1961. }
  1962. };
  1963. },
  1964. utf8: "internal",
  1965. ucs2: "internal",
  1966. binary: "internal",
  1967. ascii: "internal",
  1968. base64: "internal",
  1969. // Codepage single-byte encodings.
  1970. singlebyte: function(options) {
  1971. // Prepare chars if needed
  1972. if (!options.chars || (options.chars.length !== 128 && options.chars.length !== 256))
  1973. throw new Error("Encoding '"+options.type+"' has incorrect 'chars' (must be of len 128 or 256)");
  1974. if (options.chars.length === 128)
  1975. options.chars = asciiString + options.chars;
  1976. if (!options.charsBuf) {
  1977. options.charsBuf = new Buffer(options.chars, 'ucs2');
  1978. }
  1979. if (!options.revCharsBuf) {
  1980. options.revCharsBuf = new Buffer(65536);
  1981. var defChar = iconv.defaultCharSingleByte.charCodeAt(0);
  1982. for (var i = 0; i < options.revCharsBuf.length; i++)
  1983. options.revCharsBuf[i] = defChar;
  1984. for (var i = 0; i < options.chars.length; i++)
  1985. options.revCharsBuf[options.chars.charCodeAt(i)] = i;
  1986. }
  1987. return {
  1988. toEncoding: function(str) {
  1989. str = ensureString(str);
  1990. var buf = new Buffer(str.length);
  1991. var revCharsBuf = options.revCharsBuf;
  1992. for (var i = 0; i < str.length; i++)
  1993. buf[i] = revCharsBuf[str.charCodeAt(i)];
  1994. return buf;
  1995. },
  1996. fromEncoding: function(buf) {
  1997. buf = ensureBuffer(buf);
  1998. // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
  1999. var charsBuf = options.charsBuf;
  2000. var newBuf = new Buffer(buf.length*2);
  2001. var idx1 = 0, idx2 = 0;
  2002. for (var i = 0, _len = buf.length; i < _len; i++) {
  2003. idx1 = buf[i]*2; idx2 = i*2;
  2004. newBuf[idx2] = charsBuf[idx1];
  2005. newBuf[idx2+1] = charsBuf[idx1+1];
  2006. }
  2007. return newBuf.toString('ucs2');
  2008. }
  2009. };
  2010. },
  2011. // Codepage double-byte encodings.
  2012. table: function(options) {
  2013. var table = options.table, key, revCharsTable = options.revCharsTable;
  2014. if (!table) {
  2015. throw new Error("Encoding '" + options.type +"' has incorect 'table' option");
  2016. }
  2017. if(!revCharsTable) {
  2018. revCharsTable = options.revCharsTable = {};
  2019. for (key in table) {
  2020. revCharsTable[table[key]] = parseInt(key);
  2021. }
  2022. }
  2023. return {
  2024. toEncoding: function(str) {
  2025. str = ensureString(str);
  2026. var strLen = str.length;
  2027. var bufLen = strLen;
  2028. for (var i = 0; i < strLen; i++)
  2029. if (str.charCodeAt(i) >> 7)
  2030. bufLen++;
  2031. var newBuf = new Buffer(bufLen), gbkcode, unicode,
  2032. defaultChar = revCharsTable[iconv.defaultCharUnicode.charCodeAt(0)];
  2033. for (var i = 0, j = 0; i < strLen; i++) {
  2034. unicode = str.charCodeAt(i);
  2035. if (unicode >> 7) {
  2036. gbkcode = revCharsTable[unicode] || defaultChar;
  2037. newBuf[j++] = gbkcode >> 8; //high byte;
  2038. newBuf[j++] = gbkcode & 0xFF; //low byte
  2039. } else {//ascii
  2040. newBuf[j++] = unicode;
  2041. }
  2042. }
  2043. return newBuf;
  2044. },
  2045. fromEncoding: function(buf) {
  2046. buf = ensureBuffer(buf);
  2047. var bufLen = buf.length, strLen = 0;
  2048. for (var i = 0; i < bufLen; i++) {
  2049. strLen++;
  2050. if (buf[i] & 0x80) //the high bit is 1, so this byte is gbkcode's high byte.skip next byte
  2051. i++;
  2052. }
  2053. var newBuf = new Buffer(strLen*2), unicode, gbkcode,
  2054. defaultChar = iconv.defaultCharUnicode.charCodeAt(0);
  2055. for (var i = 0, j = 0; i < bufLen; i++, j+=2) {
  2056. gbkcode = buf[i];
  2057. if (gbkcode & 0x80) {
  2058. gbkcode = (gbkcode << 8) + buf[++i];
  2059. unicode = table[gbkcode] || defaultChar;
  2060. } else {
  2061. unicode = gbkcode;
  2062. }
  2063. newBuf[j] = unicode & 0xFF; //low byte
  2064. newBuf[j+1] = unicode >> 8; //high byte
  2065. }
  2066. return newBuf.toString('ucs2');
  2067. }
  2068. }
  2069. }
  2070. }
  2071. };
  2072. // Add aliases to convert functions
  2073. iconv.encode = iconv.toEncoding;
  2074. iconv.decode = iconv.fromEncoding;
  2075. // Load other encodings from files in /encodings dir.
  2076. var encodingsDir = __dirname+"/encodings/",
  2077. fs = require('fs');
  2078. fs.readdirSync(encodingsDir).forEach(function(file) {
  2079. if(fs.statSync(encodingsDir + file).isDirectory()) return;
  2080. var encodings = require(encodingsDir + file)
  2081. for (var key in encodings)
  2082. iconv.encodings[key] = encodings[key]
  2083. });
  2084. // Utilities
  2085. 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'+
  2086. ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f';
  2087. var ensureBuffer = function(buf) {
  2088. buf = buf || new Buffer(0);
  2089. return (buf instanceof Buffer) ? buf : new Buffer(buf.toString(), "utf8");
  2090. }
  2091. var ensureString = function(str) {
  2092. str = str || "";
  2093. return (str instanceof String) ? str : str.toString((str instanceof Buffer) ? 'utf8' : undefined);
  2094. }
  2095. var getType = function(obj) {
  2096. return Object.prototype.toString.call(obj).slice(8, -1);
  2097. }
  2098. });
  2099. require.define("/node_modules/http-browserify/package.json", function (require, module, exports, __dirname, __filename) {
  2100. module.exports = {"main":"index.js","browserify":"browser.js"}
  2101. });
  2102. require.define("/node_modules/http-browserify/browser.js", function (require, module, exports, __dirname, __filename) {
  2103. var http = module.exports;
  2104. var EventEmitter = require('events').EventEmitter;
  2105. var Request = require('./lib/request');
  2106. http.request = function (params, cb) {
  2107. if (!params) params = {};
  2108. if (!params.host) params.host = window.location.host.split(':')[0];
  2109. if (!params.port) params.port = window.location.port;
  2110. var req = new Request(new xhrHttp, params);
  2111. if (cb) req.on('response', cb);
  2112. return req;
  2113. };
  2114. http.get = function (params, cb) {
  2115. params.method = 'GET';
  2116. var req = http.request(params, cb);
  2117. req.end();
  2118. return req;
  2119. };
  2120. var xhrHttp = (function () {
  2121. if (typeof window === 'undefined') {
  2122. throw new Error('no window object present');
  2123. }
  2124. else if (window.XMLHttpRequest) {
  2125. return window.XMLHttpRequest;
  2126. }
  2127. else if (window.ActiveXObject) {
  2128. var axs = [
  2129. 'Msxml2.XMLHTTP.6.0',
  2130. 'Msxml2.XMLHTTP.3.0',
  2131. 'Microsoft.XMLHTTP'
  2132. ];
  2133. for (var i = 0; i < axs.length; i++) {
  2134. try {
  2135. var ax = new(window.ActiveXObject)(axs[i]);
  2136. return function () {
  2137. if (ax) {
  2138. var ax_ = ax;
  2139. ax = null;
  2140. return ax_;
  2141. }
  2142. else {
  2143. return new(window.ActiveXObject)(axs[i]);
  2144. }
  2145. };
  2146. }
  2147. catch (e) {}
  2148. }
  2149. throw new Error('ajax not supported in this browser')
  2150. }
  2151. else {
  2152. throw new Error('ajax not supported in this browser');
  2153. }
  2154. })();
  2155. http.STATUS_CODES = {
  2156. 100 : 'Continue',
  2157. 101 : 'Switching Protocols',
  2158. 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
  2159. 200 : 'OK',
  2160. 201 : 'Created',
  2161. 202 : 'Accepted',
  2162. 203 : 'Non-Authoritative Information',
  2163. 204 : 'No Content',
  2164. 205 : 'Reset Content',
  2165. 206 : 'Partial Content',
  2166. 207 : 'Multi-Status', // RFC 4918
  2167. 300 : 'Multiple Choices',
  2168. 301 : 'Moved Permanently',
  2169. 302 : 'Moved Temporarily',
  2170. 303 : 'See Other',
  2171. 304 : 'Not Modified',
  2172. 305 : 'Use Proxy',
  2173. 307 : 'Temporary Redirect',
  2174. 400 : 'Bad Request',
  2175. 401 : 'Unauthorized',
  2176. 402 : 'Payment Required',
  2177. 403 : 'Forbidden',
  2178. 404 : 'Not Found',
  2179. 405 : 'Method Not Allowed',
  2180. 406 : 'Not Acceptable',
  2181. 407 : 'Proxy Authentication Required',
  2182. 408 : 'Request Time-out',
  2183. 409 : 'Conflict',
  2184. 410 : 'Gone',
  2185. 411 : 'Length Required',
  2186. 412 : 'Precondition Failed',
  2187. 413 : 'Request Entity Too Large',
  2188. 414 : 'Request-URI Too Large',
  2189. 415 : 'Unsupported Media Type',
  2190. 416 : 'Requested Range Not Satisfiable',
  2191. 417 : 'Expectation Failed',
  2192. 418 : 'I\'m a teapot', // RFC 2324
  2193. 422 : 'Unprocessable Entity', // RFC 4918
  2194. 423 : 'Locked', // RFC 4918
  2195. 424 : 'Failed Dependency', // RFC 4918
  2196. 425 : 'Unordered Collection', // RFC 4918
  2197. 426 : 'Upgrade Required', // RFC 2817
  2198. 500 : 'Internal Server Error',
  2199. 501 : 'Not Implemented',
  2200. 502 : 'Bad Gateway',
  2201. 503 : 'Service Unavailable',
  2202. 504 : 'Gateway Time-out',
  2203. 505 : 'HTTP Version not supported',
  2204. 506 : 'Variant Also Negotiates', // RFC 2295
  2205. 507 : 'Insufficient Storage', // RFC 4918
  2206. 509 : 'Bandwidth Limit Exceeded',
  2207. 510 : 'Not Extended' // RFC 2774
  2208. };
  2209. });
  2210. require.define("/node_modules/http-browserify/lib/request.js", function (require, module, exports, __dirname, __filename) {
  2211. var EventEmitter = require('events').EventEmitter;
  2212. var Response = require('./response');
  2213. var isSafeHeader = require('./isSafeHeader');
  2214. var Request = module.exports = function (xhr, params) {
  2215. var self = this;
  2216. self.xhr = xhr;
  2217. self.body = '';
  2218. var uri = params.host + ':' + params.port + (params.path || '/');
  2219. xhr.open(
  2220. params.method || 'GET',
  2221. (params.scheme || 'http') + '://' + uri,
  2222. true
  2223. );
  2224. if (params.headers) {
  2225. Object.keys(params.headers).forEach(function (key) {
  2226. if (!isSafeHeader(key)) return;
  2227. var value = params.headers[key];
  2228. if (Array.isArray(value)) {
  2229. value.forEach(function (v) {
  2230. xhr.setRequestHeader(key, v);
  2231. });
  2232. }
  2233. else xhr.setRequestHeader(key, value)
  2234. });
  2235. }
  2236. var res = new Response(xhr);
  2237. res.on('ready', function () {
  2238. self.emit('response', res);
  2239. });
  2240. xhr.onreadystatechange = function () {
  2241. res.handle(xhr);
  2242. };
  2243. };
  2244. Request.prototype = new EventEmitter;
  2245. Request.prototype.setHeader = function (key, value) {
  2246. if ((Array.isArray && Array.isArray(value))
  2247. || value instanceof Array) {
  2248. for (var i = 0; i < value.length; i++) {
  2249. this.xhr.setRequestHeader(key, value[i]);
  2250. }
  2251. }
  2252. else {
  2253. this.xhr.setRequestHeader(key, value);
  2254. }
  2255. };
  2256. Request.prototype.write = function (s) {
  2257. this.body += s;
  2258. };
  2259. Request.prototype.end = function (s) {
  2260. if (s !== undefined) this.write(s);
  2261. this.xhr.send(this.body);
  2262. };
  2263. });
  2264. require.define("/node_modules/http-browserify/lib/response.js", function (require, module, exports, __dirname, __filename) {
  2265. var EventEmitter = require('events').EventEmitter;
  2266. var isSafeHeader = require('./isSafeHeader');
  2267. var Response = module.exports = function (xhr) {
  2268. this.xhr = xhr;
  2269. this.offset = 0;
  2270. };
  2271. Response.prototype = new EventEmitter;
  2272. var capable = {
  2273. streaming : true,
  2274. status2 : true
  2275. };
  2276. function parseHeaders (xhr) {
  2277. var lines = xhr.getAllResponseHeaders().split(/\r?\n/);
  2278. var headers = {};
  2279. for (var i = 0; i < lines.length; i++) {
  2280. var line = lines[i];
  2281. if (line === '') continue;
  2282. var m = line.match(/^([^:]+):\s*(.*)/);
  2283. if (m) {
  2284. var key = m[1].toLowerCase(), value = m[2];
  2285. if (headers[key] !== undefined) {
  2286. if ((Array.isArray && Array.isArray(headers[key]))
  2287. || headers[key] instanceof Array) {
  2288. headers[key].push(value);
  2289. }
  2290. else {
  2291. headers[key] = [ headers[key], value ];
  2292. }
  2293. }
  2294. else {
  2295. headers[key] = value;
  2296. }
  2297. }
  2298. else {
  2299. headers[line] = true;
  2300. }
  2301. }
  2302. return headers;
  2303. }
  2304. Response.prototype.getHeader = function (key) {
  2305. var header = this.headers ? this.headers[key.toLowerCase()] : null;
  2306. if (header) return header;
  2307. // Work around Mozilla bug #608735 [https://bugzil.la/608735], which causes
  2308. // getAllResponseHeaders() to return {} if the response is a CORS request.
  2309. // xhr.getHeader still works correctly.
  2310. if (isSafeHeader(key)) {
  2311. return this.xhr.getResponseHeader(key);
  2312. }
  2313. return null;
  2314. };
  2315. Response.prototype.handle = function () {
  2316. var xhr = this.xhr;
  2317. if (xhr.readyState === 2 && capable.status2) {
  2318. try {
  2319. this.statusCode = xhr.status;
  2320. this.headers = parseHeaders(xhr);
  2321. }
  2322. catch (err) {
  2323. capable.status2 = false;
  2324. }
  2325. if (capable.status2) {
  2326. this.emit('ready');
  2327. }
  2328. }
  2329. else if (capable.streaming && xhr.readyState === 3) {
  2330. try {
  2331. if (!this.statusCode) {
  2332. this.statusCode = xhr.status;
  2333. this.headers = parseHeaders(xhr);
  2334. this.emit('ready');
  2335. }
  2336. }
  2337. catch (err) {}
  2338. try {
  2339. this.write();
  2340. }
  2341. catch (err) {
  2342. capable.streaming = false;
  2343. }
  2344. }
  2345. else if (xhr.readyState === 4) {
  2346. if (!this.statusCode) {
  2347. this.statusCode = xhr.status;
  2348. this.emit('ready');
  2349. }
  2350. this.write();
  2351. if (xhr.error) {
  2352. this.emit('error', xhr.responseText);
  2353. }
  2354. else this.emit('end');
  2355. }
  2356. };
  2357. Response.prototype.write = function () {
  2358. var xhr = this.xhr;
  2359. if (xhr.responseText.length > this.offset) {
  2360. this.emit('data', xhr.responseText.slice(this.offset));
  2361. this.offset = xhr.responseText.length;
  2362. }
  2363. };
  2364. });
  2365. require.define("/node_modules/http-browserify/lib/isSafeHeader.js", function (require, module, exports, __dirname, __filename) {
  2366. // Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html
  2367. var unsafeHeaders = [
  2368. "accept-charset",
  2369. "accept-encoding",
  2370. "access-control-request-headers",
  2371. "access-control-request-method",
  2372. "connection",
  2373. "content-length",
  2374. "cookie",
  2375. "cookie2",
  2376. "content-transfer-encoding",
  2377. "date",
  2378. "expect",
  2379. "host",
  2380. "keep-alive",
  2381. "origin",
  2382. "referer",
  2383. "set-cookie",
  2384. "te",
  2385. "trailer",
  2386. "transfer-encoding",
  2387. "upgrade",
  2388. "user-agent",
  2389. "via"
  2390. ];
  2391. module.exports = function (headerName) {
  2392. if (!headerName) return false;
  2393. return (unsafeHeaders.indexOf(headerName.toLowerCase()) === -1)
  2394. };
  2395. });
  2396. require.alias("http-browserify", "/node_modules/http");
  2397. require.alias("http-browserify", "/node_modules/https");