Example #1
0
amazon_fireos_parser.prototype.update_from_config = function(config) {
    // TODO: share code for this func with Android. Or fix it and remove
    // the below JSHint hacks line.
    // jshint unused:false, indent:false, undef:true, loopfunc:true, shadow:true
    if (config instanceof ConfigParser) {
    } else throw new Error('update_from_config requires a ConfigParser object');

    // Update app name by editing res/values/strings.xml
    var name = config.name();
    var strings = xml.parseElementtreeSync(this.strings);
    strings.find('string[@name="app_name"]').text = name;
    fs.writeFileSync(this.strings, strings.write({indent: 4}), 'utf-8');
    events.emit('verbose', 'Wrote out Android application name to "' + name + '"');

    this.handleSplashes(config);
    this.handleIcons(config);

    var manifest = xml.parseElementtreeSync(this.manifest);
    // Update the version by changing the AndroidManifest android:versionName
    var version = config.version();
    var versionCode = config.android_versionCode() || default_versionCode(version);
    manifest.getroot().attrib['android:versionName'] = version;
    manifest.getroot().attrib['android:versionCode'] = versionCode;

    // Update package name by changing the AndroidManifest id and moving the entry class around to the proper package directory
    var pkg = config.android_packageName() || config.packageName();
    pkg = pkg.replace(/-/g, '_'); // Java packages cannot support dashes
    var orig_pkg = manifest.getroot().attrib.package;
    manifest.getroot().attrib.package = pkg;

    var act = manifest.getroot().find('./application/activity');

     // Set the orientation in the AndroidManifest
    var orientationPref = this.findOrientationPreference(config);
    if (orientationPref) {
        switch (orientationPref) {
            case 'default':
                delete act.attrib['android:screenOrientation'];
                break;
            case 'portrait':
                act.attrib['android:screenOrientation'] = 'portrait';
                break;
            case 'landscape':
                act.attrib['android:screenOrientation'] = 'landscape';
        }
    }

    // Set android:launchMode in AndroidManifest
    var androidLaunchModePref = this.findAndroidLaunchModePreference(config);
    if (androidLaunchModePref) {
        act.attrib['android:launchMode'] = androidLaunchModePref;
    } else { // User has (explicitly) set an invalid value for AndroidLaunchMode preference
        delete act.attrib['android:launchMode']; // use Android default value (standard)
    }

    // Set min/max/target SDK version
    //<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="19" ... />
    var usesSdk = manifest.getroot().find('./uses-sdk');
    ['minSdkVersion', 'maxSdkVersion', 'targetSdkVersion'].forEach(function(sdkPrefName) {
        var sdkPrefValue = config.getPreference('android-' + sdkPrefName, 'android');
        if (!sdkPrefValue) return;

        if (!usesSdk) { // if there is no required uses-sdk element, we should create it first
            usesSdk = new et.Element('uses-sdk');
            manifest.getroot().append(usesSdk);
        }
        usesSdk.attrib['android:' + sdkPrefName] = sdkPrefValue;
    });

    // Write out AndroidManifest.xml
    fs.writeFileSync(this.manifest, manifest.write({indent: 4}), 'utf-8');

    var orig_pkgDir = path.join(this.path, 'src', path.join.apply(null, orig_pkg.split('.')));
    var java_files = fs.readdirSync(orig_pkgDir).filter(function(f) {
      return f.indexOf('.svn') == -1 && f.indexOf('.java') >= 0 && fs.readFileSync(path.join(orig_pkgDir, f), 'utf-8').match(/extends\s+CordovaActivity/);
    });
    if (java_files.length === 0) {
      throw new Error('No Java files found which extend CordovaActivity.');
    } else if(java_files.length > 1) {
      events.emit('log', 'Multiple candidate Java files (.java files which extend CordovaActivity) found. Guessing at the first one, ' + java_files[0]);
    }

    var orig_java_class = java_files[0];
    var pkgDir = path.join(this.path, 'src', path.join.apply(null, pkg.split('.')));
    shell.mkdir('-p', pkgDir);
    var orig_javs = path.join(orig_pkgDir, orig_java_class);
    var new_javs = path.join(pkgDir, orig_java_class);
    var javs_contents = fs.readFileSync(orig_javs, 'utf-8');
    javs_contents = javs_contents.replace(/package [\w\.]*;/, 'package ' + pkg + ';');
    events.emit('verbose', 'Wrote out Android package name to "' + pkg + '"');
    fs.writeFileSync(new_javs, javs_contents, 'utf-8');
};
Example #2
0
 /**
  * Returns the path inside of the fixture directory.
  * @returns {string} The path inside the fixture directory.
  * @private
  */
 function getFixturePath() {
     var args = Array.prototype.slice.call(arguments);
     args.unshift(fixtureDir);
     return path.join.apply(path, args);
 }
Example #3
0
var pkg = new Pkg();

/**
 * Local dependencies
 */

var verbfile = require('./verbfile');
var pipeline = require('./build/pipeline');
var defaults = require('./build/defaults');
var tools = require('./build/tools');

/**
 * Build variables
 */

var dest = path.join.bind(path, __dirname, '../docs');
var css = path.join.bind(path, dest('assets/css'));
var src = path.join.bind(path, __dirname, 'src');
var tmpl = path.join.bind(path, src('templates'));
var assets = path.join.bind(path, dest('assets'));

/**
 * App
 */

var app = module.exports = assemble({
  exts: ['md', 'hbs', 'html', 'xml', 'txt']
});

