cron.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.cron=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var CronDate;
  3. var exports;
  4. try {
  5. CronDate = require("time").Date;
  6. exports = module.exports;
  7. } catch (e) {
  8. CronDate = Date;
  9. }
  10. function CronTime(source, zone) {
  11. this.source = source;
  12. this.zone = zone;
  13. this.second = {};
  14. this.minute = {};
  15. this.hour = {};
  16. this.dayOfWeek = {};
  17. this.dayOfMonth = {};
  18. this.month = {};
  19. if ((this.source instanceof Date) || (this.source instanceof CronDate)) {
  20. this.source = new CronDate(this.source);
  21. this.realDate = true;
  22. } else {
  23. this._parse();
  24. }
  25. }
  26. CronTime.map = ['second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
  27. CronTime.constraints = [
  28. [0, 59],
  29. [0, 59],
  30. [0, 23],
  31. [1, 31],
  32. [0, 11],
  33. [0, 6]
  34. ];
  35. CronTime.parseDefaults = ['0', '*', '*', '*', '*', '*'];
  36. CronTime.aliases = {
  37. jan: 0,
  38. feb: 1,
  39. mar: 2,
  40. apr: 3,
  41. may: 4,
  42. jun: 5,
  43. jul: 6,
  44. aug: 7,
  45. sep: 8,
  46. oct: 9,
  47. nov: 10,
  48. dec: 11,
  49. sun: 0,
  50. mon: 1,
  51. tue: 2,
  52. wed: 3,
  53. thu: 4,
  54. fri: 5,
  55. sat: 6
  56. };
  57. CronTime.prototype = {
  58. /**
  59. * calculates the next send time
  60. */
  61. sendAt: function() {
  62. var date = (this.source instanceof CronDate) ? this.source : new CronDate();
  63. if (this.zone && date.setTimezone)
  64. date.setTimezone(this.zone);
  65. //add 1 second so next time isn't now (can cause timeout to be 0)
  66. if (!(this.realDate)) date.setSeconds(date.getSeconds() + 1);
  67. if (this.realDate) {
  68. return date;
  69. }
  70. return this._getNextDateFrom(date);
  71. },
  72. /**
  73. * Get the number of milliseconds in the future at which to fire our callbacks.
  74. */
  75. getTimeout: function() {
  76. return Math.max(-1, this.sendAt().getTime() - CronDate.now());
  77. },
  78. /**
  79. * writes out a cron string
  80. */
  81. toString: function() {
  82. return this.toJSON().join(' ');
  83. },
  84. /**
  85. * Json representation of the parsed cron syntax.
  86. */
  87. toJSON: function() {
  88. return [
  89. this._wcOrAll('second'),
  90. this._wcOrAll('minute'),
  91. this._wcOrAll('hour'),
  92. this._wcOrAll('dayOfMonth'),
  93. this._wcOrAll('month'),
  94. this._wcOrAll('dayOfWeek')
  95. ];
  96. },
  97. /**
  98. * get next date that matches parsed cron time
  99. */
  100. _getNextDateFrom: function(start) {
  101. var date = new CronDate(start);
  102. //console.log("d: " + date);
  103. if (this.zone && date.setTimezone)
  104. date.setTimezone(start.getTimezone());
  105. if (this.realDate && start < new Date())
  106. console.log("WARNING: Date in past. Will never be fired.");
  107. if (this.realDate) return date;
  108. //sanity check
  109. //var i = 1000;
  110. var x = 0;
  111. while (1) {
  112. x++;
  113. var diff = date - start;
  114. console.log(x)
  115. if (!(date.getMonth() in this.month)) {
  116. date.setMonth(date.getMonth() + 1);
  117. date.setDate(1);
  118. date.setHours(0);
  119. date.setMinutes(0);
  120. continue;
  121. }
  122. if (!(date.getDate() in this.dayOfMonth)) {
  123. date.setDate(date.getDate() + 1);
  124. date.setHours(0);
  125. date.setMinutes(0);
  126. continue;
  127. }
  128. if (!(date.getDay() in this.dayOfWeek)) {
  129. date.setDate(date.getDate() + 1);
  130. date.setHours(0);
  131. date.setMinutes(0);
  132. continue;
  133. }
  134. if (!(date.getHours() in this.hour)) {
  135. date.setHours(date.getHours() == 23 && diff > 24 * 60 * 60 * 1000 ? 0 : date.getHours() + 1);
  136. date.setMinutes(0);
  137. continue;
  138. }
  139. if (!(date.getMinutes() in this.minute)) {
  140. date.setMinutes(date.getMinutes() == 59 && diff > 60 * 60 * 1000 ? 0 : date.getMinutes() + 1);
  141. date.setSeconds(0);
  142. continue;
  143. }
  144. if (!(date.getSeconds() in this.second)) {
  145. date.setSeconds(date.getSeconds() == 59 && diff > 60 * 1000 ? 0 : date.getSeconds() + 1);
  146. continue;
  147. }
  148. break;
  149. }
  150. return date;
  151. },
  152. /**
  153. * wildcard, or all params in array (for to string)
  154. */
  155. _wcOrAll: function(type) {
  156. if (this._hasAll(type)) return '*';
  157. var all = [];
  158. for (var time in this[type]) {
  159. all.push(time);
  160. }
  161. return all.join(',');
  162. },
  163. /**
  164. */
  165. _hasAll: function(type) {
  166. var constrain = CronTime.constraints[CronTime.map.indexOf(type)];
  167. for (var i = constrain[0], n = constrain[1]; i < n; i++) {
  168. if (!(i in this[type])) return false;
  169. }
  170. return true;
  171. },
  172. /**
  173. * Parse the cron syntax.
  174. */
  175. _parse: function() {
  176. var aliases = CronTime.aliases,
  177. source = this.source.replace(/[a-z]{1,3}/ig, function(alias) {
  178. alias = alias.toLowerCase();
  179. if (alias in aliases) {
  180. return aliases[alias];
  181. }
  182. throw new Error('Unknown alias: ' + alias);
  183. }),
  184. split = source.replace(/^\s\s*|\s\s*$/g, '').split(/\s+/),
  185. cur, i = 0,
  186. len = CronTime.map.length;
  187. for (; i < CronTime.map.length; i++) {
  188. // If the split source string doesn't contain all digits,
  189. // assume defaults for first n missing digits.
  190. // This adds support for 5-digit standard cron syntax
  191. cur = split[i - (len - split.length)] || CronTime.parseDefaults[i];
  192. this._parseField(cur, CronTime.map[i], CronTime.constraints[i]);
  193. }
  194. },
  195. /**
  196. * Parse a field from the cron syntax.
  197. */
  198. _parseField: function(field, type, constraints) {
  199. //var rangePattern = /^(\*)(?:\/(\d+))?$|(\d+)(?:-(\d+))?(?:\/(\d+))?(?:,|$)/g
  200. var rangePattern = /^(\d+)(?:-(\d+))?(?:\/(\d+))?$/g,
  201. typeObj = this[type],
  202. diff, pointer,
  203. low = constraints[0],
  204. high = constraints[1];
  205. // * is a shortcut to [lower-upper] range
  206. field = field.replace(/\*/g, low + '-' + high);
  207. //commas separate information, so split based on those
  208. var allRanges = field.split(',');
  209. for (var i = 0; i < allRanges.length; i++) {
  210. if (allRanges[i].match(rangePattern)) {
  211. allRanges[i].replace(rangePattern, function($0, lower, upper, step) {
  212. step = parseInt(step) || 1;
  213. // Positive integer higher than constraints[0]
  214. lower = Math.max(low, ~~Math.abs(lower));
  215. // Positive integer lower than constraints[1]
  216. upper = upper ? Math.min(high, ~~Math.abs(upper)) : lower;
  217. // Count from the lower barrier to the upper
  218. pointer = lower;
  219. do {
  220. typeObj[pointer] = true
  221. pointer += step;
  222. } while (pointer <= upper);
  223. });
  224. } else {
  225. throw new Error('Field (' + field + ') cannot be parsed');
  226. }
  227. }
  228. }
  229. };
  230. function CronJob(cronTime, onTick, onComplete, start, timeZone, context) {
  231. if (typeof cronTime != "string" && arguments.length == 1) {
  232. //crontime is an object...
  233. onTick = cronTime.onTick;
  234. onComplete = cronTime.onComplete;
  235. context = cronTime.context;
  236. start = cronTime.start;
  237. timeZone = cronTime.timeZone;
  238. cronTime = cronTime.cronTime;
  239. }
  240. if (timeZone && !(CronDate.prototype.setTimezone)) console.log('You specified a Timezone but have not included the `time` module. Timezone functionality is disabled. Please install the `time` module to use Timezones in your application.');
  241. this.context = (context || this);
  242. this._callbacks = [];
  243. this.onComplete = onComplete;
  244. this.cronTime = new CronTime(cronTime, timeZone);
  245. this.addCallback(onTick);
  246. if (start) this.start();
  247. return this;
  248. }
  249. CronJob.prototype = {
  250. /**
  251. * Add a method to fire onTick
  252. */
  253. addCallback: function(callback) {
  254. //only functions
  255. if (typeof callback == 'function') this._callbacks.push(callback);
  256. },
  257. /**
  258. * Fire all callbacks registered.
  259. */
  260. _callback: function() {
  261. for (var i = (this._callbacks.length - 1); i >= 0; i--) {
  262. //send this so the callback can call this.stop();
  263. this._callbacks[i].call(this.context, this.onComplete);
  264. }
  265. },
  266. /**
  267. * Manually set the time of a job
  268. */
  269. setTime: function(time) {
  270. if (!(time instanceof CronTime)) throw '\'time\' must be an instance of CronTime.';
  271. this.stop();
  272. this.cronTime = time;
  273. },
  274. /**
  275. * Return the next scheduled date for a job
  276. */
  277. nextDate: function() {
  278. return this.cronTime.sendAt();
  279. },
  280. /**
  281. * Start the cronjob.
  282. */
  283. start: function() {
  284. if (this.running) return;
  285. var MAXDELAY = 2147483647; // The maximum number of milliseconds setTimeout will wait.
  286. var self = this;
  287. var timeout = this.cronTime.getTimeout();
  288. var remaining = 0;
  289. if (this.cronTime.realDate) this.runOnce = true;
  290. // The callback wrapper checks if it needs to sleep another period or not
  291. // and does the real callback logic when it's time.
  292. function callbackWrapper() {
  293. // If there is sleep time remaining, calculate how long and go to sleep
  294. // again. This processing might make us miss the deadline by a few ms
  295. // times the number of sleep sessions. Given a MAXDELAY of almost a
  296. // month, this should be no issue.
  297. if (remaining) {
  298. if (remaining > MAXDELAY) {
  299. remaining -= MAXDELAY;
  300. timeout = MAXDELAY;
  301. } else {
  302. timeout = remaining;
  303. remaining = 0;
  304. }
  305. self._timeout = setTimeout(callbackWrapper, timeout);
  306. } else {
  307. // We have arrived at the correct point in time.
  308. self.running = false;
  309. //start before calling back so the callbacks have the ability to stop the cron job
  310. if (!(self.runOnce)) self.start();
  311. self._callback();
  312. }
  313. }
  314. if (timeout >= 0) {
  315. this.running = true;
  316. // Don't try to sleep more than MAXDELAY ms at a time.
  317. if (timeout > MAXDELAY) {
  318. remaining = timeout - MAXDELAY;
  319. timeout = MAXDELAY;
  320. }
  321. this._timeout = setTimeout(callbackWrapper, timeout);
  322. } else {
  323. this.stop();
  324. }
  325. },
  326. /**
  327. * Stop the cronjob.
  328. */
  329. stop: function() {
  330. clearTimeout(this._timeout);
  331. this.running = false;
  332. if (this.onComplete) this.onComplete();
  333. }
  334. };
  335. if (exports) {
  336. exports.job = function(cronTime, onTick, onComplete) {
  337. return new CronJob(cronTime, onTick, onComplete);
  338. }
  339. exports.time = function(cronTime, timeZone) {
  340. return new CronTime(cronTime, timeZone);
  341. }
  342. exports.sendAt = function(cronTime) {
  343. return exports.time(cronTime).sendAt();
  344. }
  345. exports.timeout = function(cronTime) {
  346. return exports.time(cronTime).getTimeout();
  347. }
  348. exports.CronJob = CronJob;
  349. exports.CronTime = CronTime;
  350. }
  351. },{"time":2}],2:[function(require,module,exports){
  352. (function (process){
  353. /**
  354. * Module dependencies.
  355. */
  356. var debug = require('debug')('time')
  357. , fs = require('fs')
  358. , path = require('path')
  359. , bindings = require('bindings')('time.node')
  360. , MILLIS_PER_SECOND = 1000
  361. , DAYS_OF_WEEK = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
  362. , MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December']
  363. , TZ_BLACKLIST = [ 'SystemV', 'Etc' ];
  364. /**
  365. * Extends a "Date" constructor with node-time's extensions.
  366. * By default, `time.Date` is extended with this function.
  367. * If you want the global your your module-specific Date to be extended,
  368. * then invoke this function on the Date constructor.
  369. */
  370. exports = module.exports = function (Date) {
  371. debug('extending Date constructor');
  372. var p = Date.prototype;
  373. p.getTimezone = getTimezone;
  374. p.setTimezone = setTimezone;
  375. p.getTimezoneAbbr = getTimezoneAbbr;
  376. return exports;
  377. }
  378. /**
  379. * The initial timezone of the process. This env var may initially be undefined,
  380. * in which case node-time will attempt to resolve and set the variable.
  381. */
  382. exports.currentTimezone = process.env.TZ;
  383. /**
  384. * Export the raw functions from the bindings.
  385. */
  386. exports.time = bindings.time;
  387. exports.localtime = bindings.localtime;
  388. exports.mktime = bindings.mktime;
  389. /**
  390. * A "hack" of sorts to force getting our own Date instance.
  391. * Otherwise, in normal cases, the global Natives are shared between
  392. * contexts (not what we want)...
  393. */
  394. var _Date = process.env.NODE_MODULE_CONTEXTS
  395. ? Date
  396. : require('vm').runInNewContext("Date");
  397. /**
  398. * Add the node-time extensions (setTimezone(), etc.)
  399. */
  400. exports(_Date);
  401. /**
  402. * During startup, we synchronously attempt to determine the location of the
  403. * timezone dir, or TZDIR on some systems. This isn't necessary for the
  404. * C bindings, however it's needed for the `listTimezones()` function and for
  405. * resolving the 'initial' timezone to use.
  406. */
  407. debug('attempting to resolve timezone directory.');
  408. var possibleTzdirs = [
  409. '/usr/share/zoneinfo'
  410. , '/usr/lib/zoneinfo'
  411. , '/usr/share/lib/zoneinfo'
  412. ];
  413. var TZDIR = process.env.TZDIR;
  414. if (TZDIR) {
  415. debug('got env-defined TZDIR:', TZDIR);
  416. possibleTzdirs.unshift(TZDIR);
  417. }
  418. while (possibleTzdirs.length > 0) {
  419. var d = possibleTzdirs.shift();
  420. debug('checking if directory exists:', d);
  421. try {
  422. if (fs.statSync(d).isDirectory()) {
  423. TZDIR = d;
  424. break;
  425. }
  426. } catch (e) {
  427. debug(e);
  428. }
  429. }
  430. possibleTzdirs = null; // garbage collect
  431. if (TZDIR) {
  432. debug('found timezone directory at:', TZDIR);
  433. } else {
  434. debug('WARN: Could not find timezone directory. listTimezones() won\'t work');
  435. }
  436. /**
  437. * Older versions of node-time would require the user to have the TZ
  438. * environment variable set, otherwise undesirable results would happen. Now
  439. * node-time tries to automatically determine the current timezone for you.
  440. */
  441. if (!exports.currentTimezone) {
  442. debug('`process.env.TZ` not initially set, attempting to resolve');
  443. try {
  444. var currentTimezonePath = fs.readlinkSync('/etc/localtime');
  445. if (currentTimezonePath.substring(0, TZDIR.length) === TZDIR) {
  446. // Got It!
  447. var zone = currentTimezonePath.substring(TZDIR.length + 1);
  448. exports.currentTimezone = process.env.TZ = zone;
  449. debug('resolved initial timezone:', zone);
  450. }
  451. } catch (e) {
  452. debug(e);
  453. }
  454. }
  455. if (!exports.currentTimezone) {
  456. debug('"currentTimezone" still not set. Checking "/etc/timezone"');
  457. try {
  458. var zone = fs.readFileSync('/etc/timezone', 'utf8').trim();
  459. exports.currentTimezone = process.env.TZ = zone;
  460. debug('resolved initial timezone:', zone);
  461. } catch (e) {
  462. debug(e);
  463. }
  464. }
  465. /**
  466. * The user-facing 'tzset' function is a thin wrapper around the native binding to
  467. * 'tzset()'. This function accepts a timezone String to set the process' timezone
  468. * to. Returns an object with the zoneinfo for the timezone.
  469. *
  470. * Throws (on *some* platforms) when the desired timezone could not be loaded.
  471. *
  472. * Sets the `currentTimezone` property on the exports.
  473. */
  474. function tzset (tz) {
  475. if (tz) {
  476. process.env.TZ = tz;
  477. }
  478. var usedTz = process.env.TZ;
  479. var rtn = bindings.tzset();
  480. debug('set the current timezone to:', usedTz);
  481. if (!rtn.tzname[1] && rtn.timezone === 0) {
  482. debug('got bad zoneinfo object:', rtn);
  483. var err = new Error("Unknown Timezone: '" + usedTz + "'");
  484. for (var i in rtn) {
  485. err[i] = rtn[i];
  486. }
  487. throw err;
  488. }
  489. exports.currentTimezone = usedTz;
  490. exports._currentZoneinfo = rtn;
  491. return rtn;
  492. }
  493. exports.tzset = tzset;
  494. /**
  495. * Lists the timezones that the current system can accept. It does this by going
  496. * on a recursive walk through the timezone dir and collecting filenames.
  497. */
  498. function listTimezones () {
  499. if (arguments.length == 0) {
  500. throw new Error("You must set a callback");
  501. }
  502. if (typeof arguments[arguments.length - 1] != "function") {
  503. throw new Error("You must set a callback");
  504. }
  505. var cb = arguments[arguments.length - 1]
  506. , subset = (arguments.length > 1 ? arguments[0] : null)
  507. return listTimezonesFolder(subset ? subset + "/" : "", subset ? path.join(TZDIR, "/" + subset) : TZDIR, function (err, tzs) {
  508. if (err) return cb(err);
  509. cb(null, tzs.sort());
  510. });
  511. }
  512. exports.listTimezones = listTimezones;
  513. function listTimezonesFolder(prefix, folder, cb) {
  514. var timezones = [];
  515. fs.readdir(folder, function (err, files) {
  516. if (err) return cb(err);
  517. var pending_stats = files.length;
  518. for (var i = 0; i < files.length; i++) {
  519. if (~TZ_BLACKLIST.indexOf(files[i])
  520. || files[i].indexOf(".") >= 0
  521. || files[i][0].toUpperCase() != files[i][0]) {
  522. pending_stats--;
  523. continue
  524. }
  525. fs.stat(path.join(folder, files[i]), (function (file) {
  526. return function (err, stats) {
  527. if (!err) {
  528. if (stats.isDirectory()) {
  529. listTimezonesFolder(prefix + file + "/", path.join(folder, file), function (err, tzs) {
  530. if (!err) {
  531. timezones = timezones.concat(tzs);
  532. }
  533. pending_stats--;
  534. if (pending_stats == 0) cb(null, timezones);
  535. });
  536. return;
  537. }
  538. if (prefix.length > 0) timezones.push(prefix + file);
  539. }
  540. pending_stats--;
  541. if (pending_stats == 0) cb(null, timezones);
  542. };
  543. })(files[i]));
  544. }
  545. });
  546. }
  547. /**
  548. * The "setTimezone" function is the "entry point" for a Date instance.
  549. * It must be called after an instance has been created. After, the 'getSeconds()',
  550. * 'getHours()', 'getDays()', etc. functions will return values relative
  551. * to the time zone specified.
  552. */
  553. function setTimezone (timezone, relative) {
  554. debug('Date#setTimezone(%s, %s)', timezone, relative);
  555. // If `true` is passed in as the second argument, then the Date instance
  556. // will have it's timezone set, but it's current local values will remain
  557. // the same (i.e. the Date's internal time value will be changed)
  558. var ms, s, m, h, d, mo, y
  559. if (relative) {
  560. y = this.getFullYear()
  561. mo = this.getMonth()
  562. d = this.getDate()
  563. h = this.getHours()
  564. m = this.getMinutes()
  565. s = this.getSeconds()
  566. ms = this.getMilliseconds()
  567. }
  568. // If the current process timezone doesn't match the desired timezone, then call
  569. // tzset() to change the current timezone of the process.
  570. var oldTz = exports.currentTimezone
  571. , tz = exports._currentZoneinfo;
  572. if (!tz || oldTz !== timezone) {
  573. debug('current timezone is not "%s", calling tzset()', timezone);
  574. tz = exports.tzset(timezone);
  575. }
  576. // Get the zoneinfo for this Date instance's time value
  577. var zoneInfo = exports.localtime(this.getTime() / 1000);
  578. // Change the timezone back if we changed it originally
  579. if (oldTz != timezone) {
  580. debug('setting timezone back to "%s"', oldTz);
  581. exports.tzset(oldTz);
  582. }
  583. oldTz = null;
  584. // If we got to here without throwing an Error, then
  585. // a valid timezone was requested, and we should have
  586. // a valid zoneInfo Object.
  587. this.getTimezone = function getTimezone() {
  588. return timezone;
  589. }
  590. // Returns the day of the month (1-31) for the specified date according to local time.
  591. this.getDate = function getDate() {
  592. return zoneInfo.dayOfMonth;
  593. }
  594. // Returns the day of the week (0-6) for the specified date according to local time.
  595. this.getDay = function getDay() {
  596. return zoneInfo.dayOfWeek;
  597. }
  598. // Deprecated. Returns the year (usually 2-3 digits) in the specified date according
  599. // to local time. Use `getFullYear()` instead.
  600. this.getYear = function getYear() {
  601. return zoneInfo.year;
  602. }
  603. // Returns the year (4 digits for 4-digit years) of the specified date according to local time.
  604. this.getFullYear = function getFullYear() {
  605. return zoneInfo.year + 1900;
  606. }
  607. // Returns the hour (0-23) in the specified date according to local time.
  608. this.getHours = function getHours() {
  609. return zoneInfo.hours;
  610. }
  611. // Returns the minutes (0-59) in the specified date according to local time.
  612. this.getMinutes = function getMinutes() {
  613. return zoneInfo.minutes;
  614. }
  615. // Returns the month (0-11) in the specified date according to local time.
  616. this.getMonth = function getMonth() {
  617. return zoneInfo.month;
  618. }
  619. // Returns the seconds (0-59) in the specified date according to local time.
  620. this.getSeconds = function getSeconds() {
  621. return zoneInfo.seconds;
  622. }
  623. // Returns the timezone offset from GMT the Date instance currently is in,
  624. // in minutes. Also, left of GMT is positive, right of GMT is negative.
  625. this.getTimezoneOffset = function getTimezoneOffset() {
  626. return -zoneInfo.gmtOffset / 60;
  627. }
  628. // NON-STANDARD: Returns the abbreviation (e.g. EST, EDT) for the specified time zone.
  629. this.getTimezoneAbbr = function getTimezoneAbbr() {
  630. return tz.tzname[zoneInfo.isDaylightSavings ? 1 : 0];
  631. }
  632. // Sets day, month and year at once
  633. this.setAllDateFields = function setAllDateFields(y,mo,d) {
  634. return this.setFullYear(y,mo,d);
  635. }
  636. // Sets the day of the month (from 1-31) in the current timezone
  637. this.setDate = function setDate(d) {
  638. zoneInfo.dayOfMonth = d;
  639. return mktime.call(this);
  640. }
  641. // Sets the year (four digits) in the current timezone
  642. this.setFullYear = function setFullYear(y,mo,d) {
  643. zoneInfo.year = y - 1900;
  644. if(arguments.length > 1)
  645. zoneInfo.month = mo;
  646. if(arguments.length > 2)
  647. zoneInfo.dayOfMonth = d;
  648. return mktime.call(this);
  649. }
  650. // Sets the hour (from 0-23) in the current timezone
  651. this.setHours = function setHours(h,m,s,ms) {
  652. zoneInfo.hours = h;
  653. if(arguments.length > 1)
  654. zoneInfo.minutes = m;
  655. if(arguments.length > 2)
  656. zoneInfo.seconds = s;
  657. if(arguments.length > 3) {
  658. mktime.call(this);
  659. var diff = ms - this.getMilliseconds();
  660. return this.setTime(this.getTime() + diff);
  661. } else
  662. return mktime.call(this);
  663. }
  664. // Sets the milliseconds (from 0-999) in the current timezone
  665. this.setMilliseconds = function setMilliseconds(ms) {
  666. var diff = ms - this.getMilliseconds();
  667. return this.setTime(this.getTime() + diff);
  668. }
  669. // Set the minutes (from 0-59) in the current timezone
  670. this.setMinutes = function setMinutes(m,s,ms) {
  671. zoneInfo.minutes = m;
  672. if(arguments.length > 1)
  673. zoneInfo.seconds = s;
  674. if(arguments.length > 2) {
  675. mktime.call(this);
  676. var diff = ms - this.getMilliseconds();
  677. return this.setTime(this.getTime() + diff);
  678. } else
  679. return mktime.call(this);
  680. }
  681. // Sets the month (from 0-11) in the current timezone
  682. this.setMonth = function setMonth(mo,d) {
  683. zoneInfo.month = mo;
  684. if(arguments.length > 1)
  685. zoneInfo.dayOfMonth = d;
  686. return mktime.call(this);
  687. }
  688. // Sets the seconds (from 0-59) in the current timezone
  689. this.setSeconds = function setSeconds(s,ms) {
  690. zoneInfo.seconds = s;
  691. if(arguments.length > 1) {
  692. mktime.call(this);
  693. var diff = ms - this.getMilliseconds();
  694. return this.setTime(this.getTime() + diff);
  695. } else
  696. return mktime.call(this);
  697. }
  698. // Sets a date and time by adding or subtracting a specified number of
  699. // milliseconds to/from midnight January 1, 1970.
  700. this.setTime = function setTime(v) {
  701. var rtn = _Date.prototype.setTime.call(this, v);
  702. // Since this function changes the internal UTC epoch date value, we need to
  703. // re-setup these timezone translation functions to reflect the new value
  704. reset.call(this);
  705. return rtn;
  706. }
  707. // Sets the day of the month, according to universal time (from 1-31)
  708. this.setUTCDate = function setUTCDate(d) {
  709. var rtn = _Date.prototype.setUTCDate.call(this, d);
  710. reset.call(this);
  711. return rtn;
  712. }
  713. // Sets the year, according to universal time (four digits)
  714. this.setUTCFullYear = function setUTCFullYear(y,mo,d) {
  715. var rtn;
  716. switch(arguments.length) {
  717. case 1:
  718. rtn = _Date.prototype.setUTCFullYear.call(this, y); break;
  719. case 2:
  720. rtn = _Date.prototype.setUTCFullYear.call(this, y,mo); break;
  721. case 3:
  722. rtn = _Date.prototype.setUTCFullYear.call(this, y,mo,d); break;
  723. }
  724. reset.call(this);
  725. return rtn;
  726. }
  727. // Sets the hour, according to universal time (from 0-23)
  728. this.setUTCHours = function setUTCHours(h,m,s,ms) {
  729. var rtn;
  730. switch(arguments.length) {
  731. case 1:
  732. rtn = _Date.prototype.setUTCHours.call(this, h); break;
  733. case 2:
  734. rtn = _Date.prototype.setUTCHours.call(this, h,m); break;
  735. case 3:
  736. rtn = _Date.prototype.setUTCHours.call(this, h,m,s); break;
  737. case 4:
  738. rtn = _Date.prototype.setUTCHours.call(this, h,m,s,ms); break;
  739. }
  740. reset.call(this);
  741. return rtn;
  742. }
  743. // Sets the milliseconds, according to universal time (from 0-999)
  744. this.setUTCMilliseconds = function setUTCMillseconds(ms) {
  745. var rtn = _Date.prototype.setUTCMilliseconds.call(this, ms);
  746. reset.call(this);
  747. return rtn;
  748. }
  749. // Set the minutes, according to universal time (from 0-59)
  750. this.setUTCMinutes = function setUTCMinutes(m,s,ms) {
  751. var rtn;
  752. switch(arguments.length) {
  753. case 1:
  754. rtn = _Date.prototype.setUTCMinutes.call(this, m); break;
  755. case 2:
  756. rtn = _Date.prototype.setUTCMinutes.call(this, m,s); break;
  757. case 3:
  758. rtn = _Date.prototype.setUTCMinutes.call(this, m,s,ms); break;
  759. }
  760. reset.call(this);
  761. return rtn;
  762. }
  763. // Sets the month, according to universal time (from 0-11)
  764. this.setUTCMonth = function setUTCMonth(mo,d) {
  765. var rtn;
  766. switch(arguments.length) {
  767. case 1:
  768. rtn = _Date.prototype.setUTCMonth.call(this, mo); break;
  769. case 2:
  770. rtn = _Date.prototype.setUTCMonth.call(this, mo,d); break;
  771. }
  772. reset.call(this);
  773. return rtn;
  774. }
  775. // Set the seconds, according to universal time (from 0-59)
  776. this.setUTCSeconds = function setUTCSeconds(s,ms) {
  777. var rtn;
  778. switch(arguments.length) {
  779. case 1:
  780. rtn = _Date.prototype.setUTCSeconds.call(this, s); break;
  781. case 2:
  782. rtn = _Date.prototype.setUTCSeconds.call(this, s,ms); break;
  783. }
  784. reset.call(this);
  785. return rtn;
  786. }
  787. this.toDateString = function toDateString() {
  788. return DAYS_OF_WEEK[this.getDay()].substring(0, 3) + ' ' + MONTHS[this.getMonth()].substring(0, 3) + ' ' + pad(this.getDate(), 2) + ' ' + this.getFullYear();
  789. }
  790. this.toTimeString = function toTimeString() {
  791. var offset = Math.abs(zoneInfo.gmtOffset / 60); // total minutes
  792. // split into HHMM:
  793. var hours = pad(Math.floor(offset / 60), 2);
  794. var minutes = pad(offset % 60, 2);
  795. return this.toLocaleTimeString() + ' GMT' + (zoneInfo.gmtOffset >= 0 ? '+' : '-') + hours + minutes
  796. + ' (' + tz.tzname[zoneInfo.isDaylightSavings ? 1 : 0] + ')';
  797. }
  798. this.toString = function toString() {
  799. return this.toDateString() + ' ' + this.toTimeString();
  800. }
  801. this.toLocaleDateString = function toLocaleDateString() {
  802. return DAYS_OF_WEEK[this.getDay()] + ', ' + MONTHS[this.getMonth()] + ' ' + pad(this.getDate(), 2) + ', ' + this.getFullYear();
  803. }
  804. this.toLocaleTimeString = function toLocaleTimeString() {
  805. return pad(this.getHours(), 2) + ':' + pad(this.getMinutes(), 2) + ':' + pad(this.getSeconds(), 2);
  806. }
  807. this.toLocaleString = this.toString;
  808. if (relative) {
  809. this.setAllDateFields(y,mo,d)
  810. this.setHours(h)
  811. this.setMinutes(m)
  812. this.setSeconds(s)
  813. this.setMilliseconds(ms)
  814. ms = s = m = h = d = mo = y = null
  815. }
  816. // Used internally by the 'set*' functions above...
  817. function reset () {
  818. this.setTimezone(this.getTimezone());
  819. }
  820. // 'mktime' calls 'reset' implicitly through 'setTime()'
  821. function mktime () {
  822. var oldTz = process.env.TZ;
  823. exports.tzset(this.getTimezone());
  824. zoneInfo.isDaylightSavings = -1; // Auto-detect the timezone
  825. var t = exports.mktime(zoneInfo);
  826. if (oldTz) {
  827. exports.tzset(oldTz);
  828. oldTz = null;
  829. }
  830. return this.setTime( (t * MILLIS_PER_SECOND) + this.getMilliseconds() );
  831. }
  832. return this;
  833. }
  834. // Returns a "String" of the last value set in "setTimezone".
  835. // TODO: Return something when 'setTimezone' hasn't been called yet.
  836. function getTimezone () {
  837. throw new Error('You must call "setTimezone(tz)" before "getTimezone()" may be called');
  838. }
  839. // NON-STANDARD: Returns the abbreviated timezone name, also taking daylight
  840. // savings into consideration. Useful for the presentation layer of a Date
  841. // instance.
  842. function getTimezoneAbbr () {
  843. var str = this.toString().match(/\([A-Z]+\)/)[0];
  844. return str.substring(1, str.length-1);
  845. }
  846. // Export the modified 'Date' instance. Users should either use this with the
  847. // 'new' operator, or extend an already existing Date instance with 'extend()'.
  848. // An optional, NON-STANDARD, "timezone" argument may be appended as the final
  849. // argument, in order to specify the initial timezone the Date instance should
  850. // be created with.
  851. function Date (year, month, day, hour, minute, second, millisecond, timezone) {
  852. if (!(this instanceof Date)) {
  853. return new Date(year, month, day, hour, minute, second, millisecond, timezone).toString();
  854. }
  855. var argc = arguments.length
  856. , d;
  857. // So that we don't have to do the switch block below twice!
  858. while (argc > 0 && typeof arguments[argc-1] === 'undefined') {
  859. argc--;
  860. }
  861. // An optional 'timezone' argument may be passed as the final argument
  862. if (argc >= 2 && typeof arguments[argc - 1] === 'string') {
  863. timezone = arguments[argc - 1];
  864. argc--;
  865. }
  866. // Ugly, but the native Date constructor depends on arguments.length in order
  867. // to create a Date instance in the intended fashion.
  868. switch (argc) {
  869. case 0:
  870. d = new _Date(); break;
  871. case 1:
  872. d = new _Date(year); break;
  873. case 2:
  874. d = new _Date(year, month); break;
  875. case 3:
  876. d = new _Date(year, month, day); break;
  877. case 4:
  878. d = new _Date(year, month, day, hour); break;
  879. case 5:
  880. d = new _Date(year, month, day, hour, minute); break;
  881. case 6:
  882. d = new _Date(year, month, day, hour, minute, second); break;
  883. case 7:
  884. d = new _Date(year, month, day, hour, minute, second, millisecond); break;
  885. }
  886. if (timezone) {
  887. // set time given timezone relative to the currently set local time
  888. // (changing the internal "time" milliseconds value unless ms specified)
  889. d.setTimezone(timezone, !(argc == 1 && typeof year === 'number'));
  890. } else {
  891. d.setTimezone(exports.currentTimezone);
  892. }
  893. return d;
  894. }
  895. Date.prototype = _Date.prototype;
  896. exports.Date = Date;
  897. // We also overwrite `Date.parse()`. It can accept an optional 'timezone'
  898. // second argument.
  899. function parse (dateStr, timezone) {
  900. return new Date(dateStr, timezone).getTime();
  901. }
  902. exports.parse = parse;
  903. // 'now()', 'parse()', and 'UTC()' all need to be re-defined on Date as don't enum
  904. Object.defineProperty(Date, 'now', { value: _Date.now, writable: true, enumerable: false });
  905. Object.defineProperty(Date, 'parse', { value: parse, writable: true, enumerable: false });
  906. Object.defineProperty(Date, 'UTC', { value: _Date.UTC, writable: true, enumerable: false });
  907. // Turns a "regular" Date instance into one of our "extended" Date instances.
  908. // The return value is negligible, as the original Date instance is modified.
  909. // DEPRECATED: Just extend the Date's prototype using the Date-extend function.
  910. exports.extend = function extend (date) {
  911. if (!date) return date;
  912. date.getTimezone = getTimezone;
  913. date.setTimezone = setTimezone;
  914. date.getTimezoneAbbr = getTimezoneAbbr;
  915. return date;
  916. }
  917. /**
  918. * Pads a number with 0s if required.
  919. */
  920. function pad (num, padLen) {
  921. var padding = '0000';
  922. num = String(num);
  923. return padding.substring(0, padLen - num.length) + num;
  924. }
  925. }).call(this,require('_process'))
  926. },{"_process":7,"bindings":3,"debug":4,"fs":5,"path":6,"vm":8}],3:[function(require,module,exports){
  927. (function (process,__filename){
  928. /**
  929. * Module dependencies.
  930. */
  931. var fs = require('fs')
  932. , path = require('path')
  933. , join = path.join
  934. , dirname = path.dirname
  935. , exists = fs.existsSync || path.existsSync
  936. , defaults = {
  937. arrow: process.env.NODE_BINDINGS_ARROW || ' → '
  938. , compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
  939. , platform: process.platform
  940. , arch: process.arch
  941. , version: process.versions.node
  942. , bindings: 'bindings.node'
  943. , try: [
  944. // node-gyp's linked version in the "build" dir
  945. [ 'module_root', 'build', 'bindings' ]
  946. // node-waf and gyp_addon (a.k.a node-gyp)
  947. , [ 'module_root', 'build', 'Debug', 'bindings' ]
  948. , [ 'module_root', 'build', 'Release', 'bindings' ]
  949. // Debug files, for development (legacy behavior, remove for node v0.9)
  950. , [ 'module_root', 'out', 'Debug', 'bindings' ]
  951. , [ 'module_root', 'Debug', 'bindings' ]
  952. // Release files, but manually compiled (legacy behavior, remove for node v0.9)
  953. , [ 'module_root', 'out', 'Release', 'bindings' ]
  954. , [ 'module_root', 'Release', 'bindings' ]
  955. // Legacy from node-waf, node <= 0.4.x
  956. , [ 'module_root', 'build', 'default', 'bindings' ]
  957. // Production "Release" buildtype binary (meh...)
  958. , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
  959. ]
  960. }
  961. /**
  962. * The main `bindings()` function loads the compiled bindings for a given module.
  963. * It uses V8's Error API to determine the parent filename that this function is
  964. * being invoked from, which is then used to find the root directory.
  965. */
  966. function bindings (opts) {
  967. // Argument surgery
  968. if (typeof opts == 'string') {
  969. opts = { bindings: opts }
  970. } else if (!opts) {
  971. opts = {}
  972. }
  973. opts.__proto__ = defaults
  974. // Get the module root
  975. if (!opts.module_root) {
  976. opts.module_root = exports.getRoot(exports.getFileName())
  977. }
  978. // Ensure the given bindings name ends with .node
  979. if (path.extname(opts.bindings) != '.node') {
  980. opts.bindings += '.node'
  981. }
  982. var tries = []
  983. , i = 0
  984. , l = opts.try.length
  985. , n
  986. , b
  987. , err
  988. for (; i<l; i++) {
  989. n = join.apply(null, opts.try[i].map(function (p) {
  990. return opts[p] || p
  991. }))
  992. tries.push(n)
  993. try {
  994. b = opts.path ? require.resolve(n) : require(n)
  995. if (!opts.path) {
  996. b.path = n
  997. }
  998. return b
  999. } catch (e) {
  1000. if (!/not find/i.test(e.message)) {
  1001. throw e
  1002. }
  1003. }
  1004. }
  1005. err = new Error('Could not locate the bindings file. Tried:\n'
  1006. + tries.map(function (a) { return opts.arrow + a }).join('\n'))
  1007. err.tries = tries
  1008. throw err
  1009. }
  1010. module.exports = exports = bindings
  1011. /**
  1012. * Gets the filename of the JavaScript file that invokes this function.
  1013. * Used to help find the root directory of a module.
  1014. * Optionally accepts an filename argument to skip when searching for the invoking filename
  1015. */
  1016. exports.getFileName = function getFileName (calling_file) {
  1017. var origPST = Error.prepareStackTrace
  1018. , origSTL = Error.stackTraceLimit
  1019. , dummy = {}
  1020. , fileName
  1021. Error.stackTraceLimit = 10
  1022. Error.prepareStackTrace = function (e, st) {
  1023. for (var i=0, l=st.length; i<l; i++) {
  1024. fileName = st[i].getFileName()
  1025. if (fileName !== __filename) {
  1026. if (calling_file) {
  1027. if (fileName !== calling_file) {
  1028. return
  1029. }
  1030. } else {
  1031. return
  1032. }
  1033. }
  1034. }
  1035. }
  1036. // run the 'prepareStackTrace' function above
  1037. Error.captureStackTrace(dummy)
  1038. dummy.stack
  1039. // cleanup
  1040. Error.prepareStackTrace = origPST
  1041. Error.stackTraceLimit = origSTL
  1042. return fileName
  1043. }
  1044. /**
  1045. * Gets the root directory of a module, given an arbitrary filename
  1046. * somewhere in the module tree. The "root directory" is the directory
  1047. * containing the `package.json` file.
  1048. *
  1049. * In: /home/nate/node-native-module/lib/index.js
  1050. * Out: /home/nate/node-native-module
  1051. */
  1052. exports.getRoot = function getRoot (file) {
  1053. var dir = dirname(file)
  1054. , prev
  1055. while (true) {
  1056. if (dir === '.') {
  1057. // Avoids an infinite loop in rare cases, like the REPL
  1058. dir = process.cwd()
  1059. }
  1060. if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
  1061. // Found the 'package.json' file or 'node_modules' dir; we're done
  1062. return dir
  1063. }
  1064. if (prev === dir) {
  1065. // Got to the top
  1066. throw new Error('Could not find module root given file: "' + file
  1067. + '". Do you have a `package.json` file? ')
  1068. }
  1069. // Try the parent dir next
  1070. prev = dir
  1071. dir = join(dir, '..')
  1072. }
  1073. }
  1074. }).call(this,require('_process'),"/node_modules/time/node_modules/bindings/bindings.js")
  1075. },{"_process":7,"fs":5,"path":6}],4:[function(require,module,exports){
  1076. /**
  1077. * Expose `debug()` as the module.
  1078. */
  1079. module.exports = debug;
  1080. /**
  1081. * Create a debugger with the given `name`.
  1082. *
  1083. * @param {String} name
  1084. * @return {Type}
  1085. * @api public
  1086. */
  1087. function debug(name) {
  1088. if (!debug.enabled(name)) return function(){};
  1089. return function(fmt){
  1090. fmt = coerce(fmt);
  1091. var curr = new Date;
  1092. var ms = curr - (debug[name] || curr);
  1093. debug[name] = curr;
  1094. fmt = name
  1095. + ' '
  1096. + fmt
  1097. + ' +' + debug.humanize(ms);
  1098. // This hackery is required for IE8
  1099. // where `console.log` doesn't have 'apply'
  1100. window.console
  1101. && console.log
  1102. && Function.prototype.apply.call(console.log, console, arguments);
  1103. }
  1104. }
  1105. /**
  1106. * The currently active debug mode names.
  1107. */
  1108. debug.names = [];
  1109. debug.skips = [];
  1110. /**
  1111. * Enables a debug mode by name. This can include modes
  1112. * separated by a colon and wildcards.
  1113. *
  1114. * @param {String} name
  1115. * @api public
  1116. */
  1117. debug.enable = function(name) {
  1118. try {
  1119. localStorage.debug = name;
  1120. } catch(e){}
  1121. var split = (name || '').split(/[\s,]+/)
  1122. , len = split.length;
  1123. for (var i = 0; i < len; i++) {
  1124. name = split[i].replace('*', '.*?');
  1125. if (name[0] === '-') {
  1126. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  1127. }
  1128. else {
  1129. debug.names.push(new RegExp('^' + name + '$'));
  1130. }
  1131. }
  1132. };
  1133. /**
  1134. * Disable debug output.
  1135. *
  1136. * @api public
  1137. */
  1138. debug.disable = function(){
  1139. debug.enable('');
  1140. };
  1141. /**
  1142. * Humanize the given `ms`.
  1143. *
  1144. * @param {Number} m
  1145. * @return {String}
  1146. * @api private
  1147. */
  1148. debug.humanize = function(ms) {
  1149. var sec = 1000
  1150. , min = 60 * 1000
  1151. , hour = 60 * min;
  1152. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  1153. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  1154. if (ms >= sec) return (ms / sec | 0) + 's';
  1155. return ms + 'ms';
  1156. };
  1157. /**
  1158. * Returns true if the given mode name is enabled, false otherwise.
  1159. *
  1160. * @param {String} name
  1161. * @return {Boolean}
  1162. * @api public
  1163. */
  1164. debug.enabled = function(name) {
  1165. for (var i = 0, len = debug.skips.length; i < len; i++) {
  1166. if (debug.skips[i].test(name)) {
  1167. return false;
  1168. }
  1169. }
  1170. for (var i = 0, len = debug.names.length; i < len; i++) {
  1171. if (debug.names[i].test(name)) {
  1172. return true;
  1173. }
  1174. }
  1175. return false;
  1176. };
  1177. /**
  1178. * Coerce `val`.
  1179. */
  1180. function coerce(val) {
  1181. if (val instanceof Error) return val.stack || val.message;
  1182. return val;
  1183. }
  1184. // persist
  1185. try {
  1186. if (window.localStorage) debug.enable(localStorage.debug);
  1187. } catch(e){}
  1188. },{}],5:[function(require,module,exports){
  1189. },{}],6:[function(require,module,exports){
  1190. (function (process){
  1191. // Copyright Joyent, Inc. and other Node contributors.
  1192. //
  1193. // Permission is hereby granted, free of charge, to any person obtaining a
  1194. // copy of this software and associated documentation files (the
  1195. // "Software"), to deal in the Software without restriction, including
  1196. // without limitation the rights to use, copy, modify, merge, publish,
  1197. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1198. // persons to whom the Software is furnished to do so, subject to the
  1199. // following conditions:
  1200. //
  1201. // The above copyright notice and this permission notice shall be included
  1202. // in all copies or substantial portions of the Software.
  1203. //
  1204. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1205. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1206. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1207. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1208. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1209. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1210. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1211. // resolves . and .. elements in a path array with directory names there
  1212. // must be no slashes, empty elements, or device names (c:\) in the array
  1213. // (so also no leading and trailing slashes - it does not distinguish
  1214. // relative and absolute paths)
  1215. function normalizeArray(parts, allowAboveRoot) {
  1216. // if the path tries to go above the root, `up` ends up > 0
  1217. var up = 0;
  1218. for (var i = parts.length - 1; i >= 0; i--) {
  1219. var last = parts[i];
  1220. if (last === '.') {
  1221. parts.splice(i, 1);
  1222. } else if (last === '..') {
  1223. parts.splice(i, 1);
  1224. up++;
  1225. } else if (up) {
  1226. parts.splice(i, 1);
  1227. up--;
  1228. }
  1229. }
  1230. // if the path is allowed to go above the root, restore leading ..s
  1231. if (allowAboveRoot) {
  1232. for (; up--; up) {
  1233. parts.unshift('..');
  1234. }
  1235. }
  1236. return parts;
  1237. }
  1238. // Split a filename into [root, dir, basename, ext], unix version
  1239. // 'root' is just a slash, or nothing.
  1240. var splitPathRe =
  1241. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  1242. var splitPath = function(filename) {
  1243. return splitPathRe.exec(filename).slice(1);
  1244. };
  1245. // path.resolve([from ...], to)
  1246. // posix version
  1247. exports.resolve = function() {
  1248. var resolvedPath = '',
  1249. resolvedAbsolute = false;
  1250. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  1251. var path = (i >= 0) ? arguments[i] : process.cwd();
  1252. // Skip empty and invalid entries
  1253. if (typeof path !== 'string') {
  1254. throw new TypeError('Arguments to path.resolve must be strings');
  1255. } else if (!path) {
  1256. continue;
  1257. }
  1258. resolvedPath = path + '/' + resolvedPath;
  1259. resolvedAbsolute = path.charAt(0) === '/';
  1260. }
  1261. // At this point the path should be resolved to a full absolute path, but
  1262. // handle relative paths to be safe (might happen when process.cwd() fails)
  1263. // Normalize the path
  1264. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  1265. return !!p;
  1266. }), !resolvedAbsolute).join('/');
  1267. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  1268. };
  1269. // path.normalize(path)
  1270. // posix version
  1271. exports.normalize = function(path) {
  1272. var isAbsolute = exports.isAbsolute(path),
  1273. trailingSlash = substr(path, -1) === '/';
  1274. // Normalize the path
  1275. path = normalizeArray(filter(path.split('/'), function(p) {
  1276. return !!p;
  1277. }), !isAbsolute).join('/');
  1278. if (!path && !isAbsolute) {
  1279. path = '.';
  1280. }
  1281. if (path && trailingSlash) {
  1282. path += '/';
  1283. }
  1284. return (isAbsolute ? '/' : '') + path;
  1285. };
  1286. // posix version
  1287. exports.isAbsolute = function(path) {
  1288. return path.charAt(0) === '/';
  1289. };
  1290. // posix version
  1291. exports.join = function() {
  1292. var paths = Array.prototype.slice.call(arguments, 0);
  1293. return exports.normalize(filter(paths, function(p, index) {
  1294. if (typeof p !== 'string') {
  1295. throw new TypeError('Arguments to path.join must be strings');
  1296. }
  1297. return p;
  1298. }).join('/'));
  1299. };
  1300. // path.relative(from, to)
  1301. // posix version
  1302. exports.relative = function(from, to) {
  1303. from = exports.resolve(from).substr(1);
  1304. to = exports.resolve(to).substr(1);
  1305. function trim(arr) {
  1306. var start = 0;
  1307. for (; start < arr.length; start++) {
  1308. if (arr[start] !== '') break;
  1309. }
  1310. var end = arr.length - 1;
  1311. for (; end >= 0; end--) {
  1312. if (arr[end] !== '') break;
  1313. }
  1314. if (start > end) return [];
  1315. return arr.slice(start, end - start + 1);
  1316. }
  1317. var fromParts = trim(from.split('/'));
  1318. var toParts = trim(to.split('/'));
  1319. var length = Math.min(fromParts.length, toParts.length);
  1320. var samePartsLength = length;
  1321. for (var i = 0; i < length; i++) {
  1322. if (fromParts[i] !== toParts[i]) {
  1323. samePartsLength = i;
  1324. break;
  1325. }
  1326. }
  1327. var outputParts = [];
  1328. for (var i = samePartsLength; i < fromParts.length; i++) {
  1329. outputParts.push('..');
  1330. }
  1331. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  1332. return outputParts.join('/');
  1333. };
  1334. exports.sep = '/';
  1335. exports.delimiter = ':';
  1336. exports.dirname = function(path) {
  1337. var result = splitPath(path),
  1338. root = result[0],
  1339. dir = result[1];
  1340. if (!root && !dir) {
  1341. // No dirname whatsoever
  1342. return '.';
  1343. }
  1344. if (dir) {
  1345. // It has a dirname, strip trailing slash
  1346. dir = dir.substr(0, dir.length - 1);
  1347. }
  1348. return root + dir;
  1349. };
  1350. exports.basename = function(path, ext) {
  1351. var f = splitPath(path)[2];
  1352. // TODO: make this comparison case-insensitive on windows?
  1353. if (ext && f.substr(-1 * ext.length) === ext) {
  1354. f = f.substr(0, f.length - ext.length);
  1355. }
  1356. return f;
  1357. };
  1358. exports.extname = function(path) {
  1359. return splitPath(path)[3];
  1360. };
  1361. function filter (xs, f) {
  1362. if (xs.filter) return xs.filter(f);
  1363. var res = [];
  1364. for (var i = 0; i < xs.length; i++) {
  1365. if (f(xs[i], i, xs)) res.push(xs[i]);
  1366. }
  1367. return res;
  1368. }
  1369. // String.prototype.substr - negative index don't work in IE8
  1370. var substr = 'ab'.substr(-1) === 'b'
  1371. ? function (str, start, len) { return str.substr(start, len) }
  1372. : function (str, start, len) {
  1373. if (start < 0) start = str.length + start;
  1374. return str.substr(start, len);
  1375. }
  1376. ;
  1377. }).call(this,require('_process'))
  1378. },{"_process":7}],7:[function(require,module,exports){
  1379. // shim for using process in browser
  1380. var process = module.exports = {};
  1381. process.nextTick = (function () {
  1382. var canSetImmediate = typeof window !== 'undefined'
  1383. && window.setImmediate;
  1384. var canMutationObserver = typeof window !== 'undefined'
  1385. && window.MutationObserver;
  1386. var canPost = typeof window !== 'undefined'
  1387. && window.postMessage && window.addEventListener
  1388. ;
  1389. if (canSetImmediate) {
  1390. return function (f) { return window.setImmediate(f) };
  1391. }
  1392. var queue = [];
  1393. if (canMutationObserver) {
  1394. var hiddenDiv = document.createElement("div");
  1395. var observer = new MutationObserver(function () {
  1396. var queueList = queue.slice();
  1397. queue.length = 0;
  1398. queueList.forEach(function (fn) {
  1399. fn();
  1400. });
  1401. });
  1402. observer.observe(hiddenDiv, { attributes: true });
  1403. return function nextTick(fn) {
  1404. if (!queue.length) {
  1405. hiddenDiv.setAttribute('yes', 'no');
  1406. }
  1407. queue.push(fn);
  1408. };
  1409. }
  1410. if (canPost) {
  1411. window.addEventListener('message', function (ev) {
  1412. var source = ev.source;
  1413. if ((source === window || source === null) && ev.data === 'process-tick') {
  1414. ev.stopPropagation();
  1415. if (queue.length > 0) {
  1416. var fn = queue.shift();
  1417. fn();
  1418. }
  1419. }
  1420. }, true);
  1421. return function nextTick(fn) {
  1422. queue.push(fn);
  1423. window.postMessage('process-tick', '*');
  1424. };
  1425. }
  1426. return function nextTick(fn) {
  1427. setTimeout(fn, 0);
  1428. };
  1429. })();
  1430. process.title = 'browser';
  1431. process.browser = true;
  1432. process.env = {};
  1433. process.argv = [];
  1434. function noop() {}
  1435. process.on = noop;
  1436. process.addListener = noop;
  1437. process.once = noop;
  1438. process.off = noop;
  1439. process.removeListener = noop;
  1440. process.removeAllListeners = noop;
  1441. process.emit = noop;
  1442. process.binding = function (name) {
  1443. throw new Error('process.binding is not supported');
  1444. };
  1445. // TODO(shtylman)
  1446. process.cwd = function () { return '/' };
  1447. process.chdir = function (dir) {
  1448. throw new Error('process.chdir is not supported');
  1449. };
  1450. },{}],8:[function(require,module,exports){
  1451. var indexOf = require('indexof');
  1452. var Object_keys = function (obj) {
  1453. if (Object.keys) return Object.keys(obj)
  1454. else {
  1455. var res = [];
  1456. for (var key in obj) res.push(key)
  1457. return res;
  1458. }
  1459. };
  1460. var forEach = function (xs, fn) {
  1461. if (xs.forEach) return xs.forEach(fn)
  1462. else for (var i = 0; i < xs.length; i++) {
  1463. fn(xs[i], i, xs);
  1464. }
  1465. };
  1466. var defineProp = (function() {
  1467. try {
  1468. Object.defineProperty({}, '_', {});
  1469. return function(obj, name, value) {
  1470. Object.defineProperty(obj, name, {
  1471. writable: true,
  1472. enumerable: false,
  1473. configurable: true,
  1474. value: value
  1475. })
  1476. };
  1477. } catch(e) {
  1478. return function(obj, name, value) {
  1479. obj[name] = value;
  1480. };
  1481. }
  1482. }());
  1483. var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
  1484. 'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
  1485. 'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
  1486. 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
  1487. 'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
  1488. function Context() {}
  1489. Context.prototype = {};
  1490. var Script = exports.Script = function NodeScript (code) {
  1491. if (!(this instanceof Script)) return new Script(code);
  1492. this.code = code;
  1493. };
  1494. Script.prototype.runInContext = function (context) {
  1495. if (!(context instanceof Context)) {
  1496. throw new TypeError("needs a 'context' argument.");
  1497. }
  1498. var iframe = document.createElement('iframe');
  1499. if (!iframe.style) iframe.style = {};
  1500. iframe.style.display = 'none';
  1501. document.body.appendChild(iframe);
  1502. var win = iframe.contentWindow;
  1503. var wEval = win.eval, wExecScript = win.execScript;
  1504. if (!wEval && wExecScript) {
  1505. // win.eval() magically appears when this is called in IE:
  1506. wExecScript.call(win, 'null');
  1507. wEval = win.eval;
  1508. }
  1509. forEach(Object_keys(context), function (key) {
  1510. win[key] = context[key];
  1511. });
  1512. forEach(globals, function (key) {
  1513. if (context[key]) {
  1514. win[key] = context[key];
  1515. }
  1516. });
  1517. var winKeys = Object_keys(win);
  1518. var res = wEval.call(win, this.code);
  1519. forEach(Object_keys(win), function (key) {
  1520. // Avoid copying circular objects like `top` and `window` by only
  1521. // updating existing context properties or new properties in the `win`
  1522. // that was only introduced after the eval.
  1523. if (key in context || indexOf(winKeys, key) === -1) {
  1524. context[key] = win[key];
  1525. }
  1526. });
  1527. forEach(globals, function (key) {
  1528. if (!(key in context)) {
  1529. defineProp(context, key, win[key]);
  1530. }
  1531. });
  1532. document.body.removeChild(iframe);
  1533. return res;
  1534. };
  1535. Script.prototype.runInThisContext = function () {
  1536. return eval(this.code); // maybe...
  1537. };
  1538. Script.prototype.runInNewContext = function (context) {
  1539. var ctx = Script.createContext(context);
  1540. var res = this.runInContext(ctx);
  1541. forEach(Object_keys(ctx), function (key) {
  1542. context[key] = ctx[key];
  1543. });
  1544. return res;
  1545. };
  1546. forEach(Object_keys(Script.prototype), function (name) {
  1547. exports[name] = Script[name] = function (code) {
  1548. var s = Script(code);
  1549. return s[name].apply(s, [].slice.call(arguments, 1));
  1550. };
  1551. });
  1552. exports.createScript = function (code) {
  1553. return exports.Script(code);
  1554. };
  1555. exports.createContext = Script.createContext = function (context) {
  1556. var copy = new Context();
  1557. if(typeof context === 'object') {
  1558. forEach(Object_keys(context), function (key) {
  1559. copy[key] = context[key];
  1560. });
  1561. }
  1562. return copy;
  1563. };
  1564. },{"indexof":9}],9:[function(require,module,exports){
  1565. var indexOf = [].indexOf;
  1566. module.exports = function(arr, obj){
  1567. if (indexOf) return arr.indexOf(obj);
  1568. for (var i = 0; i < arr.length; ++i) {
  1569. if (arr[i] === obj) return i;
  1570. }
  1571. return -1;
  1572. };
  1573. },{}]},{},[1])(1)
  1574. });