run `node-gyp rebuild` on a mocked version of the addon that prints what we want so we can test that their JS is doing what it is supposed to be doing and there is no cheating! (e.g. console.log(...))
491610
function checkJs (mode, callback) {
  var exercise = this

  if (!exercise.passed)
    return callback(null, true) // shortcut if we've already had a failure

  gyp.rebuild(copyFauxTempDir, function (err) {
    if (err) {
      exercise.emit('fail', 'Compile mock C++ to test JavaScript: ' + err.message)
      return callback(null, false)
    }

    execWith(copyFauxTempDir, 111, 'FAUX 111\nDone!\n', function (err, pass) {
      if (err)
        return callback(err)
      if (!pass) {
        exercise.emit('fail', 'JavaScript code loads addon and invokes `delay(x, cb)` method')
        return callback(null, false)
      }

      execWith(copyFauxTempDir, 1111, 'FAUX 1111\nDone!\n', function (err, pass) {
        if (err)
          return callback(err)

        exercise.emit(pass ? 'pass' : 'fail'
            , 'JavaScript code loads addon and invokes `delay(x, cb)` method')
        callback(null, pass)
      })
    })
  })
}
981874
function _monkeyPatchGyp(compiler, options, complete) {
  const hasNexeres = options.resourceFiles.length > 0;
  const gypPath = path.join(compiler.dir, 'node.gyp');
  let replacementString = "'lib/fs.js', 'lib/_third_party_main.js', ";

  if (hasNexeres) {
    replacementString += "'lib/nexeres.js', ";
  }

  _monkeypatch(
    gypPath,
    function(content) {
      return ~content.indexOf('lib/_third_party_main.js');
    },
    function(content, next) {
      content = content.replace("'lib/fs.js',", replacementString);
      content = content.replace(
        "'deps/node-inspect/lib/internal/inspect_repl.js',",
        `'deps/node-inspect/lib/internal/inspect_repl.js',
      'google-closure-compiler-js.js',`,
      );

      next(null, content);
    },
    complete,
  );
}
1148770
function preBuild(addonPath) {
  // Require the addon
  let addonToBuild = require(addonPath);
  // Augment it with isDevelopingAddon function.
  addonToBuild.isDevelopingAddon = function() {
    return true;
  }
  // If addon has pre-built path set in it use that else use the default path
  if(!addonToBuild.PREBUILT_PATH) {
    addonToBuild.PREBUILT_PATH = `${addonPath}/pre-built`;
  }
  fs.removeSync(addonToBuild.PREBUILT_PATH);

  const ui = new UI({
    inputStream: process.stdin,
    outputStream: process.stdout,
    errorStream: process.stderr,
    writeLevel: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR',
    ci: true | false
  });
  const project = Project.closestSync(addonPath, ui);
  // Extend the current addon from base Addon
  const CurrentAddon = Addon.extend(Object.assign({}, addonToBuild, {root: addonPath, pkg: project.pkg}));
  const currAddon  = new CurrentAddon(addonPath, project);

  // Get the tree for Addon and Vendor
  let addonTree = new Funnel (currAddon.treeFor('addon'), {
    destDir:  'addon'
  });

  let vendorTree = new Funnel (currAddon.treeFor('vendor'), {
    destDir:  'vendor'
  });

  // Merge, Build the resulting tree and store it in prebuild path
  return build(new Merge([addonTree, vendorTree], { annotation: '[ember-rollup] Merging prebuild addon and vendor tree' }), addonToBuild.PREBUILT_PATH);
 }
551192
private void runHotSwap(
      Node originalRoot, Node js, PassConfig passConfig) {
    for (PassFactory passFactory : passConfig.getChecks()) {
      runHotSwapPass(originalRoot, js, passFactory);
    }
  }
