if (! jshint(file.getContentsAsString(), conf, globals)) {

keep keep keep replace keep keep keep keep

if (! jshint(file.getContentsAsString(), conf, predefinedGlobals)) {

var _ = require('underscore');

var archinfo = require('./archinfo.js');
var buildmessage = require('./buildmessage.js');
var bundler = require('./bundler.js');
var isopack = require('./isopack.js');
var isopackets = require('./isopackets.js');
var linker = require('./linker.js');
var meteorNpm = require('./meteor-npm.js');
var watch = require('./watch.js');
var Console = require('./console.js').Console;
var files = require('./files.js');
var colonConverter = require('./colon-converter.js');
var linterPluginModule = require('./linter-plugin.js');

var compiler = exports;

// Whenever you change anything about the code that generates isopacks, bump
// this version number. The idea is that the "format" field of the isopack
// JSON file only changes when the actual specified structure of the
// isopack/unibuild changes, but this version (which is build-tool-specific)
// can change when the the contents (not structure) of the built output
// changes. So eg, if we improve the linker's static analysis, this should be
// bumped.
//
// You should also update this whenever you update any of the packages used
// directly by the isopack creation process (eg js-analyze) since they do not
// end up as watched dependencies. (At least for now, packages only used in
// target creation (eg minifiers) don't require you to update BUILT_BY, though
// you will need to quit and rerun "meteor run".)
compiler.BUILT_BY = 'meteor/16';

// This is a list of all possible architectures that a build can target. (Client
// is expanded into 'web.browser' and 'web.cordova')
compiler.ALL_ARCHES = [ "os", "web.browser", "web.cordova" ];

compiler.compile = function (packageSource, options) {
  buildmessage.assertInCapture();

  var packageMap = options.packageMap;
  var isopackCache = options.isopackCache;
  var includeCordovaUnibuild = options.includeCordovaUnibuild;

  var pluginWatchSet = packageSource.pluginWatchSet.clone();
  var plugins = {};

  var pluginProviderPackageNames = {};

  // Build plugins
  _.each(packageSource.pluginInfo, function (info) {
    buildmessage.enterJob({
      title: "building plugin `" + info.name +
        "` in package `" + packageSource.name + "`",
      rootPath: packageSource.sourceRoot
    }, function () {
      // XXX we should probably also pass options.noLineNumbers into
      //     buildJsImage so it can pass it back to its call to
      //     compiler.compile
      var buildResult = bundler.buildJsImage({
        name: info.name,
        packageMap: packageMap,
        isopackCache: isopackCache,
        use: info.use,
        sourceRoot: packageSource.sourceRoot,
        sources: info.sources,
        npmDependencies: info.npmDependencies,
        // Plugins have their own npm dependencies separate from the
        // rest of the package, so they need their own separate npm
        // shrinkwrap and cache state.
        npmDir: files.pathResolve(
          files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name))
      });
      // Add this plugin's dependencies to our "plugin dependency"
      // WatchSet. buildResult.watchSet will end up being the merged
      // watchSets of all of the unibuilds of the plugin -- plugins have
      // only one unibuild and this should end up essentially being just
      // the source files of the plugin.
      //
      // Note that we do this even on error, so that you can fix the error
      // and have the runner restart.
      pluginWatchSet.merge(buildResult.watchSet);

      if (buildmessage.jobHasMessages())
        return;

      _.each(buildResult.usedPackageNames, function (packageName) {
        pluginProviderPackageNames[packageName] = true;
      });

      // Register the built plugin's code.
      if (!_.has(plugins, info.name))
        plugins[info.name] = {};
      plugins[info.name][buildResult.image.arch] = buildResult.image;
    });
  });

  // Grab any npm dependencies. Keep them in a cache in the package
  // source directory so we don't have to do this from scratch on
  // every build.
  //
  // Go through a specialized npm dependencies update process,
  // ensuring we don't get new versions of any (sub)dependencies. This
  // process also runs mostly safely multiple times in parallel (which
  // could happen if you have two apps running locally using the same
  // package).
  //
  // We run this even if we have no dependencies, because we might
  // need to delete dependencies we used to have.
  var isPortable = true;
  var nodeModulesPath = null;
  if (packageSource.npmCacheDirectory) {
    if (meteorNpm.updateDependencies(packageSource.name,
                                     packageSource.npmCacheDirectory,
                                     packageSource.npmDependencies)) {
      nodeModulesPath = files.pathJoin(packageSource.npmCacheDirectory,
                                  'node_modules');
      if (! meteorNpm.dependenciesArePortable(packageSource.npmCacheDirectory))
        isPortable = false;
    }
  }

  var isopk = new isopack.Isopack;
  isopk.initFromOptions({
    name: packageSource.name,
    metadata: packageSource.metadata,
    version: packageSource.version,
    isTest: packageSource.isTest,
    plugins: plugins,
    pluginWatchSet: pluginWatchSet,
    cordovaDependencies: packageSource.cordovaDependencies,
    npmDiscards: packageSource.npmDiscards,
    includeTool: packageSource.includeTool,
    debugOnly: packageSource.debugOnly
  });

  _.each(packageSource.architectures, function (unibuild) {
    if (unibuild.arch === 'web.cordova' && ! includeCordovaUnibuild)
      return;

    var unibuildResult = compileUnibuild({
      isopack: isopk,
      sourceArch: unibuild,
      isopackCache: isopackCache,
      nodeModulesPath: nodeModulesPath,
      isPortable: isPortable,
      noLineNumbers: options.noLineNumbers
    });
    _.extend(pluginProviderPackageNames,
             unibuildResult.pluginProviderPackageNames);
  });

  if (options.includePluginProviderPackageMap) {
    isopk.setPluginProviderPackageMap(
      packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames)));
  }

  return isopk;
};