/**
 * Custom collections
Example #4
0
exports.isLink = function() {
  var filepath = path.join.apply(path, arguments);
  return this.exists(filepath) && fs.lstatSync(filepath).isSymbolicLink();
};
Example #5
0
exports.isPathAbsolute = function() {
  var filepath = path.join.apply(path, arguments);
  return path.resolve(filepath) === filepath.replace(/[\/\\]+$/, '');
};
function root(args) {
  args = [].slice.call(arguments, 0);
  return path.join.apply(path, [ROOT].concat(args));
}
Example #7
0
task.getFile = function() {
  var filepath = path.join.apply(path, arguments);
  var fileobj = task.expand(filepath)[0];
  return fileobj ? String(fileobj) : null;
};
Example #8
0
    return function () {
        var args = Array.prototype.slice.call(arguments, 0),
            pieces = [base].concat(args);
        return gulp.dest(pathUtil.join.apply(pathUtil, pieces));
    };
Example #9
0
 var splitPath = function(p) { return path.join.apply(undefined, p.split('/')); };
var join = function() {
  return path.join.apply(path, arguments).replace(/\\/g, "/");
};
Example #11
0
var assert = require("assert");
var Duo = require("duo");
var less = require("../");
var path = require("path");
var read = require("fs").readFileSync;

var fixture = path.join.bind(path, __dirname, "fixtures");

describe("duo-less", function () {
    it("should be a function", function () {
        assert.equal(typeof less, "function");
    });

    it("should return a function", function () {
        assert.equal(typeof less(), "function");
    });

    it("should render LESS into CSS", function (done) {
        var root = fixture();

        var duo = new Duo(root)
            .entry("example.less")
            .use(less());

        duo.run(function (err, file) {
            if (err) return done(err);
            assert.equal(file, read(fixture("example.css"), "utf8"));
            done();
        });
    });
Example #12
0
file.isPathAbsolute = function() {
  var filepath = path.join.apply(path, arguments);
  return pathIsAbsolute(filepath);
};
Example #13
0
file.isDir = function() {
  var filepath = path.join.apply(path, arguments);
  return file.exists(filepath) && fs.statSync(filepath).isDirectory();
};
Example #14
0
file.setBase = function() {
  var dirpath = path.join.apply(path, arguments);
  process.chdir(dirpath);
};
Example #15
0
  resolveModule(
    from: Path,
    moduleName: string,
    options?: ResolveModuleConfig,
  ): Path {
    const dirname = path.dirname(from);
    const paths = this._options.modulePaths;
    const moduleDirectory = this._options.moduleDirectories;
    const key = dirname + path.delimiter + moduleName;
    const defaultPlatform = this._options.defaultPlatform;
    const extensions = this._options.extensions.slice();
    if (this._supportsNativePlatform()) {
      extensions.unshift('.' + NATIVE_PLATFORM + '.js');
    }
    if (defaultPlatform) {
      extensions.unshift('.' + defaultPlatform + '.js');
    }

    // 0. If we have already resolved this module for this directory name,
    //    return a value from the cache.
    if (this._moduleNameCache[key]) {
      return this._moduleNameCache[key];
    }

    // 1. Check if the module is a haste module.
    let module = this.getModule(moduleName);
    if (module) {
      return (this._moduleNameCache[key] = module);
    }

    // 2. Check if the module is a node module and resolve it based on
    //    the node module resolution algorithm.
    // If skipNodeResolution is given we ignore all modules that look like
    // node modules (ie. are not relative requires). This enables us to speed
    // up resolution when we build a dependency graph because we don't have
    // to look at modules that may not exist and aren't mocked.
    const skipResolution =
      options && options.skipNodeResolution && !moduleName.includes(path.sep);

    const resolveNodeModule = name => {
      return Resolver.findNodeModule(name, {
        basedir: dirname,
        browser: this._options.browser,
        extensions,
        moduleDirectory,
        paths,
        resolver: this._options.resolver,
      });
    };

    if (!skipResolution) {
      module = resolveNodeModule(moduleName);

      if (module) {
        return (this._moduleNameCache[key] = module);
      }
    }

    // 3. Resolve "haste packages" which are `package.json` files outside of
    // `node_modules` folders anywhere in the file system.
    const parts = moduleName.split('/');
    const hastePackage = this.getPackage(parts.shift());
    if (hastePackage) {
      try {
        const module = path.join.apply(
          path,
          [path.dirname(hastePackage)].concat(parts),
        );
        // try resolving with custom resolver first to support extensions,
        // then fallback to require.resolve
        return (this._moduleNameCache[key] =
          resolveNodeModule(module) || require.resolve(module));
      } catch (ignoredError) {}
    }

    // 4. Throw an error if the module could not be found. `resolve.sync`
    //    only produces an error based on the dirname but we have the actual
    //    current module name available.
    const relativePath = path.relative(dirname, from);
    const err = new Error(
      `Cannot find module '${moduleName}' from '${relativePath || '.'}'`,
    );
    (err: Error & {code?: string}).code = 'MODULE_NOT_FOUND';
    throw err;
  }
Example #16
0
var assert = require('assert'),
    fs = require('fs'),
    path = require('path'),
    read = require('fs').readFileSync,
    glob = require('glob'),
    rimraf = require('rimraf'),
    stream = require('stream'),
    spawn = require('cross-spawn'),
    cli = path.join(__dirname, '..', 'bin', 'node-sass'),
    fixture = path.join.bind(null, __dirname, 'fixtures');

describe('cli', function() {
  describe('node-sass < in.scss', function() {
    it('should read data from stdin', function(done) {
      var src = fs.createReadStream(fixture('simple/index.scss'));
      var expected = read(fixture('simple/expected.css'), 'utf8').trim();
      var bin = spawn(cli);

      bin.stdout.setEncoding('utf8');
      bin.stdout.once('data', function(data) {
        assert.equal(data.trim(), expected.replace(/\r\n/g, '\n'));
        done();
      });

      src.pipe(bin.stdin);
    });

    it('should compile sass using the --indented-syntax option', function(done) {
      var src = fs.createReadStream(fixture('indent/index.sass'));
      var expected = read(fixture('indent/expected.css'), 'utf8').trim();
      var bin = spawn(cli, ['--indented-syntax']);
			        deps.forEach(function(dep, i) {
			            var dependency = workingdir.concat([dep]);
			            deps[i] = path.join.apply(null, dependency);
			        });
Example #18
0
function base () {
    var args = Array.prototype.slice.call(arguments);
    return path.join.apply(null, [__dirname].concat(args));
}
Example #19
0
 path: function() {
   var parts = Array.prototype.slice.call(arguments);
   return path.join.apply(path, [ root ].concat(parts));
 },
Example #20
0
		var joinPath = function() {
			return '.' + path.sep + path.join.apply(path, arguments);
		}
Example #21
0
 exports.path[pathName] = function pathJoin() {
   const pathValue = exports.paths[pathName];
   const funcArgs = Array.prototype.slice.call(arguments);
   const joinArgs = [pathValue].concat(funcArgs);
   return path.join.apply(this, joinArgs);
 };
Example #22
0
function getPath() {
  var args = [__dirname].concat(Array.prototype.slice.call(arguments));
  return path.join.apply(path, args);
}
Example #23
0
exports.isFile = function() {
  var filepath = path.join.apply(path, arguments);
  return this.exists(filepath) && fs.statSync(filepath).isFile();
};
module.exports = function(grunt) {
  // External lib.
  var phantomjs = require('grunt-lib-phantomjs').init(grunt);

  var collector = new istanbul.Collector();

  var reporter;

  // Growl is optional
  var growl;
  try {
    growl = require('growl');
  } catch(e) {
    growl = function(){};
    grunt.verbose.write('Growl not found, \'npm install growl\' for Growl support');
  }

  // Get an asset file, local to the root of the project.
  var asset = path.join.bind(null, __dirname, '..');

  // Manage runners listening to phantomjs
  var phantomjsEventManager = (function() {
    var listeners = {};
    var suites = [];

    // Hook on Phantomjs Mocha reporter events.
    phantomjs.on('mocha.*', function(test) {
      var name, fullTitle, slow, err;
      var evt = this.event.replace('mocha.', '');

      if (evt === 'end') {
        phantomjs.halt();
      }

      // Expand test values (and façace the Mocha test object)
      if (test) {
        fullTitle = test.fullTitle;
        test.fullTitle = function() {
          return fullTitle;
        };

        slow = this.slow;
        test.slow = function() {
          return slow;
        };

        test.parent = suites[suites.length - 1] || null;

        err = test.err;
      }

      if (evt === 'suite') {
          suites.push(test);
      } else if (evt === 'suite end') {
          suites.pop(test);
      }

      // Trigger events for each runner listening
      for (name in listeners) {
        listeners[name].emit.call(listeners[name], evt, test, err);
      }
    });

    return {
      add: function(name, runner) {
        listeners[name] = runner;
      },
      remove: function(name) {
        delete listeners[name];
      }
    };
  }());

  phantomjs.on('istanbul.coverage', function(coverage) {
    if (coverage) {
      collector.add(coverage);
    }
  });

  // Built-in error handlers.
  phantomjs.on('fail.load', function(url) {
    phantomjs.halt();
    grunt.verbose.write('Running PhantomJS...').or.write('...');
    grunt.log.error();
    grunt.warn('PhantomJS unable to load "' + url + '" URI.', 90);
  });

  phantomjs.on('fail.timeout', function() {
    phantomjs.halt();
    grunt.log.writeln();
    grunt.warn('PhantomJS timed out, possibly due to a missing Mocha run() call.', 90);
  });

  // Debugging messages.
  phantomjs.on('debug', grunt.log.debug.bind(grunt.log, 'phantomjs'));

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('mocha', 'Run Mocha unit tests in a headless PhantomJS instance.', function() {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      // Output console.log calls
      log: false,
      // Mocha reporter
      reporter: 'Dot',
      // Default PhantomJS timeout.
      timeout: 5000,
      // Mocha-PhantomJS bridge file to be injected.
      inject: asset('phantomjs/bridge.js'),
      // Main PhantomJS script file
      phantomScript: asset('phantomjs/main.js'),
      // Explicit non-file URLs to test.
      urls: [],
      // Fail with grunt.warn on first test failure
      bail: false,
      // Log script errors as grunt errors
      logErrors: false,
      // Growl notification when tests pass.
      growlOnSuccess: true
    });

    // Output console messages if log == true
    if (options.log) {
      phantomjs.removeAllListeners(['console']);
      phantomjs.on('console', grunt.log.writeln);
    } else {
      phantomjs.off('console', grunt.log.writeln);
    }

    // Output errors on script errors
    if (options.logErrors) {
      phantomjs.on('error.*', function(error, stack) {
        var formattedStack = _.map(stack, function(frame) {
          return "    at " + (frame.function ? frame.function : "undefined") + " (" + frame.file + ":" + frame.line + ")";
        }).join("\n");
        grunt.fail.warn(error + "\n" + formattedStack, 3);
      });
    }

    var optsStr = JSON.stringify(options, null, '  ');
    grunt.verbose.writeln('Options: ' + optsStr);

    // Clean Phantomjs options to prevent any conflicts
    var PhantomjsOptions = _.omit(options, 'reporter', 'urls', 'log', 'bail');

    var phantomOptsStr = JSON.stringify(PhantomjsOptions, null, '  ');
    grunt.verbose.writeln('Phantom options: ' + phantomOptsStr);

    // Combine any specified URLs with src files.
    var urls = options.urls.concat(_.compact(this.filesSrc));

    // Remember all stats from all tests
    var testStats = [];

    // This task is asynchronous.
    var done = this.async();

    // Hijack console.log to capture reporter output
    var dest = this.data.dest;
    var output = [];
    var consoleLog = console.log;
    // Latest mocha xunit reporter sends to process.stdout instead of console
    var processWrite = process.stdout.write;


    // Only hijack if we really need to
    if (dest) {
      console.log = function() {
        consoleLog.apply(console, arguments);
        // FIXME: This breaks older versions of mocha
        // processWrite.apply(process.stdout, arguments);
        output.push(util.format.apply(util, arguments));
      };
    }

    // Process each filepath in-order.
    grunt.util.async.forEachSeries(urls, function(url, next) {
      grunt.log.writeln('Testing: ' + url);

      // create a new mocha runner façade
      var runner = new EventEmitter();
      phantomjsEventManager.add(url, runner);

      // Clear runner event listener when test is over
      runner.on('end', function() {
        phantomjsEventManager.remove(url);
      });

      // Set Mocha reporter
      var Reporter = null;
      if (reporters[options.reporter]) {
        Reporter = reporters[options.reporter];
      } else {
        // Resolve external reporter module
        var externalReporter;
        try {
          externalReporter = require.resolve(options.reporter);
        } catch (e) {
          // Resolve to local path
          externalReporter = path.resolve(options.reporter);
        }

        if (externalReporter) {
          try {
            Reporter = require(externalReporter);
          }
          catch (e) { }
        }
      }
      if (Reporter === null) {
        grunt.fatal('Specified reporter is unknown or unresolvable: ' + options.reporter);
      }
      reporter = new Reporter(runner);

      // Launch PhantomJS.
      phantomjs.spawn(url, {
        // Exit code to use if PhantomJS fails in an uncatchable way.
        failCode: 90,
        // Additional PhantomJS options.
        options: PhantomjsOptions,
        // Do stuff when done.
        done: function(err) {
          var stats = runner.stats;
          testStats.push(stats);

          if (err) {
            // Show Growl notice
            // @TODO: Get an example of this
            // growl('PhantomJS Error!');

            // If there was a PhantomJS error, abort the series.
            grunt.fatal(err);
            done(false);
          } else {
            // If failures, show growl notice
            if (stats.failures > 0) {
              var reduced = helpers.reduceStats([stats]);
              var failMsg = reduced.failures + '/' + reduced.tests +
                ' tests failed (' + reduced.duration + 's)';

              // Show Growl notice, if avail
              growl(failMsg, {
                image: asset('growl/error.png'),
                title: 'Failure in ' + grunt.task.current.target,
                priority: 3
              });

              // Bail tests if bail option is true
              if (options.bail) grunt.warn(failMsg);
            }

            // Process next file/url
            next();
          }
        }
      });
    },
    // All tests have been run.
    function() {
      if (dest) {
        // Restore console.log to original and write the output
        console.log = consoleLog;
        grunt.file.write(dest, output.join('\n'));
      }

      var stats = helpers.reduceStats(testStats);

      if (stats.failures === 0) {
        var okMsg = stats.tests + ' passed!' + ' (' + stats.duration + 's)';

        if (options.growlOnSuccess) {
          growl(okMsg, {
            image: asset('growl/ok.png'),
            title: okMsg,
            priority: 3
          });
        }

        grunt.log.ok(okMsg);

        var finalCoverage = collector.getFinalCoverage(); // TODO do this a different way, bad for large # of files
        stats.coverage = istanbul.utils.summarizeCoverage(finalCoverage);

        //
        //console.log('final_coverage', finalCoverage);
        coverageInfo = set(finalCoverage);

        if (options.coverage.dir) {
          grunt.log.writeln('Writing a full lcov coverage report to ', options.coverage.dir);
          writeIstanbulReport(grunt, coverageInfo, options);
          done(true);
          return;
        }
        //

        var coverageFile = options.coverage && options.coverage.coverageFile || 'coverage/coverage.json';

        // check if coverage was enable during the testrun
        if (stats.coverage && stats.coverage.lines && stats.coverage.lines.total > 0 && coverageFile) {

          // write the coverage json to a file
          grunt.file.write(coverageFile, JSON.stringify(finalCoverage));

          grunt.log.ok('Coverage:');
          grunt.log.ok('-  Lines: ' + stats.coverage.lines.pct + '%');
          grunt.log.ok('-  Statements: ' + stats.coverage.statements.pct + '%');
          grunt.log.ok('-  Functions: ' + stats.coverage.functions.pct + '%');
          grunt.log.ok('-  Branches: ' + stats.coverage.branches.pct + '%');
        }

        // Async test pass
        done(true);

      } else {
        var failMsg = stats.failures + '/' + stats.tests + ' tests failed (' +
          stats.duration + 's)';

        // Show Growl notice, if avail
        growl(failMsg, {
          image: asset('growl/error.png'),
          title: failMsg,
          priority: 3
        });

        // Bail tests if bail option is true
        if (options.bail) {
          grunt.warn(failMsg);
        } else {
          grunt.log.error(failMsg);
        }

        // Async test fail
        done(false);
      }
    });
  });
};
Example #25
0
exports.exists = function() {
  var filepath = path.join.apply(path, arguments);
  return fs.existsSync(filepath);
};
Example #26
0
'use strict';

require('mocha');
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var Lexer = require('../lib/lexer');

var fixtures = path.join.bind(path, __dirname, 'fixtures');

function read(filepath) {
  return fs.readFileSync(filepath);
}
function fixture(filepath) {
  return read(fixtures(filepath));
}

describe('lexer', function() {
  describe.skip('whitespace', function() {
    it('should capture indentation', function() {
      var str = fixture('block-indent.html');
      var lexer = new Lexer({path: 'string', contents: str});
      var tok = lexer.tokenize();
      console.log(tok);
    });

    it('should capture significant whitespace', function() {
      var str = fixture('layout-text-node.html');
      var lexer = new Lexer({path: 'string', contents: str});
      var tok = lexer.tokenize();
      console.log(tok);
Example #27
0
var fse = require("fs-extra");
var path = require("path");
var local = path.join.bind(path, __dirname);
var exec = require('../utils/execPromise');

var NodeGit = require('..');

if(process.env.NODEGIT_TEST_THREADSAFETY) {
  console.log('Enabling thread safety in NodeGit');
  NodeGit.enableThreadSafety();
} else if (process.env.NODEGIT_TEST_THREADSAFETY_ASYNC) {
  console.log('Enabling thread safety for async actions only in NodeGit');
  NodeGit.setThreadSafetyStatus(NodeGit.THREAD_SAFETY.ENABLED_FOR_ASYNC_ONLY);
}

var workdirPath = local("repos/workdir");

before(function() {
  this.timeout(350000);

  var url = "https://github.com/nodegit/test";
  return fse.remove(local("repos"))
    .then(function() {
      fse.remove(local("home"))
    })
    .then(function() {
      fse.mkdir(local("repos"));
    })
    .then(function() {
      return exec("git init " + local("repos", "empty"));
    })
Example #28
0
"use strict";var urlParser=require("url");var http=require("http");var https=require("https");var util=require("util");var path=require("path");var fs=require("fs");var events=require("events");var crypto=require("crypto");var expressionCache={};var regexpMail=new RegExp("^[a-zA-Z0-9-_.]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$");var regexpUrl=new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");var ENCODING="utf8";var UNDEFINED="undefined";var STRING="string";var FUNCTION="function";var NUMBER="number";var OBJECT="object";var BOOLEAN="boolean";var NEWLINE="\r\n";var VERSION=typeof framework!==UNDEFINED?"v"+framework.version:"";if(typeof setImmediate===UNDEFINED){global.setImmediate=function(cb){process.nextTick(cb)}}var hasOwnProperty=Object.prototype.hasOwnProperty;function expression(query,params){var name=params.join(",");var fn=expressionCache[query+"-"+name];if(!fn){fn=eval("(function("+name+"){"+(query.indexOf("return")===-1?"return ":"")+query+"})");expressionCache[query+name]=fn}var values=[];for(var i=2;i<arguments.length;i++)values.push(arguments[i]);return function(){var arr=[];for(var i=0;i<arguments.length;i++)arr.push(arguments[i]);for(var i=0;i<values.length;i++)arr.push(values[i]);return fn.apply(this,arr)}}global.expression=expression;exports.isEmpty=function(obj){if(obj===null)return true;if(obj.length&&obj.length>0)return false;if(obj.length===0)return true;for(var key in obj){if(hasOwnProperty.call(obj,key))return false}return true};exports.request=function(url,method,data,callback,headers,encoding,timeout){var uri=urlParser.parse(url);var h={};var isJSON=typeof data===OBJECT;encoding=encoding||ENCODING;method=(method||"").toString().toUpperCase();if(method!=="GET")h["Content-Type"]="application/x-www-form-urlencoded";if(isJSON)h["Content-Type"]="application/json";util._extend(h,headers);h["X-Powered-By"]="partial.js"+VERSION;var options={protocol:uri.protocol,auth:uri.auth,method:method,hostname:uri.hostname,port:uri.port,path:uri.path,agent:false,headers:h};var response=function(res){if(!callback){res.resume();return}res._buffer="";res.on("data",function(chunk){this._buffer+=chunk.toString(encoding)});res.on("end",function(){callback(null,this._buffer,res.statusCode,res.headers)});res.resume()};var con=options.protocol==="https:"?https:http;try{var isPOST=method==="POST"||method==="PUT";var req=isPOST?callback?con.request(options,response):con.request(options):callback?con.get(options,response):con.get(options);if(callback){req.on("error",function(error){callback(error,null,0,{})});req.setTimeout(timeout||1e4,function(){callback(new Error(exports.httpStatus(408)),null,0,{})})}if(isPOST)req.end(isJSON?JSON.stringify(data):(data||"").toString(),encoding)}catch(ex){if(callback)callback(ex,null,0,{});return false}return true};exports.download=function(url,callback,headers,method,params,encoding){var uri=urlParser.parse(url);var h={};method=(method||"").toString().toUpperCase();encoding=encoding||ENCODING;util._extend(h,headers);h["X-Powered-By"]="partial.js"+VERSION;var options={protocol:uri.protocol,auth:uri.auth,method:method,hostname:uri.hostname,port:uri.port,path:uri.path,agent:false,headers:h};var response=function(res){callback(null,res)};var con=options.protocol==="https:"?https:http;try{var isPOST=method==="POST"||method==="PUT";var req=isPOST?callback?con.request(options,response):con.request(options):callback?con.get(options,response):con.get(options);if(callback){req.on("error",function(error){callback(error,null)})}if(isPOST)req.end((params||"").toString(),ENCODING)}catch(ex){if(callback)callback(ex,null);return false}return true};exports.send=function(name,stream,url,callback,headers,method){var self=this;if(typeof callback==="object"){var tmp=headers;callback=headers;headers=tmp}if(typeof stream===STRING)stream=fs.createReadStream(stream,{flags:"r"});var BOUNDARY="----"+Math.random().toString(16).substring(2);var h={};if(headers)util._extend(h,headers);name=path.basename(name);h["Cache-Control"]="max-age=0";h["Content-Type"]="multipart/form-data; boundary="+BOUNDARY;h["X-Powered-By"]="partial.js"+VERSION;var uri=urlParser.parse(url);var options={protocol:uri.protocol,auth:uri.auth,method:method||"POST",hostname:uri.hostname,port:uri.port,path:uri.path,agent:false,headers:h};var response=function(res){if(!callback)return;res.body="";res.on("data",function(chunk){this.body+=chunk.toString(ENCODING)});res.on("end",function(){callback(null,res.body)})};var connection=options.protocol==="https:"?https:http;var req=connection.request(options,response);if(callback){req.on("error",function(err){callback(err,null)})}var header=NEWLINE+NEWLINE+"--"+BOUNDARY+NEWLINE+'Content-Disposition: form-data; name="File"; filename="'+name+'"'+NEWLINE+"Content-Type: "+utils.getContentType(path.extname(name))+NEWLINE+NEWLINE;req.write(header);stream.on("end",function(){req.end(NEWLINE+NEWLINE+"--"+BOUNDARY+"--")});stream.pipe(req,{end:false});return self};exports.trim=function(obj){var type=typeof obj;if(type===STRING)return obj.trim();if(type!==OBJECT)return obj;Object.keys(obj).forEach(function(name){var val=obj[name];if(typeof val===OBJECT){exports.trim(val);return}if(typeof val!==STRING)return;obj[name]=val.trim()});return obj};exports.noop=function(){};exports.httpStatus=function(code,addCode){return(addCode||true?code+": ":"")+http.STATUS_CODES[code]};exports.extend=function(target,source,rewrite){if(target===null||source===null)return target;if(typeof target!==OBJECT||typeof source!==OBJECT)return target;var keys=Object.keys(source);var i=keys.length;while(i--){var key=keys[i];if(rewrite||typeof target[key]===UNDEFINED)target[key]=source[key]}return target};exports.copy=function(target,source,rewrite){if(target===null||source===null)return target;if(typeof target!==OBJECT||typeof source!==OBJECT)return target;if(typeof rewrite===UNDEFINED)rewrite=true;var keys=Object.keys(source);var i=keys.length;while(i--){var key=keys[i];if(typeof target[key]===UNDEFINED)continue;if(rewrite){target[key]=source[key];continue}target[key]=source[key]}return target};exports.reduce=function(source,prop){if(source===null||prop===null)return source;var type=typeof prop;if(prop instanceof Array){Object.keys(source).forEach(function(o){if(prop.indexOf(o)===-1)delete source[o]})}if(type===OBJECT){var obj=Object.keys(prop);Object.keys(source).forEach(function(o){if(obj.indexOf(o)===-1)delete source[o]})}return source};exports.isRelative=function(url){return!(url.substring(0,2)==="//"||url.indexOf("http://")!==-1||url.indexOf("https://")!==-1)};exports.htmlEncode=function(str){var type=typeof str;if(type===UNDEFINED)return"";if(type!==STRING)str=str.toString();return str.htmlEncode()};exports.htmlDecode=function(str){var type=typeof str;if(type===UNDEFINED)return"";if(type!==STRING)str=str.toString();return str.htmlDecode()};exports.isStaticFile=function(url){var pattern=/\.\w{2,8}($|\?)+/g;return pattern.test(url)};exports.isNullOrEmpty=function(str){if(typeof str!==STRING)return true;return str.length===0};exports.parseInt=function(obj,def){var type=typeof obj;if(type===UNDEFINED)return def||0;var str=type!==STRING?obj.toString():obj;return str.parseInt(def,10)};exports.parseFloat=function(obj,def){var type=typeof obj;if(type===UNDEFINED)return def||0;var str=type!==STRING?obj.toString():obj;return str.parseFloat(def)};exports.isArray=function(obj){return util.isArray(obj)};exports.isDate=function(obj){return util.isDate(obj)};exports.getContentType=function(ext){if(ext[0]===".")ext=ext.substring(1);var extension={ai:"application/postscript",appcache:"text/cache-manifest",avi:"video/avi",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",less:"text/css",sass:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/msword",dtd:"application/xml-dtd",eps:"application/postscript",exe:"application/octet-stream",gif:"image/gif",gzip:"application/x-gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",ifb:"text/calendar",jpe:"image/jpeg",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",m4a:"audio/mp4a-latm",m4v:"video/x-m4v",md:"text/markdown",mid:"audio/midi",midi:"audio/midi",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mpe:"video/mpeg",mpeg:"video/mpeg",mpg:"video/mpeg",mpga:"audio/mpeg",mv4:"video/mv4",ogg:"application/ogg",pdf:"application/pdf",png:"image/png",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.ms-powerpoint",ps:"application/postscript",rar:"application/x-rar-compressed",rtf:"text/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",txt:"text/plain",wav:"audio/x-wav",webp:"image/webp",woff:"font/woff",xht:"application/xhtml+xml",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",zip:"application/zip"};return extension[ext.toLowerCase()]||"application/octet-stream"};exports.etag=function(text,version){var sum=0;var length=text.length;for(var i=0;i<length;i++)sum+=text.charCodeAt(i);return sum.toString()+(version?":"+version:"")};exports.path=function(path,delimiter){delimiter=delimiter||"/";if(path[path.length-1]===delimiter)return path;return path+delimiter};exports.random=function(max,min){max=max||1e5;min=min||0;return Math.floor(Math.random()*(max-min+1))+min};exports.GUID=function(max){max=max||40;var rnd=function(){return Math.floor(Math.random()*65536).toString(16)};var str="";for(var i=0;i<max/4+1;i++)str+=rnd();return str.substring(0,max)};exports.validate=function(model,properties,prepare,builder,resource,path){if(typeof builder===FUNCTION&&typeof resource===UNDEFINED){resource=builder;builder=null}var error=builder;var current=typeof path===UNDEFINED?"":path+".";var isSchema=false;var schemaName="";var definition=null;if(!(error instanceof builders.ErrorBuilder))error=new builders.ErrorBuilder(resource);if(typeof properties===STRING){var schema=builders.validation(properties);if(schema.length!==0){schemaName=properties;properties=schema;isSchema=true;definition=builders.schema(schemaName)}else properties=properties.replace(/\s/g,"").split(",")}if(typeof model===UNDEFINED||model===null)model={};if(typeof prepare!==FUNCTION)throw new Error("Validate hasn't any method to validate properties.\nDefine delegate: framework.onValidate ...");for(var i=0;i<properties.length;i++){var name=properties[i].toString();var value=model[name];var type=typeof value;value=(type===FUNCTION?model[name]():model[name])||"";if(type!==OBJECT&&isSchema){if(builders.isJoin(definition[name]))type=OBJECT}if(type===OBJECT){if(isSchema){var schema=builders.schema(schemaName)||null;if(schema!==null){schema=schema[name]||null;if(schema!==null){var isArray=schema[0]==="[";if(isArray)schema=schema.substring(1,schema.length-1);if(isArray){if(!(value instanceof Array)){error.add(name,"@");continue}var sublength=value.length;for(var j=0;j<sublength;j++)exports.validate(value[j],schema,prepare,error,resource,current+name);continue}exports.validate(value,schema,prepare,error,resource,current+name);continue}}}exports.validate(value,properties,prepare,error,resource,current+name);continue}var result=prepare(name,value,current+name);if(typeof result===UNDEFINED)continue;type=typeof result;if(type===STRING){error.add(name,result,current+name);continue}if(type===BOOLEAN){if(!result)error.add(name,"@",current+name);continue}if(result.isValid===false)error.add(name,result.error,current+name)}return error};exports.isValid=function(valid,error){return{isValid:valid,error:error||"@"}};exports.isEmail=function(str){return(str||"").toString().isEmail()};exports.isURL=function(str){return(str||"").toString().isURL()};exports.combine=function(){return"."+path.join.apply(this,arguments)};exports.removeDiacritics=function(str){var dictionaryA=["á","ä","č","ď","é","ě","ť","ž","ú","ů","ü","í","ï","ô","ó","ö","š","ľ","ĺ","ý","ÿ","č","ř"];var dictionaryB=["a","a","c","d","e","e","t","z","u","u","u","i","i","o","o","o","s","l","l","y","y","c","r"];var buf="";var length=str.length;for(var i=0;i<length;i++){var c=str[i];var isUpper=false;var index=dictionaryA.indexOf(c);if(index===-1){index=dictionaryA.indexOf(c.toLowerCase());isUpper=true}if(index===-1){buf+=c;continue}c=dictionaryB[index];if(isUpper)c=c.toUpperCase();buf+=c}return buf};exports.encode_WS=function(data){var bytesFormatted=[];bytesFormatted[0]=129;if(data.length<=125){bytesFormatted[1]=data.length}else if(data.length>=126&&data.length<=65535){bytesFormatted[1]=126;bytesFormatted[2]=data.length>>8&255;bytesFormatted[3]=data.length&255}else{bytesFormatted[1]=127;bytesFormatted[2]=data.length>>56&255;bytesFormatted[3]=data.length>>48&255;bytesFormatted[4]=data.length>>40&255;bytesFormatted[5]=data.length>>32&255;bytesFormatted[6]=data.length>>24&255;bytesFormatted[7]=data.length>>16&255;bytesFormatted[8]=data.length>>8&255;bytesFormatted[9]=data.length&255}var length=data.length;for(var i=0;i<length;i++)bytesFormatted.push(data.charCodeAt(i));return bytesFormatted};exports.decode_WS=function(data){var datalength=data[1]&127;var indexFirstMask=2;if(datalength===126)indexFirstMask=4;else if(datalength===127)indexFirstMask=10;var masks=data.slice(indexFirstMask,indexFirstMask+4);var i=indexFirstMask+4;var index=0;var output="";var length=data.length;while(i<length)output+=String.fromCharCode(data[i++]^masks[index++%4]);return output};exports.distance=function(lat1,lon1,lat2,lon2){var R=6371;var dLat=(lat2-lat1).toRad();var dLon=(lon2-lon1).toRad();var a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(lat1.toRad())*Math.cos(lat2.toRad())*Math.sin(dLon/2)*Math.sin(dLon/2);var c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));return(R*c).floor(3)};exports.ls=function(path,callback,filter){var filelist=new FileList;filelist.onComplete=callback;filelist.onFilter=filter||null;filelist.walk(path)};Date.prototype.add=function(type,value){var self=this;switch(type){case"s":case"ss":case"second":case"seconds":self.setSeconds(self.getSeconds()+value);return self;case"m":case"mm":case"minute":case"minutes":self.setMinutes(self.getMinutes()+value);return self;case"h":case"hh":case"hour":case"hours":self.setHours(self.getHours()+value);return self;case"d":case"dd":case"day":case"days":self.setDate(self.getDate()+value);return self;case"M":case"MM":case"month":case"months":self.setMonth(self.getMonth()+value);return self;case"y":case"yyyy":case"year":case"years":self.setFullYear(self.getFullYear()+value);return self}return self};Date.prototype.format=function(format){var self=this;var h=self.getHours();var m=self.getMinutes().toString();var s=self.getSeconds().toString();var M=(self.getMonth()+1).toString();var yyyy=self.getFullYear().toString();var d=self.getDate().toString();var a="AM";var H=h.toString();if(h>=12){h-=12;a="PM"}if(h===0)h=12;h=h.toString();var hh=h.padLeft(2,"0");var HH=H.padLeft(2,"0");var mm=m.padLeft(2,"0");var ss=s.padLeft(2,"0");var MM=M.padLeft(2,"0");var dd=d.padLeft(2,"0");var yy=yyyy.substring(2);return format.replace(/yyyy/g,yyyy).replace(/yy/g,yy).replace(/MM/g,MM).replace(/M/g,M).replace(/dd/g,dd).replace(/d/g,d).replace(/HH/g,HH).replace(/H/g,H).replace(/hh/g,hh).replace(/h/g,h).replace(/mm/g,mm).replace(/m/g,m).replace(/ss/g,ss).replace(/s/g,ss).replace(/a/g,a)};if(!String.prototype.trim){String.prototype.trim=function(){return this.replace(/^[\s]+|[\s]+$/g,"")}}String.prototype.count=function(text){var index=0;var count=0;do{index=this.indexOf(text,index+text.length);if(index>0)count++}while(index>0);return count};String.prototype.parseDate=function(){return new Date(this.toString())};String.prototype.contains=function(value,mustAll){var str=this.toString();if(typeof value===STRING)return str.indexOf(value)!==-1;var length=value.length;for(var i=0;i<length;i++){var exists=str.indexOf(value[i])!==-1;if(mustAll){if(!exists)return false}else if(exists)return true}return mustAll?true:false};String.prototype.configuration=function(){var arr=this.split("\n");var length=arr.length;var obj={};for(var i=0;i<length;i++){var str=arr[i];if(str==="")continue;if(str.substring(0,2)==="//")continue;var index=str.indexOf(":");if(index===-1)continue;obj[str.substring(0,index).trim()]=str.substring(index+1).trim()}return obj};String.prototype.format=function(){var formatted=this;var length=arguments.length;for(var i=0;i<length;i++){var regexp=new RegExp("\\{"+i+"\\}","gi");formatted=formatted.replace(regexp,arguments[i])}return formatted};String.prototype.htmlEncode=function(){return this.replace(/\&/g,"&amp;").replace(/\>/g,"&gt;").replace(/\</g,"&lt;").replace(/\"/g,"&quot;")};String.prototype.htmlDecode=function(){return this.replace(/&gt;/g,">").replace(/\&lt;/g,"<").replace(/\&quot;/g,'"').replace(/&amp;/g,"&")};String.prototype.urlEncode=function(){return encodeURIComponent(this)};String.prototype.urlDecode=function(){return decodeURIComponent(this)};String.prototype.params=function(obj){var formatted=this.toString();if(typeof obj===UNDEFINED||obj===null)return formatted;var reg=/\{[^}\n]*\}/g;var match=formatted.match(reg);if(match===null)return formatted;var length=match.length;for(var i=0;i<length;i++){var prop=match[i];var isEncode=false;var name=prop.substring(1,prop.length-1).trim();var format="";var index=name.indexOf("|");if(index!==-1){format=name.substring(index+1,name.length).trim();name=name.substring(0,index).trim()}if(prop.substring(0,2)==="{!")name=name.substring(1);else isEncode=true;var val;if(name.indexOf(".")!==-1){var arr=name.split(".");if(arr.length===2)val=obj[arr[0]][arr[1]];else if(arr.length===3)val=obj[arr[0]][arr[1]][arr[3]];else if(arr.length===4)val=obj[arr[0]][arr[1]][arr[3]][arr[4]];else if(arr.length===5)val=obj[arr[0]][arr[1]][arr[3]][arr[4]][arr[5]]}else val=name.length===0?obj:obj[name];if(typeof val===FUNCTION)val=val(index);if(typeof val===UNDEFINED)return;if(format.length>0){var type=typeof val;if(type===STRING){var max=parseInt(format,10);if(!isNaN(max))val=val.max(max+3,"...")}else if(type===NUMBER||util.isDate(val))val=val.format(format)}val=val.toString().dollar();formatted=formatted.replace(prop,isEncode?exports.htmlEncode(val):val)}return formatted};String.prototype.max=function(length,chars){var str=this.toString();chars=chars||"...";return str.length>length?str.substring(0,length-chars.length)+chars:str};String.prototype.isJSON=function(){var self=this;if(self.length<=1)return false;var a=self[0];var b=self[self.length-1];return a==='"'&&b==='"'||a==="["&&b==="]"||a==="{"&&b==="}"};String.prototype.isURL=function(){var str=this.toString();if(str.length<=7)return false;return regexpUrl.test(str)};String.prototype.isEmail=function(){var str=this.toString();if(str.length<=4)return false;if(str[0]==="."||str[str.length-1]===".")return false;return regexpMail.test(str)};String.prototype.parseInt=function(def){var num=0;var str=this.toString();if(str.substring(0,1)==="0")num=parseInt(str.replace(/\s/g,"").substring(1),10);else num=parseInt(str.replace(/\s/g,""),10);if(isNaN(num))return def||0;return num};String.prototype.parseFloat=function(def){var num=0;var str=this.toString();if(str.substring(0,1)==="0")num=parseFloat(str.replace(/\s/g,"").substring(1).replace(",","."));else num=parseFloat(str.replace(/\s/g,"").replace(",","."));if(isNaN(num))return def||0;return num};String.prototype.toUnicode=function(){var result="";var self=this.toString();var length=self.length;for(var i=0;i<length;++i){if(self.charCodeAt(i)>126||self.charCodeAt(i)<32)result+="\\u"+self.charCodeAt(i).hex(4);else result+=self[i]}return result};String.prototype.fromUnicode=function(){var str=this.replace(/\\u([\d\w]{4})/gi,function(match,v){return String.fromCharCode(parseInt(v,16))});return unescape(str)};String.prototype.sha1=function(){var hash=crypto.createHash("sha1");hash.update(this.toString(),ENCODING);return hash.digest("hex")};String.prototype.md5=function(){var hash=crypto.createHash("md5");hash.update(this.toString(),ENCODING);return hash.digest("hex")};String.prototype.encode=function(key,isUnique){var str="0"+this.toString();var data_count=str.length;var key_count=key.length;var change=str[data_count-1];var random=isUnique||true?exports.random(120)+40:65;var count=data_count+random%key_count;var values=[];var index=0;values[0]=String.fromCharCode(random);var counter=this.length+key.length;for(var i=count-1;i>0;i--){index=str.charCodeAt(i%data_count);values[i]=String.fromCharCode(index^(key.charCodeAt(i%key_count)^random))}var hash=new Buffer(counter+"="+values.join(""),ENCODING).toString("base64").replace(/\//g,"-").replace(/\+/g,"_");index=hash.indexOf("=");if(index>0)return hash.substring(0,index);return hash};String.prototype.decode=function(key){var values=this.toString().replace(/\-/g,"/").replace(/\_/g,"+");var mod=values.length%4;if(mod>0){for(var i=0;i<mod;i++)values+="="}values=new Buffer(values,"base64").toString(ENCODING);var index=values.indexOf("=");if(index===-1)return"";var counter=parseInt(values.substring(0,index),10);if(isNaN(counter))return"";values=values.substring(index+1);var count=values.length;var random=values.charCodeAt(0);var key_count=key.length;var data_count=count-random%key_count;var decrypt_data=[];for(var i=data_count-1;i>0;i--){index=values.charCodeAt(i)^(random^key.charCodeAt(i%key_count));decrypt_data[i]=String.fromCharCode(index)}var val=decrypt_data.join("");if(counter!==val.length+key.length)return"";return val};String.prototype.base64ToFile=function(filename,callback){var self=this.toString();var index=self.indexOf(",");if(index===-1)index=0;else index++;if(callback)fs.writeFile(filename,self.substring(index),"base64",callback);else fs.writeFile(filename,self.substring(index),"base64",exports.noop);return this};String.prototype.base64ContentType=function(){var self=this.toString();var index=self.indexOf(";");if(index===-1)return"";return self.substring(5,index)};String.prototype.removeDiacritics=function(){return exports.removeDiacritics(this)};String.prototype.indent=function(max,c){var self=this.toString();return new Array(max+1).join(c||" ")+self};String.prototype.isNumber=function(isDecimal){var self=this.toString();var length=self.length;if(length===0)return false;isDecimal=isDecimal||false;for(var i=0;i<length;i++){var ascii=self.charCodeAt(i);if(isDecimal){if(ascii===44||ascii===46){isDecimal=false;continue}}if(ascii<48||ascii>57)return false}return true};String.prototype.padLeft=function(max,c){var self=this.toString();return new Array(Math.max(0,max-self.length+1)).join(c||" ")+self};String.prototype.padRight=function(max,c){var self=this.toString();return self+new Array(Math.max(0,max-self.length+1)).join(c||" ")};String.prototype.insert=function(index,value){var str=this.toString();var a=str.substring(0,index);var b=value.toString()+str.substring(index);return a+b};String.prototype.dollar=function(){var str=this.toString();var index=str.indexOf("$",0);while(index!==-1){if(str[index+1]==="$")str=str.insert(index,"$");index=str.indexOf("$",index+2)}return str.toString()};String.prototype.link=function(max){max=max||60;var self=this.toString().trim().toLowerCase().removeDiacritics();var builder="";var length=self.length;for(var i=0;i<length;i++){var c=self[i];var code=self.charCodeAt(i);if(builder.length>=max)break;if(code>31&&code<48){if(builder[builder.length-1]==="-")continue;builder+="-";continue}if(code>47&&code<58){builder+=c;continue}if(code>94&&code<123){builder+=c;continue}}return builder};String.prototype.pluralize=function(zero,one,few,other){var str=this.toString();return str.parseInt().pluralize(zero,one,few,other)};String.prototype.isBoolean=function(){var self=this.toString().toLowerCase();return self==="true"||self==="false"?true:false};Number.prototype.floor=function(decimals){return Math.floor(this*Math.pow(10,decimals))/Math.pow(10,decimals)};Number.prototype.padLeft=function(max,c){return this.toString().padLeft(max,c||"0")};Number.prototype.padRight=function(max,c){return this.toString().padRight(max,c||"0")};Number.prototype.format=function(format){var index=0;var num=this.toString();var beg=0;var end=0;var max=0;var output="";if(typeof format===STRING){var d=false;for(var i=0;i<format.length;i++){var c=format[i];if(c==="#"){if(d)end++;else beg++}if(c===".")d=true}var strBeg=num;var strEnd="";index=num.indexOf(".");if(index!==-1){strBeg=num.substring(0,index);strEnd=num.substring(index+1)}if(strBeg.length>beg){max=strBeg.length-beg;var tmp="";for(var i=0;i<max;i++)tmp+="#";format=tmp+format}if(strBeg.length<beg)strBeg=strBeg.padLeft(beg," ");if(strEnd.length<end)strEnd=strEnd.padRight(end,"0");if(strEnd.length>end)strEnd=strEnd.substring(0,end);d=false;index=0;var skip=true;var length=format.length;for(var i=0;i<length;i++){var c=format[i];if(c!=="#"){if(skip)continue;if(c==="."){d=true;index=0}output+=c;continue}var value=d?strEnd[index]:strBeg[index];if(skip)skip=[","," "].indexOf(value)!==-1;if(!skip)output+=value;index++}return output}output="### ### ###";beg=num.indexOf(".");max=format||0;if(max===0&&num!=-1)max=num.length-(beg+1);if(max>0){output+=".";for(var i=0;i<max;i++)output+="#"}return this.format(output)};Number.prototype.pluralize=function(zero,one,few,other){var num=this;var value="";if(num===0)value=zero||"";else if(num===1)value=one||"";else if(num>1&&num<5)value=few||"";else value=other;var beg=value.indexOf("#");var end=value.lastIndexOf("#");if(beg===-1)return value;var format=value.substring(beg,end+1);return num.format(format)+value.replace(format,"")};Number.prototype.hex=function(length){var str=this.toString(16).toUpperCase();while(str.length<length)str="0"+str;return str};Number.prototype.condition=function(ifTrue,ifFalse){return(this%2===0?ifTrue:ifFalse)||""};Number.prototype.VAT=function(percentage,decimals,includedVAT){var num=this;var type=typeof decimals;if(type===BOOLEAN){var tmp=includedVAT;includedVAT=decimals;decimals=tmp;type=typeof decimals}if(type===UNDEFINED)decimals=2;if(typeof includedVAT===UNDEFINED)includedVAT=true;if(percentage===0||num===0)return num;return includedVAT?(num/(percentage/100+1)).floor(decimals):(num*(percentage/100+1)).floor(decimals)};Number.prototype.discount=function(percentage,decimals){var num=this;var type=typeof decimals;if(type===UNDEFINED)decimals=2;return(num-num/100*percentage).floor(decimals)};Number.prototype.parseDate=function(plus){return new Date(this+(plus||0))};if(typeof Number.prototype.toRad==="undefined"){Number.prototype.toRad=function(){return this*Math.PI/180}}Boolean.prototype.condition=function(ifTrue,ifFalse){return(this?ifTrue:ifFalse)||""};Array.prototype.take=function(count){var arr=[];var self=this;var length=self.length;for(var i=0;i<length;i++){arr.push(self[i]);if(arr.length>=count)return arr}return arr};Array.prototype.skip=function(count){var arr=[];var self=this;var length=self.length;for(var i=0;i<length;i++){if(i>=count)arr.push(self[i])}return arr};Array.prototype.where=function(cb){var self=this;var selected=[];var length=self.length;for(var i=0;i<length;i++){if(cb.call(self,self[i],i))selected.push(self[i])}return selected};Array.prototype.find=function(cb){var self=this;var length=self.length;for(var i=0;i<length;i++){if(cb.call(self,self[i],i))return self[i]}return null};Array.prototype.remove=function(cb){var self=this;var arr=[];var length=self.length;for(var i=0;i<length;i++){if(!cb.call(self,self[i],i))arr.push(self[i])}return arr};Array.prototype.random=function(){var self=this;return self[exports.random(self.length-1)]};Array.prototype.waiting=function(onItem,callback){var self=this;var item=self.shift();if(typeof item===UNDEFINED){if(callback)callback();return}onItem.call(self,item,function(){self.waiting(onItem,callback)});return self};Array.prototype.randomize=function(){var self=this;var random=(Math.floor(Math.random()*1e8)*10).toString();var index=0;var old=0;self.sort(function(a,b){var c=random[index++];if(typeof c===UNDEFINED){c=random[0];index=0}if(old>c){old=c;return-1}if(old===c){old=c;return 0}old=c;return 1});return self};function AsyncTask(owner,name,fn,cb,waiting){this.handlers={oncomplete:this.complete.bind(this)};this.isRunning=0;this.owner=owner;this.name=name;this.fn=fn;this.cb=cb;this.waiting=waiting;this.interval=null;this.isCanceled=false}AsyncTask.prototype.run=function(){var self=this;try{self.isRunning=1;self.owner.tasksWaiting[self.name]=true;self.owner.emit("begin",self.name);var timeout=self.owner.tasksTimeout[self.name];if(timeout>0)self.interval=setTimeout(self.timeout.bind(self),timeout);self.fn(self.handlers.oncomplete)}catch(ex){self.owner.emit("error",self.name,ex);self.complete()}return self};AsyncTask.prototype.timeout=function(timeout){var self=this;if(timeout>0){clearTimeout(self.interval);setTimeout(self.timeout.bind(self),timeout);return self}if(timeout<=0){clearTimeout(self.interval);setTimeout(self.timeout.bind(self),timeout);return self}self.cancel(true);return self};AsyncTask.prototype.cancel=function(isTimeout){var self=this;self.isCanceled=true;if(isTimeout)self.owner.emit("timeout",self.name);else self.owner.emit("cancel",self.name);self.fn=null;self.cb=null};AsyncTask.prototype.complete=function(){var item=this;var self=item.owner;item.isRunning=2;delete self.tasksPending[item.name];delete self.tasksWaiting[item.name];if(!item.isCanceled){try{self.emit("end",item.name);if(item.cb)item.cb()}catch(ex){self.emit("error",ex,item.name)}}self.reload();self.refresh();return self};function Async(owner){this._max=0;this._count=0;this._isRunning=false;this.owner=owner;this.onComplete=[];this.tasksPending={};this.tasksWaiting={};this.tasksAll=[];this.tasksTimeout={}}Async.prototype={get count(){return this._count},get percentage(){var self=this;return 100-Math.floor(self._count*100/self._max)}};Async.prototype.__proto__=new events.EventEmitter;Async.prototype.reload=function(){var self=this;self.tasksAll=Object.keys(self.tasksPending);self.emit("percentage",self.percentage);return self};Async.prototype.cancel=function(name){var self=this;if(typeof name===UNDEFINED){for(var i=0;i<self._count;i++)self.cancel(tasksAll[i]);return true}var task=self.tasksPending[name];if(!task)return false;delete self.tasksPending[name];delete self.tasksWaiting[name];task.cancel();self.reload();self.refresh();return true};Async.prototype.await=function(name,fn,cb){var self=this;if(typeof name===FUNCTION){cb=fn;fn=name;name=exports.GUID(6)}if(typeof self.tasksPending[name]!==UNDEFINED)return false;self.tasksPending[name]=new AsyncTask(self,name,fn,cb,null);self._max++;self.reload();self.refresh();return true};Async.prototype.wait=function(name,waitingFor,fn,cb){var self=this;if(typeof waitingFor===FUNCTION){cb=fn;fn=waitingFor;waitingFor=name;name=exports.GUID(6)}if(typeof self.tasksPending[name]!==UNDEFINED)return false;self.tasksPending[name]=new AsyncTask(self,name,fn,cb,waitingFor);self._max++;self.reload();self.refresh();return true};Async.prototype.complete=function(fn){return this.run(fn)};Async.prototype.run=function(fn){var self=this;self._isRunning=true;if(fn)self.onComplete.push(fn);self.refresh();return self};Async.prototype.isRunning=function(name){var self=this;if(!name)return self._isRunning;var task=self.tasksPending[name];if(!task)return false;return task.isRunning===1};Async.prototype.isWaiting=function(name){var self=this;var task=self.tasksPending[name];if(!task)return false;return task.isRunning===0};Async.prototype.isPending=function(name){var self=this;var task=self.tasksPending[name];if(!task)return false;return true};Async.prototype.timeout=function(name,timeout){var self=this;if(timeout<=0||typeof timeout===UNDEFINED){delete self.tasksTimeout[name];return self}self.tasksTimeout[name]=timeout;return self};Async.prototype.refresh=function(name){var self=this;if(!self._isRunning)return self;self._count=self.tasksAll.length;for(var i=0;i<self._count;i++){var task=self.tasksPending[self.tasksAll[i]];
function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}
Example #30
0
module.exports = function () {
	var joinArgs = arguments;
	return join.apply(this, [process.cwd()].concat(Object.keys(joinArgs).map(function (key) {
		return joinArgs[key];
	})));
};