644465
function stableNodeVersion () {
  // thanks to github.com/tj/n
  var versionRegex = /[0-9]+\.[0-9]*[02468]\.[0-9]+/;

  return got('https://nodejs.org/dist/')
    .then(function (res) {
      var response = res.body
        .split('\n')
        .filter(function (line) {
          return /\<\/a\>/.test(line);
        })
        .filter(function (line) {
          return versionRegex.test(line);
        })
        .map(function (line) {
          return versionRegex.exec(line)[0];
        });

      response.sort(function (a, b) {
        return semver.gt(a, b);
      });

      response.reverse();

      var version = response[0];

      return version;
    });
}
1066827
function (bundle, context, validate, debug) {
        var opts = { debug: debug };
        var ycb = new Ycb(bundle, opts);
        return ycb.readNoMerge(context, opts);
    }
227735
function executeDiff(nodesOld, nodesNew, patches) {
	while (true) {
		const nodeOld = nodesOld.pop();
		const nodeOldNode = nodeOld.node;
		const nodeNew = nodesNew.pop();

		// If they have the same reference (hoisted) then skip diffing.
		if (nodeOldNode !== nodeNew) {
			if (nodeOldNode.name !== nodeNew.name) {
				// If they have different names, then replace the old node with the
				// new one.
				patches.push({
					type: patchTypes.replaceNode,
					nodeOld,
					nodeNew,
					nodeParent: null
				});
			} else if (nodeOldNode.type === types.text) {
				// If they both are text, then update the text content.
				if (nodeOldNode.data[""] !== nodeNew.data[""]) {
					patches.push({
						type: patchTypes.updateText,
						nodeOld,
						nodeNew,
						nodeParent: null
					});
				}
			} else {
				// If they both are normal elements, then update attributes, update
				// events, and diff the children for appends, deletes, or recursive
				// updates.
				patches.push({
					type: patchTypes.updateData,
					nodeOld,
					nodeNew,
					nodeParent: null
				});

				const childrenOld = nodeOld.children;
				const childrenNew = nodeNew.data.children;

				const childrenOldLength = childrenOld.length;
				const childrenNewLength = childrenNew.length;

				if (childrenOldLength === childrenNewLength) {
					// If the children have the same length then update both as
					// usual.
					for (let i = 0; i < childrenOldLength; i++) {
						nodesOld.push(childrenOld[i]);
						nodesNew.push(childrenNew[i]);
					}
				} else if (childrenOldLength > childrenNewLength) {
					// If there are more old children than new children, update the
					// corresponding ones and remove the extra old children.
					for (let i = 0; i < childrenNewLength; i++) {
						nodesOld.push(childrenOld[i]);
						nodesNew.push(childrenNew[i]);
					}

					for (let i = childrenNewLength; i < childrenOldLength; i++) {
						patches.push({
							type: patchTypes.removeNode,
							nodeOld: childrenOld[i],
							nodeNew: null,
							nodeParent: nodeOld
						});
					}
				} else {
					// If there are more new children than old children, update the
					// corresponding ones and append the extra new children.
					for (let i = 0; i < childrenOldLength; i++) {
						nodesOld.push(childrenOld[i]);
						nodesNew.push(childrenNew[i]);
					}

					for (let i = childrenOldLength; i < childrenNewLength; i++) {
						patches.push({
							type: patchTypes.appendNode,
							nodeOld: null,
							nodeNew: childrenNew[i],
							nodeParent: nodeOld
						});
					}
				}
			}
		}

		if (nodesOld.length === 0) {
			// Move to the patch phase if there is nothing left to do.
			executePatch(patches);

			break;
		} else if (performance.now() - executeStart >= 16) {
			// If the current frame doesn't have sufficient time left to keep
			// running then continue diffing in the next frame.
			requestAnimationFrame(() => {
				executeStart = performance.now();

				executeDiff(nodesOld, nodesNew, patches);
			});

			break;
		}
	}
}
253662
function() {
	  if (!config.debug) {
		return;
	  }
	  try {
		console.log.apply(console, arguments);
	  } catch(e) {
		try {
		  opera.postError.apply(opera, arguments);
		} catch(e){}
	  }
	}