// options.sourceArch is a SourceArch to compile.  Process all source files
// through the appropriate handlers and run the prelink phase on any resulting
// JavaScript. Create a new Unibuild and add it to options.isopack.
//
// Returns a list of source files that were used in the compilation.
var compileUnibuild = function (options) {
  buildmessage.assertInCapture();

  var isopk = options.isopack;
  var inputSourceArch = options.sourceArch;
  var isopackCache = options.isopackCache;
  var nodeModulesPath = options.nodeModulesPath;
  var isPortable = options.isPortable;
  var noLineNumbers = options.noLineNumbers;

  var isApp = ! inputSourceArch.pkg.name;
  var resources = [];
  var js = [];
  var pluginProviderPackageNames = {};
  // The current package always is a plugin provider. (This also means we no
  // longer need a buildOfPath entry in buildinfo.json.)
  pluginProviderPackageNames[isopk.name] = true;
  var watchSet = inputSourceArch.watchSet.clone();

  // *** Determine and load active plugins

  // XXX we used to include our own extensions only if we were the
  // "use" role. now we include them everywhere because we don't have
  // a special "use" role anymore. it's not totally clear to me what
  // the correct behavior should be -- we need to resolve whether we
  // think about extensions as being global to a package or particular
  // to a unibuild.

  // (there's also some weirdness here with handling implies, because
  // the implies field is on the target unibuild, but we really only care
  // about packages.)
  var activePluginPackages = [isopk];

  // We don't use plugins from weak dependencies, because the ability
  // to compile a certain type of file shouldn't depend on whether or
  // not some unrelated package in the target has a dependency. And we
  // skip unordered dependencies, because it's not going to work to
  // have circular build-time dependencies.
  //
  // eachUsedUnibuild takes care of pulling in implied dependencies for us (eg,
  // templating from standard-app-packages).
  //
  // We pass archinfo.host here, not self.arch, because it may be more specific,
  // and because plugins always have to run on the host architecture.
  compiler.eachUsedUnibuild({
    dependencies: inputSourceArch.uses,
    arch: archinfo.host(),
    isopackCache: isopackCache,
    skipUnordered: true
    // implicitly skip weak deps by not specifying acceptableWeakPackages option
  }, function (unibuild) {
    if (unibuild.pkg.name === isopk.name)
      return;
    pluginProviderPackageNames[unibuild.pkg.name] = true;
    // If other package is built from source, then we need to rebuild this
    // package if any file in the other package that could define a plugin
    // changes.
    watchSet.merge(unibuild.pkg.pluginWatchSet);

    if (_.isEmpty(unibuild.pkg.plugins))
      return;
    activePluginPackages.push(unibuild.pkg);
  });

  activePluginPackages = _.uniq(activePluginPackages);

  // *** Assemble the list of source file handlers from the plugins
  // XXX BBP redoc
  var allHandlersWithPkgs = {};
  var compilerPluginsByExtension = {};
  var linterPluginsByExtension = {};
  var sourceExtensions = {};  // maps source extensions to isTemplate

  sourceExtensions['js'] = false;
  allHandlersWithPkgs['js'] = {
    pkgName: null /* native handler */,
    handler: function (compileStep) {
      // This is a hardcoded handler for *.js files. Since plugins
      // are written in JavaScript we have to start somewhere.

      var options = {
        data: compileStep.read().toString('utf8'),
        path: compileStep.inputPath,
        sourcePath: compileStep.inputPath,
        _hash: compileStep._hash
      };

      if (compileStep.fileOptions.hasOwnProperty("bare")) {
        options.bare = compileStep.fileOptions.bare;
      } else if (compileStep.fileOptions.hasOwnProperty("raw")) {
        // XXX eventually get rid of backward-compatibility "raw" name
        // XXX COMPAT WITH 0.6.4
        options.bare = compileStep.fileOptions.raw;
      }

      compileStep.addJavaScript(options);
    }
  };

  _.each(activePluginPackages, function (otherPkg) {
    otherPkg.ensurePluginsInitialized();

    // Iterate over the legacy source handlers.
    _.each(otherPkg.getSourceHandlers(), function (sourceHandler, ext) {
      // XXX comparing function text here seems wrong.
      if (_.has(allHandlersWithPkgs, ext) &&
          allHandlersWithPkgs[ext].handler.toString() !== sourceHandler.handler.toString()) {
        buildmessage.error(
          "conflict: two packages included in " +
            (inputSourceArch.pkg.name || "the app") + ", " +
            (allHandlersWithPkgs[ext].pkgName || "the app") + " and " +
            (otherPkg.name || "the app") + ", " +
            "are both trying to handle ." + ext);
        // Recover by just going with the first handler we saw
        return;
      }
      // Is this handler only registered for, say, "web", and we're building,
      // say, "os"?
      if (sourceHandler.archMatching &&
          !archinfo.matches(inputSourceArch.arch, sourceHandler.archMatching)) {
        return;
      }
      allHandlersWithPkgs[ext] = {
        pkgName: otherPkg.name,
        handler: sourceHandler.handler
      };
      sourceExtensions[ext] = !!sourceHandler.isTemplate;
    });

    // Iterate over the compiler plugins.
    _.each(otherPkg.sourceProcessors.compiler, function (compilerPlugin, id) {
      _.each(compilerPlugin.extensions, function (ext) {
        if (_.has(allHandlersWithPkgs, ext) ||
            _.has(compilerPluginsByExtension, ext)) {
          buildmessage.error(
            "conflict: two packages included in " +
              (inputSourceArch.pkg.name || "the app") + ", " +
              (allHandlersWithPkgs[ext].pkgName || "the app") + " and " +
              (otherPkg.name || "the app") + ", " +
              "are both trying to handle ." + ext);
          // Recover by just going with the first one we found.
          return;
        }
        compilerPluginsByExtension[ext] = compilerPlugin;
        sourceExtensions[ext] = compilerPlugin.isTemplate;
      });
    });

    // Iterate over the linters
    _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {
      _.each(linterPlugin.extensions, function (ext) {
        linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];
        linterPluginsByExtension[ext].push(linterPlugin);
      });
    });
  });

  // *** Determine source files
  // Note: sourceExtensions does not include leading dots
  // Note: the getSourcesFunc function isn't expected to add its
  // source files to watchSet; rather, the watchSet is for other
  // things that the getSourcesFunc consulted (such as directory
  // listings or, in some hypothetical universe, control files) to
  // determine its source files.
  var sourceItems = inputSourceArch.getSourcesFunc(sourceExtensions, watchSet);

  if (nodeModulesPath) {
    // If this slice has node modules, we should consider the shrinkwrap file
    // to be part of its inputs. (This is a little racy because there's no
    // guarantee that what we read here is precisely the version that's used,
    // but it's better than nothing at all.)
    //
    // Note that this also means that npm modules used by plugins will get
    // this npm-shrinkwrap.json in their pluginDependencies (including for all
    // packages that depend on us)!  This is good: this means that a tweak to
    // an indirect dependency of the coffee-script npm module used by the
    // coffeescript package will correctly cause packages with *.coffee files
    // to be rebuilt.
    var shrinkwrapPath = nodeModulesPath.replace(
        /node_modules$/, 'npm-shrinkwrap.json');
    watch.readAndWatchFile(watchSet, shrinkwrapPath);
  }

  // *** Process each source file
  var addAsset = function (contents, relPath, hash) {
    // XXX hack
    if (! inputSourceArch.pkg.name)
      relPath = relPath.replace(/^(private|public)\//, '');

    resources.push({
      type: "asset",
      data: contents,
      path: relPath,
      servePath: colonConverter.convert(
        files.pathJoin(inputSourceArch.pkg.serveRoot, relPath)),
      hash: hash
    });
  };

  var convertSourceMapPaths = function (sourcemap, f) {
    if (! sourcemap) {
      // Don't try to convert it if it doesn't exist
      return sourcemap;
    }

    var srcmap = JSON.parse(sourcemap);
    srcmap.sources = _.map(srcmap.sources, f);
    return JSON.stringify(srcmap);
  };

  var wrappedSourceItems = _.map(sourceItems, function (source) {
    var fileWatchSet = new watch.WatchSet;
    // readAndWatchFileWithHash returns an object carrying a buffer with the
    // file-contents. The buffer contains the original data of the file (no EOL
    // transforms from the tools/files.js part).
    // We don't put this into the unibuild's watchSet immediately since we want
    // to avoid putting it there if it turns out not to be relevant to our
    // arch.
    var absPath = files.pathResolve(
      inputSourceArch.pkg.sourceRoot, source.relPath);
    var file = watch.readAndWatchFileWithHash(fileWatchSet, absPath);

    Console.nudge(true);

    return {
      relPath: source.relPath,
      watchset: fileWatchSet,
      contents: file.contents,
      hash: file.hash,
      source: source,
      'package': isopk.name
    };
  });

  runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);

  _.each(wrappedSourceItems, function (wrappedSource) {
    var source = wrappedSource.source;
    var relPath = source.relPath;
    var fileOptions = _.clone(source.fileOptions) || {};
    var absPath = files.pathResolve(inputSourceArch.pkg.sourceRoot, relPath);
    var filename = files.pathBasename(relPath);
    var contents = wrappedSource.contents;
    var hash = wrappedSource.hash;
    var fileWatchSet = wrappedSource.watchset;

    Console.nudge(true);

    if (contents === null) {
      // It really sucks to put this check here, since this isn't publish
      // code...
      if (source.relPath.match(/:/)) {
        buildmessage.error(
          "Couldn't build this package on Windows due to the following file " +
          "with a colon -- " + source.relPath + ". Please rename and " +
          "and re-publish the package.");
      } else {
        buildmessage.error("File not found: " + source.relPath);
      }

      // recover by ignoring (but still watching the file)
      watchSet.merge(fileWatchSet);
      return;
    }

    // Find the handler for source files with this extension.
    var handler = null;
    var isBuildPluginSource = false;
    if (! fileOptions.isAsset) {
      var parts = filename.split('.');
      // don't use iteration functions, so we can return/break
      for (var i = 1; i < parts.length; i++) {
        var extension = parts.slice(i).join('.');
        if (_.has(compilerPluginsByExtension, extension)) {
          var compilerPlugin = compilerPluginsByExtension[extension];
          if (! compilerPlugin.relevantForArch(inputSourceArch.arch)) {
            // This file is for a compiler plugin but not for this arch. Skip
            // it, and don't even watch it.  (eg, skip CSS preprocessor files on
            // the server.)
            return;
          }
          isBuildPluginSource = true;
          break;
        }
        if (_.has(allHandlersWithPkgs, extension)) {
          handler = allHandlersWithPkgs[extension].handler;
          break;
        }
      }
    }

    // OK, this is relevant to this arch, so watch it.
    watchSet.merge(fileWatchSet);

    if (isBuildPluginSource) {
      // This is source used by a new-style compiler plugin; it will be fully
      // processed later in the bundler.
      resources.push({
        type: "source",
        data: contents,
        path: relPath,
        hash: hash
      });
      return;
    }

    if (! handler) {
      // If we don't have an extension handler, serve this file as a
      // static resource on the client, or ignore it on the server.
      //
      // XXX This is pretty confusing, especially if you've
      // accidentally forgotten a plugin -- revisit?
      addAsset(contents, relPath, hash);
      return;
    }

    // This object is called a #CompileStep and it's the interface
    // to plugins that define new source file handlers (eg,
    // Coffeescript).
    //
    // Fields on CompileStep:
    //
    // - arch: the architecture for which we are building
    // - inputSize: total number of bytes in the input file
    // - inputPath: the filename and (relative) path of the input
    //   file, eg, "foo.js". We don't provide a way to get the full
    //   path because you're not supposed to read the file directly
    //   off of disk. Instead you should call read(). That way we
    //   can ensure that the version of the file that you use is
    //   exactly the one that is recorded in the dependency
    //   information.
    // - pathForSourceMap: If this file is to be included in a source map,
    //   this is the name you should use for it in the map.
    // - rootOutputPath: on web targets, for resources such as
    //   stylesheet and static assets, this is the root URL that
    //   will get prepended to the paths you pick for your output
    //   files so that you get your own namespace, for example
    //   '/packages/foo'. null on non-web targets
    // - fileOptions: any options passed to "api.addFiles"; for
    //   use by the plugin. The built-in "js" plugin uses the "bare"
    //   option for files that shouldn't be wrapped in a closure.
    // - declaredExports: An array of symbols exported by this unibuild, or null
    //   if it may not export any symbols (eg, test unibuilds). This is used by
    //   CoffeeScript to ensure that it doesn't close over those symbols, eg.
    // - read(n): read from the input file. If n is given it should
    //   be an integer, and you will receive the next n bytes of the
    //   file as a Buffer. If n is omitted you get the rest of the
    //   file.
    // - appendDocument({ section: "head", data: "my markup" })
    //   Browser targets only. Add markup to the "head" or "body"
    //   Web targets only. Add markup to the "head" or "body"
    //   section of the document.
    // - addStylesheet({ path: "my/stylesheet.css", data: "my css",
    //                   sourceMap: "stringified json sourcemap"})
    //   Web targets only. Add a stylesheet to the
    //   document. 'path' is a requested URL for the stylesheet that
    //   may or may not ultimately be honored. (Meteor will add
    //   appropriate tags to cause the stylesheet to be loaded. It
    //   will be subject to any stylesheet processing stages in
    //   effect, such as minification.)
    // - addJavaScript({ path: "my/program.js", data: "my code",
    //                   sourcePath: "src/my/program.js",
    //                   bare: true })
    //   Add JavaScript code, which will be namespaced into this
    //   package's environment (eg, it will see only the exports of
    //   this package's imports), and which will be subject to
    //   minification and so forth. Again, 'path' is merely a hint
    //   that may or may not be honored. 'sourcePath' is the path
    //   that will be used in any error messages generated (eg,
    //   "foo.js:4:1: syntax error"). It must be present and should
    //   be relative to the project root. Typically 'inputPath' will
    //   do handsomely. "bare" means to not wrap the file in
    //   a closure, so that its vars are shared with other files
    //   in the module.
    // - addAsset({ path: "my/image.png", data: Buffer })
    //   Add a file to serve as-is over HTTP (web targets) or
    //   to include as-is in the bundle (os targets).
    //   This time `data` is a Buffer rather than a string. For
    //   web targets, it will be served at the exact path you
    //   request (concatenated with rootOutputPath). For server
    //   targets, the file can be retrieved by passing path to
    //   Assets.getText or Assets.getBinary.
    // - error({ message: "There's a problem in your source file",
    //           sourcePath: "src/my/program.ext", line: 12,
    //           column: 20, func: "doStuff" })
    //   Flag an error -- at a particular location in a source
    //   file, if you like (you can even indicate a function name
    //   to show in the error, like in stack traces). sourcePath,
    //   line, column, and func are all optional.
    //
    // XXX for now, these handlers must only generate portable code
    // (code that isn't dependent on the arch, other than 'web'
    // vs 'os') -- they can look at the arch that is provided
    // but they can't rely on the running on that particular arch
    // (in the end, an arch-specific unibuild will be emitted only if
    // there are native node modules). Obviously this should
    // change. A first step would be a setOutputArch() function
    // analogous to what we do with native node modules, but maybe
    // what we want is the ability to ask the plugin ahead of time
    // how specific it would like to force unibuilds to be.
    //
    // XXX we handle encodings in a rather cavalier way and I
    // suspect we effectively end up assuming utf8. We can do better
    // than that!
    //
    // XXX addAsset probably wants to be able to set MIME type and
    // also control any manifest field we deem relevant (if any)
    //
    // XXX Some handlers process languages that have the concept of
    // include files. These are problematic because we need to
    // somehow instrument them to get the names and hashs of all of
    // the files that they read for dependency tracking purposes. We
    // don't have an API for that yet, so for now we provide a
    // workaround, which is that _fullInputPath contains the full
    // absolute path to the input files, which allows such a plugin
    // to set up its include search path. It's then on its own for
    // registering dependencies (for now..)
    //
    // XXX in the future we should give plugins an easy and clean
    // way to return errors (that could go in an overall list of
    // errors experienced across all files)
    var readOffset = 0;

    /**
     * The comments for this class aren't used to generate docs right now.
     * The docs live in the GitHub Wiki at: https://github.com/meteor/meteor/wiki/CompileStep-API-for-Build-Plugin-Source-Handlers
     * @class CompileStep
     * @summary The object passed into Plugin.registerSourceHandler
     * @global
     */
    var compileStep = {

      /**
       * @summary The total number of bytes in the input file.
       * @memberOf CompileStep
       * @instance
       * @type {Integer}
       */
      inputSize: contents.length,

      /**
       * @summary The filename and relative path of the input file.
       * Please don't use this filename to read the file from disk, instead
       * use [compileStep.read](CompileStep-read).
       * @type {String}
       * @instance
       * @memberOf CompileStep
       */
      inputPath: files.convertToOSPath(relPath, true),

      /**
       * @summary The filename and absolute path of the input file.
       * Please don't use this filename to read the file from disk, instead
       * use [compileStep.read](CompileStep-read).
       * @type {String}
       * @instance
       * @memberOf CompileStep
       */
      fullInputPath: files.convertToOSPath(absPath),

      // The below is used in the less and stylus packages... so it should be
      // public API.
      _fullInputPath: files.convertToOSPath(absPath), // avoid, see above..

      // Used for one optimization. Don't rely on this otherwise.
      _hash: hash,

      // XXX duplicates _pathForSourceMap() in linker
      /**
       * @summary If you are generating a sourcemap for the compiled file, use
       * this path for the original file in the sourcemap.
       * @type {String}
       * @memberOf CompileStep
       * @instance
       */
      pathForSourceMap: files.convertToOSPath(
        inputSourceArch.pkg.name ?  inputSourceArch.pkg.name + "/" + relPath :
                                    files.pathBasename(relPath), true),

      // null if this is an app. intended to be used for the sources
      // dictionary for source maps.
      /**
       * @summary The name of the package in which the file being built exists.
       * @type {String}
       * @memberOf CompileStep
       * @instance
       */
      packageName: inputSourceArch.pkg.name,

      /**
       * @summary On web targets, this will be the root URL prepended
       * to the paths you pick for your output files. For example,
       * it could be "/packages/my-package".
       * @type {String}
       * @memberOf CompileStep
       * @instance
       */
      rootOutputPath: files.convertToOSPath(
        inputSourceArch.pkg.serveRoot, true),

      /**
       * @summary The architecture for which we are building. Can be "os",
       * "web.browser", or "web.cordova".
       * @type {String}
       * @memberOf CompileStep
       * @instance
       */
      arch: inputSourceArch.arch,

      /**
       * @deprecated in 0.9.4
       * This is a duplicate API of the above, we don't need it.
       */
      archMatches: function (pattern) {
        return archinfo.matches(inputSourceArch.arch, pattern);
      },

      /**
       * @summary Any options passed to "api.addFiles".
       * @type {Object}
       * @memberOf CompileStep
       * @instance
       */
      fileOptions: fileOptions,

      /**
       * @summary The list of exports that the current package has defined.
       * Can be used to treat those symbols differently during compilation.
       * @type {Object}
       * @memberOf CompileStep
       * @instance
       */
      declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),

      /**
       * @summary Read from the input file. If `n` is specified, returns the
       * next `n` bytes of the file as a Buffer. XXX not sure if this actually
       * returns a String sometimes...
       * @param  {Integer} [n] The number of bytes to return.
       * @instance
       * @memberOf CompileStep
       * @returns {Buffer}
       */
      read: function (n) {
        if (n === undefined || readOffset + n > contents.length)
          n = contents.length - readOffset;
        var ret = contents.slice(readOffset, readOffset + n);
        readOffset += n;
        return ret;
      },

      /**
       * @summary Works in web targets only. Add markup to the `head` or `body`
       * section of the document.
       * @param  {Object} options
       * @param {String} options.section Which section of the document should
       * be appended to. Can only be "head" or "body".
       * @param {String} options.data The content to append.
       * @memberOf CompileStep
       * @instance
       */
      addHtml: function (options) {
        if (! archinfo.matches(inputSourceArch.arch, "web"))
          throw new Error("Document sections can only be emitted to " +
                          "web targets");
        if (options.section !== "head" && options.section !== "body")
          throw new Error("'section' must be 'head' or 'body'");
        if (typeof options.data !== "string")
          throw new Error("'data' option to appendDocument must be a string");
        resources.push({
          type: options.section,
          data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8')
        });
      },

      /**
       * @deprecated in 0.9.4
       */
      appendDocument: function (options) {
        this.addHtml(options);
      },

      /**
       * @summary Web targets only. Add a stylesheet to the document.
       * @param {Object} options
       * @param {String} path The requested path for the added CSS, may not be
       * satisfied if there are path conflicts.
       * @param {String} data The content of the stylesheet that should be
       * added.
       * @param {String} sourceMap A stringified JSON sourcemap, in case the
       * stylesheet was generated from a different file.
       * @memberOf CompileStep
       * @instance
       */
      addStylesheet: function (options) {
        if (! archinfo.matches(inputSourceArch.arch, "web"))
          throw new Error("Stylesheets can only be emitted to " +
                          "web targets");
        if (typeof options.data !== "string")
          throw new Error("'data' option to addStylesheet must be a string");
        resources.push({
          type: "css",
          refreshable: true,
          data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),
          servePath: colonConverter.convert(
            files.pathJoin(
              inputSourceArch.pkg.serveRoot,
              files.convertToStandardPath(options.path, true))),
          sourceMap: convertSourceMapPaths(options.sourceMap,
                                           files.convertToStandardPath)
        });
      },

      /**
       * @summary Add JavaScript code. The code added will only see the
       * namespaces imported by this package as runtime dependencies using
       * ['api.use'](#PackageAPI-use). If the file being compiled was added
       * with the bare flag, the resulting JavaScript won't be wrapped in a
       * closure.
       * @param {Object} options
       * @param {String} options.path The path at which the JavaScript file
       * should be inserted, may not be honored in case of path conflicts.
       * @param {String} options.data The code to be added.
       * @param {String} options.sourcePath The path that will be used in
       * any error messages generated by this file, e.g. `foo.js:4:1: error`.
       * @memberOf CompileStep
       * @instance
       */
      addJavaScript: function (options) {
        if (typeof options.data !== "string")
          throw new Error("'data' option to addJavaScript must be a string");
        if (typeof options.sourcePath !== "string")
          throw new Error("'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.");

        // By default, use fileOptions for the `bare` option but also allow
        // overriding it with the options
        var bare = fileOptions.bare;
        if (options.hasOwnProperty("bare")) {
          bare = options.bare;
        }

        js.push({
          source: files.convertToStandardLineEndings(options.data),
          sourcePath: files.convertToStandardPath(options.sourcePath, true),
          servePath: files.pathJoin(
            inputSourceArch.pkg.serveRoot,
            files.convertToStandardPath(options.path, true)),
          bare: !! bare,
          sourceMap: convertSourceMapPaths(options.sourceMap,
                                           files.convertToStandardPath),
          sourceHash: options._hash
        });
      },

      /**
       * @summary Add a file to serve as-is to the browser or to include on
       * the browser, depending on the target. On the web, it will be served
       * at the exact path requested. For server targets, it can be retrieved
       * using `Assets.getText` or `Assets.getBinary`.
       * @param {Object} options
       * @param {String} path The path at which to serve the asset.
       * @param {Buffer|String} data The data that should be placed in
       * the file.
       * @memberOf CompileStep
       * @instance
       */
      addAsset: function (options) {
        if (! (options.data instanceof Buffer)) {
          if (_.isString(options.data)) {
            options.data = new Buffer(options.data);
          } else {
            throw new Error("'data' option to addAsset must be a Buffer or String.");
          }
        }

        addAsset(options.data, files.convertToStandardPath(options.path, true));
      },

      /**
       * @summary Display a build error.
       * @param  {Object} options
       * @param {String} message The error message to display.
       * @param {String} [sourcePath] The path to display in the error message.
       * @param {Integer} line The line number to display in the error message.
       * @param {String} func The function name to display in the error message.
       * @memberOf CompileStep
       * @instance
       */
      error: function (options) {
        buildmessage.error(options.message || ("error building " + relPath), {
          file: options.sourcePath,
          line: options.line ? options.line : undefined,
          column: options.column ? options.column : undefined,
          func: options.func ? options.func : undefined
        });
      }
    };

    try {
      (buildmessage.markBoundary(handler))(compileStep);
    } catch (e) {
      e.message = e.message + " (compiling " + relPath + ")";
      buildmessage.exception(e);

      // Recover by ignoring this source file (as best we can -- the
      // handler might already have emitted resources)
    }
  });

  // *** Run Phase 1 link

  // Load jsAnalyze from the js-analyze package... unless we are the
  // js-analyze package, in which case never mind. (The js-analyze package's
  // default unibuild is not allowed to depend on anything!)
  var jsAnalyze = null;
  if (! _.isEmpty(js) && inputSourceArch.pkg.name !== "js-analyze") {
    jsAnalyze = isopackets.load('js-analyze')['js-analyze'].JSAnalyze;
  }

  var results = linker.prelink({
    inputFiles: js,
    useGlobalNamespace: isApp,
    // I was confused about this, so I am leaving a comment -- the
    // combinedServePath is either [pkgname].js or [pluginName]:plugin.js.
    // XXX: If we change this, we can get rid of source arch names!
    combinedServePath: isApp ? null :
      "/packages/" + colonConverter.convert(
        inputSourceArch.pkg.name +
        (inputSourceArch.kind === "main" ? "" : (":" + inputSourceArch.kind)) +
        ".js"),
    name: inputSourceArch.pkg.name || null,
    declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),
    jsAnalyze: jsAnalyze,
    noLineNumbers: noLineNumbers
  });

  // *** Determine captured variables
  var packageVariables = [];
  var packageVariableNames = {};
  _.each(inputSourceArch.declaredExports, function (symbol) {
    if (_.has(packageVariableNames, symbol.name))
      return;
    packageVariables.push({
      name: symbol.name,
      export: symbol.testOnly? "tests" : true
    });
    packageVariableNames[symbol.name] = true;
  });
  _.each(results.assignedVariables, function (name) {
    if (_.has(packageVariableNames, name))
      return;
    packageVariables.push({
      name: name
    });
    packageVariableNames[name] = true;
  });

  // *** Consider npm dependencies and portability
  var arch = inputSourceArch.arch;
  if (arch === "os" && ! isPortable) {
    // Contains non-portable compiled npm modules, so set arch correctly
    arch = archinfo.host();
  }
  if (! archinfo.matches(arch, "os")) {
    // npm modules only work on server architectures
    nodeModulesPath = undefined;
  }

  // *** Output unibuild object
  isopk.addUnibuild({
    kind: inputSourceArch.kind,
    arch: arch,
    uses: inputSourceArch.uses,
    implies: inputSourceArch.implies,
    watchSet: watchSet,
    nodeModulesPath: nodeModulesPath,
    prelinkFiles: results.files,
    packageVariables: packageVariables,
    resources: resources
  });

  return {
    pluginProviderPackageNames: pluginProviderPackageNames
  };
};

var runLinters = function (
  inputSourceArch,
  isopackCache,
  wrappedSourceItems,
  linterPluginsByExtension) {
  // For linters, figure out what are the global imports from other packages
  // that we use directly, or are implied.
  var globalImports = ['Package', 'Assets', 'Npm'];
  compiler.eachUsedUnibuild({
    dependencies: inputSourceArch.uses,
    arch: inputSourceArch.arch,
    isopackCache: isopackCache,
    skipUnordered: true,
    skipDebugOnly: true
  }, function (unibuild) {
    if (unibuild.pkg.name === inputSourceArch.pkg.name)
      return;
    _.each(unibuild.packageVariables, function (symbol) {
      if (symbol.export === true)
        globalImports.push(symbol.name);
    });
  });

  // For each file choose the longest extension handled by linters.
  var longestMatchingExt = {};
  _.each(wrappedSourceItems, function (wrappedSource) {
    var filename = files.pathBasename(wrappedSource.relPath);
    var parts = filename.split('.');
    for (var i = 1; i < parts.length; i++) {
      var extension = parts.slice(i).join('.');
      if (_.has(linterPluginsByExtension, extension)) {
        longestMatchingExt[wrappedSource.relPath] = extension;
        break;
      }
    }
  });

  // Run linters on files.
  _.each(linterPluginsByExtension, function (linters, ext) {
    var sourcesToLint = [];
    _.each(wrappedSourceItems, function (wrappedSource) {
      var relPath = wrappedSource.relPath;
      var hash = wrappedSource.hash;
      var fileWatchSet = wrappedSource.watchset;
      var source = wrappedSource.source;

      // only run linters matching the longest handled extension
      if (longestMatchingExt[relPath] !== ext)
        return;

      sourcesToLint.push(new linterPluginModule.LintingFile(wrappedSource));
    });

    _.each(linters, function (linterDef) {
      // skip linters not relevant to the arch we are compiling for
      if (! linterDef.relevantForArch(inputSourceArch.arch))
        return;

      var linter = linterDef.instantiatePlugin();
      buildmessage.enterJob({
        title: "linting files with " + linterDef.isopack.name
      }, function () {
        try {
          var markedLinter = buildmessage.markBoundary(linter.run.bind(linter));
          markedLinter(sourcesToLint, globalImports);
        } catch (e) {
          buildmessage.exception(e);
        }
      });
    });
  });
};