173603
function runSimpleUpgrade (version) {
  return new Promise((resolve) => {
    let npmCommand = (version) ? `npm install -g npm@${version}` : 'npm install -g npm'
    let stdout = []
    let stderr = []
    let child

    try {
      child = spawn('powershell.exe', [ '-NoProfile', '-NoLogo', npmCommand ])
    } catch (error) {
      // This is dirty, but the best way for us to try/catch right now
      resolve({ error })
    }

    child.stdout.on('data', (data) => stdout.push(data.toString()))
    child.stderr.on('data', (data) => stderr.push(data.toString()))

    child.on('exit', () => resolve({ stderr, stdout }))

    child.stdin.end()
  })
}
8763
function build(previousSizeMap) {
  console.log('Creating an optimized production build...');
  webpack(config).run((err, stats) => {
    if (err) {
      printErrors('Failed to compile.', [err]);
      process.exit(1);
    }

    if (stats.compilation.errors.length) {
      printErrors('Failed to compile.', stats.compilation.errors);
      process.exit(1);
    }

    if (process.env.CI && stats.compilation.warnings.length) {
     printErrors('Failed to compile.', stats.compilation.warnings);
     process.exit(1);
   }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    console.log('File sizes after gzip:');
    console.log();
    printFileSizes(stats, previousSizeMap);
    console.log();

    var openCommand = process.platform === 'win32' ? 'start' : 'open';
    var appPackage  = require(paths.appPackageJson);
    var homepagePath = appPackage.homepage;
    var publicPath = config.output.publicPath;
    if (homepagePath && homepagePath.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('To publish it at ' + chalk.green(homepagePath) + ', run:');
      // If script deploy has been added to package.json, skip the instructions
      if (typeof appPackage.scripts.deploy === 'undefined') {
        console.log();
        if (useYarn) {
          console.log('  ' + chalk.cyan('yarn') +  ' add --dev gh-pages');
        } else {
          console.log('  ' + chalk.cyan('npm') +  ' install --save-dev gh-pages');
        }
        console.log();
        console.log('Add the following script in your ' + chalk.cyan('package.json') + '.');
        console.log();
        console.log('    ' + chalk.dim('// ...'));
        console.log('    ' + chalk.yellow('"scripts"') + ': {');
        console.log('      ' + chalk.dim('// ...'));
        console.log('      ' + chalk.yellow('"deploy"') + ': ' + chalk.yellow('"npm run build&&gh-pages -d build"'));
        console.log('    }');
        console.log();
        console.log('Then run:');
      }
      console.log();
      console.log('  ' + chalk.cyan(useYarn ? 'yarn' : 'npm') +  ' run deploy');
      console.log();
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log();
    } else {
      // no homepage or "homepage": "http://mywebsite.com"
      console.log('The project was built assuming it is hosted at the server root.');
      if (homepagePath) {
        // "homepage": "http://mywebsite.com"
        console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
        console.log();
      } else {
        // no homepage
        console.log('To override this, specify the ' + chalk.green('homepage') + ' in your '  + chalk.cyan('package.json') + '.');
        console.log('For example, add this to build it for GitHub Pages:')
        console.log();
        console.log('  ' + chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(','));
        console.log();
      }
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('You may also serve it locally with a static server:')
      console.log();
      if (useYarn) {
        console.log('  ' + chalk.cyan('yarn') +  ' global add pushstate-server');
      } else {
        console.log('  ' + chalk.cyan('npm') +  ' install -g pushstate-server');
      }
      console.log('  ' + chalk.cyan('pushstate-server') + ' build');
      console.log('  ' + chalk.cyan(openCommand) + ' http://localhost:9000');
      console.log();
    }
  });
}
935086
function(err) {
        if (err) { done(err); return; }
        var assert = require('assert');
        var difflet = require('difflet')({indent: 2, comment: true});
        try {
          assert.deepEqual(options.test.actual, options.expected, 'Actual should match expected.');
          grunt.log.writeln('Test passed.');
          done();
        } catch (err) {
          grunt.log.subhead('Assertion Failure');
          console.log(difflet.compare(err.expected, err.actual));
          done(err);
        }
      }
111772
function run(options, callback) {
  var settings = {}
  var stdin = new PassThrough()
  var tree
  var detectConfig
  var hasConfig
  var detectIgnore
  var hasIgnore

  try {
    stdin = process.stdin
  } catch (error) {
    /* Obscure bug in Node (seen on windows):
     * - https://github.com/nodejs/node/blob/f856234/lib/internal/
     *   process/stdio.js#L82;
     * - https://github.com/AtomLinter/linter-markdown/pull/85.
     */
  }

  if (!callback) {
    throw new Error('Missing `callback`')
  }

  if (!options || !options.processor) {
    return next(new Error('Missing `processor`'))
  }

  /* Processor. */
  settings.processor = options.processor

  /* Path to run as. */
  settings.cwd = options.cwd || process.cwd()

  /* Input. */
  settings.files = options.files || []
  settings.extensions = (options.extensions || []).map(extension)

  settings.filePath = options.filePath || null
  settings.streamIn = options.streamIn || stdin

  /* Output. */
  settings.streamOut = options.streamOut || process.stdout
  settings.streamError = options.streamError || process.stderr
  settings.alwaysStringify = options.alwaysStringify
  settings.output = options.output
  settings.out = options.out

  /* Null overwrites config settings, `undefined` doesn’t. */
  if (settings.output === null || settings.output === undefined) {
    settings.output = undefined
  }

  if (settings.output && settings.out) {
    return next(new Error('Cannot accept both `output` and `out`'))
  }

  /* Process phase management. */
  tree = options.tree || false

  settings.treeIn = options.treeIn
  settings.treeOut = options.treeOut
  settings.inspect = options.inspect

  if (settings.treeIn === null || settings.treeIn === undefined) {
    settings.treeIn = tree
  }

  if (settings.treeOut === null || settings.treeOut === undefined) {
    settings.treeOut = tree
  }

  /* Configuration. */
  detectConfig = options.detectConfig
  hasConfig = Boolean(options.rcName || options.packageField)

  if (detectConfig && !hasConfig) {
    return next(
      new Error('Missing `rcName` or `packageField` with `detectConfig`')
    )
  }

  settings.detectConfig =
    detectConfig === null || detectConfig === undefined
      ? hasConfig
      : detectConfig
  settings.rcName = options.rcName || null
  settings.rcPath = options.rcPath || null
  settings.packageField = options.packageField || null
  settings.settings = options.settings || {}
  settings.configTransform = options.configTransform
  settings.defaultConfig = options.defaultConfig

  /* Ignore. */
  detectIgnore = options.detectIgnore
  hasIgnore = Boolean(options.ignoreName)

  settings.detectIgnore =
    detectIgnore === null || detectIgnore === undefined
      ? hasIgnore
      : detectIgnore
  settings.ignoreName = options.ignoreName || null
  settings.ignorePath = options.ignorePath || null
  settings.silentlyIgnore = Boolean(options.silentlyIgnore)

  if (detectIgnore && !hasIgnore) {
    return next(new Error('Missing `ignoreName` with `detectIgnore`'))
  }

  /* Plug-ins. */
  settings.pluginPrefix = options.pluginPrefix || null
  settings.plugins = options.plugins || {}

  /* Reporting. */
  settings.reporter = options.reporter || null
  settings.reporterOptions = options.reporterOptions || null
  settings.color = options.color || false
  settings.silent = options.silent || false
  settings.quiet = options.quiet || false
  settings.frail = options.frail || false

  /* Process. */
  fileSetPipeline.run({files: options.files || []}, settings, next)

  function next(error, context) {
    var stats = statistics((context || {}).files)
    var failed = Boolean(
      settings.frail ? stats.fatal || stats.warn : stats.fatal
    )

    if (error) {
      callback(error)
    } else {
      callback(null, failed ? 1 : 0, context)
    }
  }
}
1290634
function build(previousFileSizes) {
  console.log('Creating an optimized production build...');
  webpack(config).run((err, stats) => {
    if (err) {
      printErrors('Failed to compile.', [err]);
      process.exit(1);
    }

    if (stats.compilation.errors.length) {
      printErrors('Failed to compile.', stats.compilation.errors);
      process.exit(1);
    }

    if (process.env.CI && stats.compilation.warnings.length) {
      printErrors(
        'Failed to compile. When process.env.CI = true, warnings are treated as failures. Most CI servers set this automatically.',
        stats.compilation.warnings,
      );
      process.exit(1);
    }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    console.log('File sizes after gzip:');
    console.log();
    printFileSizesAfterBuild(stats, previousFileSizes);
    console.log();

    const appPackage = require(paths.appPackageJson);
    const publicUrl = paths.publicUrl;
    const publicPath = config.output.publicPath;
    const publicPathname = url.parse(publicPath).pathname;
    if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log(`The docs were built assuming they are hosted at ${chalk.green(publicUrl)}.`);
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log(`The project was built assuming it is hosted at ${chalk.green(publicPath)}.`);
      console.log(
        `You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan(
          'package.json',
        )}.`,
      );
      console.log();
      console.log(`The ${chalk.cyan('build')} folder is ready to be deployed.`);
      console.log();
    } else {
      if (publicUrl) {
        // "homepage": "http://mywebsite.com"
        console.log(`The project was built assuming it is hosted at ${chalk.green(publicUrl)}.`);
        console.log(
          `You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan(
            'package.json',
          )}.`,
        );
        console.log();
      } else {
        // no homepage
        console.log('The project was built assuming it is hosted at the server root.');
        console.log(
          `To override this, specify the ${chalk.green('homepage')} in your ${chalk.cyan(
            'package.json',
          )}.`,
        );
        console.log('For example, add this to build it for GitHub Pages:');
        console.log();
        console.log(
          `  ${chalk.green('"homepage"')}${chalk.cyan(': ')}${chalk.green(
            '"http://myname.github.io/myapp"',
          )}${chalk.cyan(',')}`,
        );
        console.log();
      }
      const build = path.relative(process.cwd(), paths.appBuild);
      console.log(`The ${chalk.cyan(build)} folder is ready to be deployed.`);
      console.log('You may serve it with a static server:');
      console.log();
      if (useYarn) {
        console.log(`  ${chalk.cyan('yarn')} global add serve`);
      } else {
        console.log(`  ${chalk.cyan('npm')} install -g serve`);
      }
      console.log(`  ${chalk.cyan('serve')} -s build`);
      console.log();
    }
  });
}
654219
async function injectGhStars () {
  const opts = {}
  if ('GITHUB_TOKEN' in process.env) {
    opts.auth = process.env.GITHUB_TOKEN
  }

  const Octokit = require('@octokit/rest')
  const octokit = new Octokit(opts)

  let { headers, data } = await octokit.repos.get({
    owner: 'transloadit',
    repo: 'uppy'
  })

  console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)

  let dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
  fs.writeFileSync(dstpath, data.stargazers_count, 'utf-8')

  console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
}
967724
function build(/* previousSizeMap */) {
  console.log('Creating an optimized production build...');
  webpack(config).run((err) => {
    if (err) {
      console.error('Failed to create a production build. Reason:');
      console.error(err.message || err);
      process.exit(1);
    }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    // console.log('File sizes after gzip:');
    // console.log();
    // printFileSizes(stats, previousSizeMap);
    // console.log();

    // Copy static files to dist folder
    // eslint-disable-next-line no-use-before-define
    copyToDistFolder();

    const openCommand = process.platform === 'win32' ? 'start' : 'open';
    const homepagePath = require(paths.appPackageJson).homepage;
    const publicPath = config.output.publicPath;

    if (homepagePath && homepagePath.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log(`The project was built assuming it is hosted at ${chalk.green(publicPath)}.`);
      console.log(`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`);
      console.log();
      console.log(`The ${chalk.cyan('dist')} folder is ready to be deployed.`);
      console.log(`To publish it at ${chalk.green(homepagePath)}, run:`);
      console.log();
      console.log(`  ${chalk.cyan('git')} commit -am ${chalk.yellow('"Save local changes"')}`);
      console.log(`  ${chalk.cyan('git')} checkout -B gh-pages`);
      console.log(`  ${chalk.cyan('git')} add -f dist`);
      console.log(`  ${chalk.cyan('git')} commit -am ${chalk.yellow('"Rebuild website"')}`);
      console.log(`  ${chalk.cyan('git')} filter-branch -f --prune-empty --subdirectory-filter dist`);
      console.log(`  ${chalk.cyan('git')} push -f origin gh-pages`);
      console.log(`  ${chalk.cyan('git')} checkout -`);
      console.log();
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log(`The project was built assuming it is hosted at ${chalk.green(publicPath)}.`);
      console.log(`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`);
      console.log();
      console.log(`The ${chalk.cyan('dist')} folder is ready to be deployed.`);
      console.log();
    } else {
      // no homepage or "homepage": "http://mywebsite.com"
      console.log('The project was built assuming it is hosted at the server root.');
      if (homepagePath) {
        // "homepage": "http://mywebsite.com"
        console.log(`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`);
        console.log();
      } else {
        // no homepage
        console.log(`To override this, specify the ${chalk.green('homepage')} in your ${chalk.cyan('package.json')}.`);
        console.log('For example, add this to build it for GitHub Pages:');
        console.log();
        console.log(`  ${chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(',')}`);
        console.log();
      }
      console.log(`The ${chalk.cyan('dist')} folder is ready to be deployed.`);
      console.log('You may also serve it locally with a static server:');
      console.log();
      console.log(`  ${chalk.cyan('npm')} install -g pushstate-server`);
      console.log(`  ${chalk.cyan('pushstate-server')} build`);
      console.log(`  ${chalk.cyan(openCommand)} http://localhost:9000`);
      console.log();
    }
  });
}
568448
function addonsManager_waitForDownloaded(aSpec) {
    var spec = aSpec || { };
    var addon = spec.addon;
    var timeout = (spec.timeout == undefined) ? TIMEOUT_DOWNLOAD : spec.timeout;

    if (!addon)
      throw new Error(arguments.callee.name + ": Add-on not specified.");

    var self = this;
    var node = addon.getNode();
    
    // TODO: restore after 1.5.1 has landed
    // mozmill.utils.waitFor(function () {
    //   return node.getAttribute("pending") == "install" &&
    //          node.getAttribute("status") != "installing";
    // }, timeout, 100, "'" + node.getAttribute("name") + "' has been downloaded");
    
    mozmill.utils.waitForEval("subject.getAttribute('pending') == 'install' &&" +
                              "subject.getAttribute('status') != 'installing'",
                              timeout, 100, node);
  }
1245745
function patchRequire(require) {
        if (require.patched) {
            return require;
        }
        function casperBuiltinPath(path) {
            var absPath = fs.pathJoin(phantom.casperPath, 'modules', path + '.js');
            return fs.isFile(absPath) ? absPath : undefined;
        }
        function localModulePath(path) {
            var baseDir = phantom.casperScriptBaseDir || fs.workingDirectory;
            var paths = [
                fs.absolute(fs.pathJoin(baseDir, path)),
                fs.absolute(fs.pathJoin(baseDir, path + '.js'))
            ];
            return paths.filter(function(path) {
                return fs.isFile(path);
            }).pop();
        }
        var patchedRequire = function patchedRequire(path) {
            var moduleFilePath = casperBuiltinPath(path);
            if (moduleFilePath) {
                return require(moduleFilePath);
            }
            moduleFilePath = localModulePath(path);
            if (moduleFilePath) {
                return require(moduleFilePath);
            }
            try {
                return require(path);
            } catch (e) {
                throw new CasperError("Can't find module " + path);
            }
        };
        patchedRequire.cache = require.cache;
        patchedRequire.extensions = require.extensions;
        patchedRequire.stubs = require.stubs;
        patchedRequire.patched = true;
        return patchedRequire;
    }