// Iterates over each in options.dependencies as well as unibuilds implied by
// them. The packages in question need to already be built and in
// options.isopackCache.
compiler.eachUsedUnibuild = function (
  options, callback) {
  buildmessage.assertInCapture();
  var dependencies = options.dependencies;
  var arch = options.arch;
  var isopackCache = options.isopackCache;

  var acceptableWeakPackages = options.acceptableWeakPackages || {};

  var processedUnibuildId = {};
  var usesToProcess = [];
  _.each(dependencies, function (use) {
    if (options.skipUnordered && use.unordered)
      return;
    if (use.weak && !_.has(acceptableWeakPackages, use.package))
      return;
    usesToProcess.push(use);
  });

  while (! _.isEmpty(usesToProcess)) {
    var use = usesToProcess.shift();

    var usedPackage = isopackCache.getIsopack(use.package);

    // Ignore this package if we were told to skip debug-only packages and it is
    // debug-only.
    if (usedPackage.debugOnly && options.skipDebugOnly)
      continue;

    var unibuild = usedPackage.getUnibuildAtArch(arch);
    if (!unibuild) {
      // The package exists but there's no unibuild for us. A buildmessage has
      // already been issued. Recover by skipping.
      continue;
    }

    if (_.has(processedUnibuildId, unibuild.id))
      continue;
    processedUnibuildId[unibuild.id] = true;

    callback(unibuild, {
      unordered: !!use.unordered,
      weak: !!use.weak
    });

    _.each(unibuild.implies, function (implied) {
      usesToProcess.push(implied);
    });
  }
};


Template.configureLoginServiceDialogForMeetup.helpers({
  siteUrl: function () {
    return Meteor.absoluteUrl();
  }
});

Template.configureLoginServiceDialogForMeetup.fields = function () {
  return [
    {property: 'clientId', label: 'Key'},
    {property: 'secret', label: 'Secret'}
  ];
};


# Meteor packages used by this project, one per line.
#
# 'meteor add' and 'meteor remove' will edit this file for you,
# but you can also edit it by hand.

meteor-platform
underscore


var sourceExtensions = {};  // maps source extensions to isTemplate

var util = Npm.require('util');
var Future = Npm.require('fibers/future');
var path = Npm.require('path');
var jshint = Npm.require('jshint').JSHINT;

Plugin.registerLinter({
  extensions: ["jshintrc", "js"],
}, function () {
  var linter = new JsHintLinter();
  return linter;
});

function JsHintLinter () {};

JsHintLinter.prototype.processFilesForTarget = function (files, globals) {
  var conf = {
    undef: true,
    unused: true,
    node: true,
    browser: true
  };

  files.forEach(function (file) {
    // find the config file
    if (file.getBasename() === '.jshintrc') {
      var confStr = file.getContentsAsString();
      try {
        conf = JSON.parse(confStr);
      } catch (err) {
        file.error({ message: "Failed to parse .jshint file, not a valid JSON: " + err.message });
      }
      return;
    }
    // require configuration file to be called '.jshintrc'
    if (path.extname(file.getBasename()) !== '.js') {
      file.error({ message: "Unrecognized configuration file name. Configuration file should be called .jshintrc" });
      return;
    }
  });

  files.forEach(function (file) {
    if (file.getBasename() === '.jshintrc')
      return;
    if (! jshint(file.getContentsAsString(), conf, globals)) {
      jshint.errors.forEach(function (error) {
        file.error({
          message: error.reason,
          line: error.line,
          column: error.character
        });
      });
    }
  });
};


## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/

# Visual Studo 2015 cache/options directory
.vs/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUNIT
*.VisualState.xml
TestResult.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile

# Visual Studio profiler
*.psess
*.vsp
*.vspx

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding addin-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# NCrunch
_NCrunch_*
.*crunch*.local.xml

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config

# Windows Azure Build Output
csx/
*.build.csdef

# Windows Store app package directory
AppPackages/

# Others
*.[Cc]ache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
bower_components/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm

# SQL Server files
*.mdf
*.ldf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings

# Microsoft Fakes
FakesAssemblies/

# Node.js Tools for Visual Studio
.ntvs_analysis.dat

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt


// The HTTP proxy is primarily so we can use localhost:3000 with OAuth,
// on devices which don't run a webserver e.g. Android / iOS
// This is a generic HTTP proxy, like a mini-Squid
// (whereas run-proxy.js is just for our app)
var _ = require('underscore');
var Future = require('fibers/future');
var runLog = require('./run-log.js');
var url = require('url');

// options: listenPort, listenHost, onFailure
var HttpProxy = function (options) {
  var self = this;

  self.listenPort = options.listenPort;
  self.listenHost = options.listenHost;

  self.onFailure = options.onFailure || function () {};

  self.mode = "proxy";
  self.httpQueue = []; // keys: req, res
  self.websocketQueue = []; // keys: req, socket, head
  self.connectQueue = [];  // keys: req, socket, head

  self.proxy = null;
  self.server = null;
};

_.extend(HttpProxy.prototype, {
  // Start the proxy server, block (yield) until it is ready to go
  // (actively listening on outer and proxying to inner), and then
  // return.
  start: function () {
    var self = this;

    if (self.server)
      throw new Error("already running?");

    self.started = false;

    var http = require('http');
    var net = require('net');
    var httpProxy = require('http-proxy');

    self.proxy = httpProxy.createProxyServer({
      // agent is required to handle keep-alive, and http-proxy 1.0 is a little
      // buggy without it: https://github.com/nodejitsu/node-http-proxy/pull/488
      agent: new http.Agent({ maxSockets: 1000 }),
      xfwd: false //true
    });

    var server = self.server = http.createServer(function (req, res) {
      // Normal HTTP request
      self.httpQueue.push({ req: req, res: res });
      self._tryHandleConnections();
    });

    self.server.on('connect', function (req, socket, head) {
      self.connectQueue.push({ req: req, socket: socket, head: head });
      self._tryHandleConnections();
    });

    self.server.on('upgrade', function (req, socket, head) {
      // Websocket connection
      self.websocketQueue.push({ req: req, socket: socket, head: head });
      self._tryHandleConnections();
    });

    var fut = new Future;
    self.server.on('error', function (err) {
      if (err.code === 'EADDRINUSE') {
        var port = self.listenPort;
        runLog.log(
          "HTTP proxy server can't listen on port " + port + ". \n" +
          "If something else is using port " + port + ", you can\n" +
          "specify an alternative port with --http-proxy-port <port>.");
      } else if (self.listenHost &&
                 (err.code === 'ENOTFOUND' || err.code === 'EADDRNOTAVAIL')) {
        // This handles the case of "entered a DNS name that's unknown"
        // (ENOTFOUND from getaddrinfo) and "entered some random IP that we
        // can't bind to" (EADDRNOTAVAIL from listen).
        runLog.log(
          "Can't listen on host " + self.listenHost +
          " (" + err.code + " from " + err.syscall + ").");
      } else {
        runLog.log('' + err);
      }
      self.onFailure();
      // Allow start() to return.
      fut.isResolved() || fut['return']();
    });

    // Don't crash if the app doesn't respond; instead return an error
    // immediately.
    self.proxy.on('error', function (err, req, resOrSocket) {
      if (resOrSocket instanceof http.ServerResponse) {
        resOrSocket.writeHead(503, {
          'Content-Type': 'text/plain'
        });
        resOrSocket.end('Unexpected error.');
      } else if (resOrSocket instanceof net.Socket) {
        resOrSocket.end();
      }
    });

    self.server.listen(self.listenPort, self.listenHost || '0.0.0.0', function () {
      if (self.server) {
        self.started = true;
      } else {
        // stop() got called while we were invoking listen! Close the server (we
        // still have the var server). The rest of the cleanup shouldn't be
        // necessary.
        server.close();
      }
      fut.isResolved() || fut['return']();
    });

    fut.wait();
  },

  // Idempotent.
  stop: function () {
    var self = this;

    if (! self.server)
      return;

    if (! self.started) {
      // This probably means that we failed to listen. However, there could be a
      // race condition and we could be in the middle of starting to listen! In
      // that case, the listen callback will notice that we nulled out server
      // here.
      self.server = null;
      return;
    }

    // This stops listening but allows existing connections to
    // complete gracefully.
    self.server.close();
    self.server = null;

    // It doesn't seem to be necessary to do anything special to
    // destroy an httpProxy proxyserver object.
    self.proxy = null;

    // Drop any held connections.
    _.each(self.httpQueue, function (c) {
      c.res.statusCode = 500;
      c.res.end();
    });
    self.httpQueue = [];

    _.each(self.websocketQueue, function (c) {
      c.socket.destroy();
    });
    self.websocketQueue = [];

    _.each(self.connectQueue, function (c) {
      c.socket.destroy();
    });
    self.connectQueue = [];

    self.mode = "hold";
  },

  _tryHandleConnections: function () {
    var self = this;

    while (self.httpQueue.length) {
      if (self.mode !== "proxy")
        break;

      var c = self.httpQueue.shift();
      var req = c.req;
      var targetUrl = req.url;
      runLog.log("Proxy request: " + req.method + " " +req.url);
      var newUrl = req.url
      self.proxy.web(c.req, c.res, {
        target: targetUrl
      });
    }

    while (self.websocketQueue.length) {
      if (self.mode !== "proxy")
        break;

      var c = self.websocketQueue.shift();
      var req = c.req;
      var targetUrl = req.url;
      runLog.log("Proxy request (websocket): " + req.method + " " +req.url);
      self.proxy.ws(c.req, c.socket, c.head, {
        target: targetUrl
      });
    }

    while (self.connectQueue.length) {
      if (self.mode !== "proxy")
        break;

      var c = self.connectQueue.shift();
      runLog.log("Proxy request (connect): " + c.req.method + " " + c.req.url);
      proxyConnectMethod(c.req, c.socket, c.head);
    }
  },

  // The proxy can be in one of three modes:
  // - "proxy": connections are proxied
  //
  // The initial mode is "proxy".
  setMode: function (mode) {
    var self = this;
    self.mode = mode;
    self._tryHandleConnections();
  }
});

// This is what http-proxy does
// XXX: We should submit connect support upstream
var setupSocket = function(socket) {
  socket.setTimeout(0);
  socket.setNoDelay(true);

  socket.setKeepAlive(true, 0);

  return socket;
};

var proxyConnectMethod = function (req, socket, options, head, server, clb) {
  if (req.method !== 'CONNECT') {
    socket.destroy();
    return true;
  }

  var tokens = req.url.split(':');

  if (tokens.length != 2) {
    runLog.log("Bad request: " + req.url);
    socket.destroy();
    return true;
  }

  var host = tokens[0];
  var port = tokens[1];

  if (port != 443) {
    runLog.log("Blocking request to non-443 port: " + req.url);
    socket.destroy();
    return true;
  }

  setupSocket(socket);

  // XXX: Needed?
  // if (head && head.length) socket.unshift(head);

  var net = require('net');
  var proxySocket = net.createConnection(port, host);
  setupSocket(proxySocket);

  socket.on('error', function (err) {
    runLog.log("Error on socket: " + err);
    proxySocket.end();
  });
  proxySocket.on('error', function (err) {
    runLog.log("Error on proxySocket: " + err);
    socket.end();
  });

  proxySocket.on('connect', function(connect) {
    runLog.log("Connection established to " + host + ":" + port);
    socket.write("HTTP/1.0 200 Connection established\n\n");
    socket.pipe(proxySocket);
    proxySocket.pipe(socket);
  });
};

exports.HttpProxy = HttpProxy;


@menu-width: 270px;
@column: 5.55555%;

body {
  .position(absolute, 0, 0, 0, 0);
  background-color: #315481;
  .background-image( linear-gradient(top, #315481, #918e82 100%) );
  background-repeat: no-repeat;
  background-attachment: fixed;
}

#container {
  .position(absolute, 0, 0, 0, 0);

  @media screen and (min-width: 60em) {
    left: @column;
    right: @column;
  }

  @media screen and (min-width: 80em) {
    left: 2*@column;
    right: 2*@column;
  }

  // Hide anything offscreen
  overflow: hidden;
}

#menu {
  .position(absolute, 0, 0, 0, 0, @menu-width);
}

#content-container {
  .position(absolute, 0, 0, 0, 0);
  .transition(all 200ms ease-out);
  .transform(translate3d(0, 0, 0));
  background: @color-tertiary;
  opacity: 1;

  @media screen and (min-width: 40em) {
    left: @menu-width;
  }

  .content-scrollable {
    .position(absolute, 0, 0, 0, 0);
    .transform(translate3d(0, 0, 0));
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  // Toggle menu on mobile
  .menu-open & {
    .transform(translate3d(@menu-width, 0, 0));
    opacity: .85;
    left: 0;

    @media screen and (min-width: 40em) {
      // Show menu on desktop, negate .menu-open
      .transform(translate3d(0, 0, 0)); //reset transform and use position properties instead
      opacity: 1;
      left: @menu-width;
    }
  }
}

// Transparent screen to prevent interactions on content when menu is open
.content-overlay {
  .position(absolute, 0, 0, 0, 0);
  cursor: pointer;

  .menu-open & {
    .transform(translate3d(@menu-width, 0, 0));
    z-index: 1;
  }

  // Hide overlay on desktop
  @media screen and (min-width: 40em) { display: none; }
}


_.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {


#pragma once
//-------------------------------------------------------------------------------------------------
// <copyright file="dutil.h" company="Outercurve Foundation">
//   Copyright (c) 2004, Outercurve Foundation.
//   This software is released under Microsoft Reciprocal License (MS-RL).
//   The license and further copyright text can be found in the file
//   LICENSE.TXT at the root directory of the distribution.
// </copyright>
//
// <summary>
//    Header for utility layer that provides standard support for asserts, exit macros
// </summary>
//-------------------------------------------------------------------------------------------------

#define DAPI __stdcall
#define DAPIV __cdecl // used only for functions taking variable length arguments

#define DAPI_(type) EXTERN_C type DAPI
#define DAPIV_(type) EXTERN_C type DAPIV

// enums
enum REPORT_LEVEL
{
    REPORT_NONE,      // turns off report (only valid for XXXSetLevel())
    REPORT_WARNING,   // written if want only warnings or reporting is on in general
    REPORT_STANDARD,  // written if reporting is on
    REPORT_VERBOSE,   // written only if verbose reporting is on
    REPORT_DEBUG,     // reporting useful when debugging code
    REPORT_ERROR,     // always gets reported, but can never be specified
};

// asserts and traces
typedef BOOL (DAPI *DUTIL_ASSERTDISPLAYFUNCTION)(__in_z LPCSTR sz);

extern "C" void DAPI Dutil_SetAssertModule(__in HMODULE hAssertModule);
extern "C" void DAPI Dutil_SetAssertDisplayFunction(__in DUTIL_ASSERTDISPLAYFUNCTION pfn);
extern "C" void DAPI Dutil_Assert(__in_z LPCSTR szFile, __in int iLine);
extern "C" void DAPI Dutil_AssertSz(__in_z LPCSTR szFile, __in int iLine, __in_z LPCSTR szMsg);

extern "C" void DAPI Dutil_TraceSetLevel(__in REPORT_LEVEL ll, __in BOOL fTraceFilenames);
extern "C" REPORT_LEVEL DAPI Dutil_TraceGetLevel();
extern "C" void __cdecl Dutil_Trace(__in_z LPCSTR szFile, __in int iLine, __in REPORT_LEVEL rl, __in_z __format_string LPCSTR szMessage, ...);
extern "C" void __cdecl Dutil_TraceError(__in_z LPCSTR szFile, __in int iLine, __in REPORT_LEVEL rl, __in HRESULT hr, __in_z __format_string LPCSTR szMessage, ...);
extern "C" void DAPI Dutil_RootFailure(__in_z LPCSTR szFile, __in int iLine, __in HRESULT hrError);

#ifdef DEBUG

#define AssertSetModule(m) (void)Dutil_SetAssertModule(m)
#define AssertSetDisplayFunction(pfn) (void)Dutil_SetAssertDisplayFunction(pfn)
#define Assert(f)          ((f)    ? (void)0 : (void)Dutil_Assert(__FILE__, __LINE__))
#define AssertSz(f, sz)    ((f)    ? (void)0 : (void)Dutil_AssertSz(__FILE__, __LINE__, sz))

#define TraceSetLevel(l, f) (void)Dutil_TraceSetLevel(l, f)
#define TraceGetLevel() (REPORT_LEVEL)Dutil_TraceGetLevel()
#define Trace(l, f) (void)Dutil_Trace(__FILE__, __LINE__, l, f, NULL)
#define Trace1(l, f, s) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s)
#define Trace2(l, f, s, t) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s, t)
#define Trace3(l, f, s, t, u) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s, t, u)

#define TraceError(x, f) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, NULL)
#define TraceError1(x, f, s) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s)
#define TraceError2(x, f, s, t) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s, t)
#define TraceError3(x, f, s, t, u) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s, t, u)

#define TraceErrorDebug(x, f) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, NULL)
#define TraceErrorDebug1(x, f, s) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s)
#define TraceErrorDebug2(x, f, s, t) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s, t)
#define TraceErrorDebug3(x, f, s, t, u) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s, t, u)

#else // !DEBUG

#define AssertSetModule(m)
#define AssertSetDisplayFunction(pfn)
#define Assert(f)
#define AssertSz(f, sz)

#define TraceSetLevel(l, f)
#define Trace(l, f)
#define Trace1(l, f, s)
#define Trace2(l, f, s, t)
#define Trace3(l, f, s, t, u)

#define TraceError(x, f)
#define TraceError1(x, f, s)
#define TraceError2(x, f, s, t)
#define TraceError3(x, f, s, t, u)

#define TraceErrorDebug(x, f)
#define TraceErrorDebug1(x, f, s)
#define TraceErrorDebug2(x, f, s, t)
#define TraceErrorDebug3(x, f, s, t, u)

#endif // DEBUG

// ExitTrace can be overriden
#ifndef ExitTrace
#define ExitTrace TraceError
#endif
#ifndef ExitTrace1
#define ExitTrace1 TraceError1
#endif
#ifndef ExitTrace2
#define ExitTrace2 TraceError2
#endif
#ifndef ExitTrace3
#define ExitTrace3 TraceError3
#endif

// Exit macros
#define ExitFunction()        { goto LExit; }
#define ExitFunction1(x)          { x; goto LExit; }

#define ExitOnLastError(x, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; } }
#define ExitOnLastError1(x, f, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; } }
#define ExitOnLastError2(x, f, s, t) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; } }

#define ExitOnLastErrorDebugTrace(x, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug(x, s); goto LExit; } }
#define ExitOnLastErrorDebugTrace1(x, f, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug1(x, f, s); goto LExit; } }
#define ExitOnLastErrorDebugTrace2(x, f, s, t) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug2(x, f, s, t); goto LExit; } }

#define ExitWithLastError(x, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitWithLastError1(x, f, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }
#define ExitWithLastError2(x, f, s, t) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }
#define ExitWithLastError3(x, f, s, t, u) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace3(x, f, s, t, u); goto LExit; }

#define ExitOnFailure(x, s)   if (FAILED(x)) { ExitTrace(x, s);  goto LExit; }
#define ExitOnFailure1(x, f, s)   if (FAILED(x)) { ExitTrace1(x, f, s);  goto LExit; }
#define ExitOnFailure2(x, f, s, t)   if (FAILED(x)) { ExitTrace2(x, f, s, t);  goto LExit; }
#define ExitOnFailure3(x, f, s, t, u) if (FAILED(x)) { ExitTrace3(x, f, s, t, u);  goto LExit; }

#define ExitOnRootFailure(x, s)   if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s);  goto LExit; }
#define ExitOnRootFailure1(x, f, s)   if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s);  goto LExit; }
#define ExitOnRootFailure2(x, f, s, t)   if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t);  goto LExit; }
#define ExitOnRootFailure3(x, f, s, t, u) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace3(x, f, s, t, u);  goto LExit; }

#define ExitOnFailureDebugTrace(x, s)   if (FAILED(x)) { TraceErrorDebug(x, s);  goto LExit; }
#define ExitOnFailureDebugTrace1(x, f, s)   if (FAILED(x)) { TraceErrorDebug1(x, f, s);  goto LExit; }
#define ExitOnFailureDebugTrace2(x, f, s, t)   if (FAILED(x)) { TraceErrorDebug2(x, f, s, t);  goto LExit; }
#define ExitOnFailureDebugTrace3(x, f, s, t, u) if (FAILED(x)) { TraceErrorDebug3(x, f, s, t, u);  goto LExit; }

#define ExitOnNull(p, x, e, s)   if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s);  goto LExit; }
#define ExitOnNull1(p, x, e, f, s)   if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s);  goto LExit; }
#define ExitOnNull2(p, x, e, f, s, t)   if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t);  goto LExit; }

#define ExitOnNullWithLastError(p, x, s) if (NULL == p) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitOnNullWithLastError1(p, x, f, s) if (NULL == p) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }

#define ExitOnNullDebugTrace(p, x, e, s)   if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug(x, s);  goto LExit; }
#define ExitOnNullDebugTrace1(p, x, e, f, s)   if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug1(x, f, s);  goto LExit; }

#define ExitOnInvalidHandleWithLastError(p, x, s) if (INVALID_HANDLE_VALUE == p) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitOnInvalidHandleWithLastError1(p, x, f, s) if (INVALID_HANDLE_VALUE == p) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }

#define ExitOnWin32Error(e, x, s) if (ERROR_SUCCESS != e) { x = HRESULT_FROM_WIN32(e); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitOnWin32Error1(e, x, f, s) if (ERROR_SUCCESS != e) { x = HRESULT_FROM_WIN32(e); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }
#define ExitOnWin32Error2(e, x, f, s, t) if (ERROR_SUCCESS != e) { x = HRESULT_FROM_WIN32(e); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }

// release macros
#define ReleaseObject(x) if (x) { x->Release(); }
#define ReleaseObjectArray(prg, cel) if (prg) { for (DWORD Dutil_ReleaseObjectArrayIndex = 0; Dutil_ReleaseObjectArrayIndex < cel; ++Dutil_ReleaseObjectArrayIndex) { ReleaseObject(prg[Dutil_ReleaseObjectArrayIndex]); } ReleaseMem(prg); }
#define ReleaseVariant(x) { ::VariantClear(&x); }
#define ReleaseNullObject(x) if (x) { (x)->Release(); x = NULL; }
#define ReleaseCertificate(x) if (x) { ::CertFreeCertificateContext(x); x=NULL; }
#define ReleaseHandle(x) if (x) { ::CloseHandle(x); x = NULL; }

// useful defines and macros
#define Unused(x) ((void)x)

#ifndef countof
#if 1
#define countof(ary) (sizeof(ary) / sizeof(ary[0]))
#else
#ifndef __cplusplus
#define countof(ary) (sizeof(ary) / sizeof(ary[0]))
#else
template<typename T> static char countofVerify(void const *, T) throw() { return 0; }
template<typename T> static void countofVerify(T *const, T *const *) throw() {};
#define countof(arr) (sizeof(countofVerify(arr,&(arr))) * sizeof(arr)/sizeof(*(arr)))
#endif
#endif
#endif

#define roundup(x, n) roundup_typed(x, n, DWORD)
#define roundup_typed(x, n, t) (((t)(x) + ((t)(n) - 1)) & ~((t)(n) - 1))

#define HRESULT_FROM_RPC(x) ((HRESULT) ((x) | FACILITY_RPC))

#ifndef MAXSIZE_T
#define MAXSIZE_T ((SIZE_T)~((SIZE_T)0))
#endif

typedef const BYTE* LPCBYTE;

#define E_FILENOTFOUND HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
#define E_PATHNOTFOUND HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)
#define E_INVALIDDATA HRESULT_FROM_WIN32(ERROR_INVALID_DATA)
#define E_INVALIDSTATE HRESULT_FROM_WIN32(ERROR_INVALID_STATE)
#define E_INSUFFICIENT_BUFFER HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)
#define E_MOREDATA HRESULT_FROM_WIN32(ERROR_MORE_DATA)
#define E_NOMOREITEMS HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS)
#define E_NOTFOUND HRESULT_FROM_WIN32(ERROR_NOT_FOUND)
#define E_MODNOTFOUND HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND)
#define E_BADCONFIGURATION HRESULT_FROM_WIN32(ERROR_BAD_CONFIGURATION)

#define AddRefAndRelease(x) { x->AddRef(); x->Release(); }

#define MAKEDWORD(lo, hi) ((DWORD)MAKELONG(lo, hi))
#define MAKEQWORDVERSION(mj, mi, b, r) (((DWORD64)MAKELONG(r, b)) | (((DWORD64)MAKELONG(mi, mj)) << 32))

// other functions
extern "C" HRESULT DAPI LoadSystemLibrary(__in_z LPCWSTR wzModuleName, __out HMODULE *phModule);
extern "C" HRESULT DAPI LoadSystemLibraryWithPath(__in_z LPCWSTR wzModuleName, __out HMODULE *phModule, __deref_out_z_opt LPWSTR* psczPath);


# weibo

An implementation of the Weibo OAuth flow. See the [project
page](https://www.meteor.com/accounts) on Meteor Accounts for more
details.


_.each(linterPlugin.extensions, function (ext) {

linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];

// Note: sourceExtensions does not include leading dots

keep replace replace replace replace keep keep keep keep keep


accounts-base@1.2.0
accounts-password@1.1.1
autoupdate@1.2.1
base64@1.0.3
binary-heap@1.0.3
blaze@2.1.2
blaze-tools@1.0.3
boilerplate-generator@1.0.3
callback-hook@1.0.3
check@1.0.5
ddp@1.1.0
deps@1.0.7
ejson@1.0.6
email@1.0.6
fastclick@1.0.3
geojson-utils@1.0.3
html-tools@1.0.4
htmljs@1.0.4
http@1.1.0
id-map@1.0.3
insecure@1.0.3
iron:core@0.3.4
iron:dynamic-template@0.4.1
iron:layout@0.4.1
iron:router@0.9.4
jquery@1.11.3_2
json@1.0.3
launch-screen@1.0.2
less@1.0.14
livedata@1.0.13
localstorage@1.0.3
logging@1.0.7
meteor@1.1.6
meteor-platform@1.2.2
minifiers@1.1.5
minimongo@1.0.8
mobile-status-bar@1.0.3
mongo@1.1.0
npm-bcrypt@0.7.8_2
observe-sequence@1.0.6
ordered-dict@1.0.3
random@1.0.3
reactive-dict@1.1.0
reactive-var@1.0.5
reload@1.1.3
retry@1.0.3
routepolicy@1.0.5
service-configuration@1.0.4
session@1.1.0
sha@1.0.3
spacebars@1.0.6
spacebars-compiler@1.0.6
srp@1.0.3
templating@1.1.1
tracker@1.0.7
ui@1.0.6
underscore@1.0.3
url@1.0.4
webapp@1.2.0
webapp-hashing@1.0.3


Package.describe({
  summary: "Deprecated: Use the 'blaze' package",
  version: '1.0.6'
});

Package.onUse(function (api) {
  api.use('blaze');
  api.imply('blaze');

  // XXX COMPAT WITH PACKAGES BUILT FOR 0.9.0.
  //
  // (in particular, packages that have a weak dependency on this
  // package, since then exported symbols live on the
  // `Package.ui` object)
  api.export(['Blaze', 'UI', 'Handlebars']);
});


runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);

_.each(wrappedSourceItems, function (wrappedSource) {

keep keep keep keep keep replace keep keep keep

runLinters(inputSourceArch, isopackCache, wrappedSourceItems, allLinters);


# Defer in Inactive Tab

Tests that `Meteor.defer` works in an inactive tab in iOS Safari.

(`setTimeout` and `setInterval` events aren't delivered to inactive
tabs in iOS Safari until they become active again).

Sadly we have to run the test manually because scripts aren't allowed
to open windows themselves except in response to user events.

This test will not run on Chrome for iOS because the storage event is
not implemented in that browser.  Also doesn't attempt to run on
versions of IE that don't support `window.addEventListener`.


====================================================================
For the license for Meteor itself, see LICENSE.txt in the root of
the repository.  This file contains the licenses for externally
maintained libraries.
====================================================================

----------
MongoDB: http://www.mongodb.org/
----------

LICENSE

  Most MongoDB source files are made available under the terms of the
  GNU Affero General Public License (AGPL).  See individual files for
  details.

  As an exception, the files in the client/, debian/, rpm/,
  utils/mongoutils, and all subdirectories thereof are made available under
  the terms of the Apache License, version 2.0.

http://www.gnu.org/licenses/agpl-3.0.html
http://www.apache.org/licenses/LICENSE-2.0

MongoDB uses third-party libraries or other resources that may
be distributed under licenses different than the MongoDB software.

In the event that we accidentally failed to list a required notice,
please bring it to our attention through any of the ways detailed here :

           mongodb-dev@googlegroups.com

The attached notices are provided for information only.

1) License Notice for Boost
---------------------------

http://www.boost.org/LICENSE_1_0.txt

Boost Software License - Version 1.0 - August 17th, 2003

Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:

The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

2) License Notice for V8
-------------------------

http://code.google.com/p/v8/source/browse/trunk/LICENSE

This license applies to all parts of V8 that are not externally
maintained libraries.  The externally maintained libraries used by V8
are:

  - Jscre, located under third_party/jscre.  This code is copyrighted
    by the University of Cambridge and Apple Inc. and released under a
    2-clause BSD license.

  - Dtoa, located under third_party/dtoa.  This code is copyrighted by
    David M. Gay and released under an MIT license.

  - Strongtalk assembler, the basis of the files assembler-arm-inl.h,
    assembler-arm.cc, assembler-arm.h, assembler-ia32-inl.h,
    assembler-ia32.cc, assembler-ia32.h, assembler.cc and assembler.h.
    This code is copyrighted by Sun Microsystems Inc. and released
    under a 3-clause BSD license.

These libraries have their own licenses; we recommend you read them,
as their terms may differ from the terms below.

Copyright 2006-2008, Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.
    * Neither the name of Google Inc. nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

3) License Notice for PCRE
--------------------------

http://www.pcre.org/licence.txt

PCRE LICENCE
------------

PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.

Release 7 of PCRE is distributed under the terms of the "BSD" licence, as
specified below. The documentation for PCRE, supplied in the "doc"
directory, is distributed under the same terms as the software itself.

The basic library functions are written in C and are freestanding. Also
included in the distribution is a set of C++ wrapper functions.

THE BASIC LIBRARY FUNCTIONS
---------------------------

Written by:       Philip Hazel
Email local part: ph10
Email domain:     cam.ac.uk

University of Cambridge Computing Service,
Cambridge, England.

Copyright (c) 1997-2008 University of Cambridge
All rights reserved.

THE C++ WRAPPER FUNCTIONS
-------------------------

Contributed by:   Google Inc.

Copyright (c) 2007-2008, Google Inc.
All rights reserved.

THE "BSD" LICENCE
-----------------

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    * Neither the name of the University of Cambridge nor the name of Google
      Inc. nor the names of their contributors may be used to endorse or
      promote products derived from this software without specific prior
      written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

4) License notice for Aladdin MD5
---------------------------------

Copyright (C) 1999, 2002 Aladdin Enterprises.  All rights reserved.

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.

L. Peter Deutsch
ghost@aladdin.com

5) License notice for Snappy - http://code.google.com/p/snappy/
---------------------------------
 Copyright 2005 and onwards Google Inc.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:

     * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above
 copyright notice, this list of conditions and the following disclaimer
 in the documentation and/or other materials provided with the
 distribution.
     * Neither the name of Google Inc. nor the names of its
 contributors may be used to endorse or promote products derived from
 this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 A light-weight compression algorithm.  It is designed for speed of
 compression and decompression, rather than for the utmost in space
 savings.

 For getting better compression ratios when you are compressing data
 with long repeated sequences or compressing data that is similar to
 other data, while still compressing fast, you might look at first
 using BMDiff and then compressing the output of BMDiff with
 Snappy.

End


// For linters, figure out what are the global imports from other packages

// that we use directly, or are implied.

keep keep keep keep keep replace keep keep


var getNonZeroWeightedTerms = function (costTerms, costWeights) {
  if (typeof costWeights === 'number') {
    return costWeights ? costTerms : [];
  } else {
    var terms = [];
    for (var i = 0; i < costTerms.length; i++) {
      if (costWeights[i]) {
        terms.push(costTerms[i]);
      }
    }
    return terms;
  }
};

// See comments on minimizeWeightedSum and maximizeWeightedSum.
var minMaxWS = function (solver, solution, costTerms, costWeights, options,
                         isMin) {
  var curSolution = solution;
  var curCost = curSolution.getWeightedSum(costTerms, costWeights);

  var optFormula = options && options.formula;
  var weightedSum = (optFormula || Logic.weightedSum(costTerms, costWeights));

  var progress = options && options.progress;
  var strategy = options && options.strategy;

  // array of terms with non-zero weights, populated on demand
  var nonZeroTerms = null;

  if (isMin && curCost > 0) {
    // try to skip straight to 0 cost, because if it works, it could
    // save us some time
    if (progress) {
      progress('trying', 0);
    }
    var zeroSolution = null;
    nonZeroTerms = getNonZeroWeightedTerms(costTerms, costWeights);
    var zeroSolution = solver.solveAssuming(Logic.not(Logic.or(nonZeroTerms)));
    if (zeroSolution) {
      curSolution = zeroSolution;
      curCost = 0;
    }
  }

  if (isMin && strategy === 'bottom-up') {
    for (var trialCost = 1; trialCost < curCost; trialCost++) {
      if (progress) {
        progress('trying', trialCost);
      }
      var costIsTrialCost = Logic.equalBits(
        weightedSum, Logic.constantBits(trialCost));
      var newSolution = solver.solveAssuming(costIsTrialCost);
      if (newSolution) {
        curSolution = newSolution;
        curCost = trialCost;
        break;
      }
    }
  } else if (strategy && strategy !== 'default') {
    throw new Error("Bad strategy: " + strategy);
  } else {
    strategy = 'default';
  }

  if (strategy === 'default') {
    // for minimization, count down from current cost. for maximization,
    // count up.
    while (isMin ? curCost > 0 : true) {
      if (progress) {
        progress('improving', curCost);
      }
      var improvement = (isMin ? Logic.lessThan : Logic.greaterThan)(
        weightedSum, Logic.constantBits(curCost));
      var newSolution = solver.solveAssuming(improvement);
      if (! newSolution) {
        break;
      }
      solver.require(improvement);
      curSolution = newSolution;
      curCost = curSolution.getWeightedSum(costTerms, costWeights);
    }
  }

  if (isMin && curCost === 0) {
    // express the requirement that the weighted sum be 0 in an efficient
    // way for the solver (all terms with non-zero weights must be 0)
    if (! nonZeroTerms) {
      nonZeroTerms = getNonZeroWeightedTerms(costTerms, costWeights);
    }
    solver.forbid(nonZeroTerms);
  } else {
    solver.require(Logic.equalBits(weightedSum, Logic.constantBits(curCost)));
  }

  if (progress) {
    progress('finished', curCost);
  }

  return curSolution;
};

// Minimize (or maximize) the dot product of costTerms and
// costWeights, and further, require (as in solver.require) that the
// value of the dot product be equal to the optimum found.  Returns a
// valid solution where this optimum is achieved.
//
// `solution` must be a current valid solution as returned from
// `solve` or `solveAssuming`.  It is used as a starting point (to
// evaluate the current cost).
//
// costWeights is an array (of same length as costTerms) or a single
// WholeNumber.
//
// if the caller passes options.formula, it should be the formula
// Logic.weightedSum(costTerms, costWeights).  The optimizer will use
// this existing formula rather than generating a new one (for
// efficiency).  The optimizer still wants to know the terms and
// weights, because it is more efficient for it to evaluate the
// current cost using them directly rather than the formula.
//
// options.progress: a function that takes two arguments, to call at
// particular times during optimization.  Called with arguments
// ('improving', cost) when about to search for a way to improve on
// `cost`, and called with arguments ('finished', cost) when the
// optimum is reached.  There's also ('trying', cost) when a cost
// is tried directly (which is usually done with 0 right off the bat).
//
// options.strategy: a string hinting how to go about the optimization.
// the default strategy (option absent or 'default') is to work down
// from the current cost for minimization or up from the current cost
// for maximization, and iteratively insist that the cost be made lower
// if possible.  For minimization, the alternate strategy 'bottom-up' is
// available, which starts at 0 and tries ever higher costs until one
// works.  All strategies first try and see if a cost of 0 is possible.

// ("costTerms" is kind of a misnomer since they may be Formulas or Terms.)
Logic.Solver.prototype.minimizeWeightedSum = function (solution, costTerms,
                                                       costWeights, options) {
  return minMaxWS(this, solution, costTerms, costWeights, options, true);
};

Logic.Solver.prototype.maximizeWeightedSum = function (solution, costTerms,
                                                       costWeights, options) {
  return minMaxWS(this, solution, costTerms, costWeights, options, false);
};