Installs a JavaScript package downloaded from npmjs.org.

    For example to install React::

        install_jspackage('react', '0.14.8', './node_modules')

    To install last version provide `None` as the version.
557972
def install_jspackage(package_name, version, modulesdir):
    
    if not version:
        version = ''

    requirements = _resolve_dependencies(package_name, version)
    print('Packages going to be installed: {0}'.format(', '.join(
        '{0}->{1}'.format(*i) for i in requirements
    )))

    downloads = {}
    for dependency_name, _, version_info in requirements:
        try:
            downloads[dependency_name] = version_info['dist']['tarball']
        except KeyError:
            raise JSPackageInstallError('Unable to detect a supported download url for package',
                                        error_code=3)

    for dependency_name, download_url in downloads.items():
        tarball = BytesIO()
        print('Fetching {0}'.format(download_url), end='')
        with closing(urlopen(download_url)) as data:
            chunk = data.read(1024)
            while chunk:
                print('.', end='')
                tarball.write(chunk)
                chunk = data.read(1024)
        print('')

        tarball.seek(0)
        with closing(tarfile.open(fileobj=tarball)) as tb:
            dest = os.path.join(modulesdir, dependency_name)
            tmpdir = tempfile.mkdtemp()
            try:
                tb.extractall(tmpdir)
                shutil.rmtree(os.path.abspath(dest), ignore_errors=True)
                shutil.move(os.path.join(tmpdir, 'package'),
                            os.path.abspath(dest))
            finally:
                shutil.rmtree(tmpdir)

    print('Installing {0} in {1} Done!'.format(package_name, modulesdir))
1114074
function packageVersion(repo) {
    var location = repo ? path.join(repo, 'package.json') : './package.json';
    var pack = require(location);
    return pack['version'];
}
165095
def run(self):
        has_npm = npm_installation_check()
        if has_npm:
            run_npm_install()
        else:
            print("Warning: npm not installed using prebuilded js files!",
                  file=sys.stderr)
        
        for js in JS_FILES:
            downloaded_js_name = os.path.join(TOP_DIR, js)
            installed_js_name = os.path.join(TOP_DIR, "sphinx_hwt", "html", js)
            if has_npm:
                assert os.path.exists(downloaded_js_name), downloaded_js_name
                os.makedirs(os.path.dirname(installed_js_name), exist_ok=True)
                copyfile(downloaded_js_name, installed_js_name)
                print("copy generated from NPM packages", installed_js_name)
            else:
                if os.path.exists(installed_js_name):
                    print("using prebuilded", installed_js_name)
                else:
                    raise Exception("Can not find npm,"
                                    " which is required for the installation "
                                    "and this is pacpage has not js prebuilded")
1127680
async function updatePackageJSON (version) {
  ['package.json'].forEach(async fileName => {
    const filePath = path.resolve(__dirname, '..', fileName)
    const file = require(filePath)
    file.version = version
    await writeFile(filePath, JSON.stringify(file, null, 2))
  })
}
321350
function npmInstall(packageName)
{
    return new Promise((resolve,reject) => {
        
        npm.load({
            save:false,
			progress: false,
            force:true
        }, function (er) {
            if (er)
            {
                PAILogger.error(er);
				return reject(er);
			}
            
            npm.commands.install([packageName], function (er, data) {
                if (er) {
					PAILogger.error(er);
					return reject(er);
                }
                resolve(data);
                // command succeeded, and data might have some info
            });
            
        });
        
    });
}
242758
async function installPackages(environment) {
	const cwdBefore = process.cwd();
	await buildUnreleasedPackages();
	process.chdir(path.resolve(__dirname, '../environments', environment));
	console.log('🗑️  Removing packages for ' + environment);
	await rimrafAsync('package-lock.json');
	await rimrafAsync('node_modules');

	console.log('💿  Installing packages for ' + environment);
	await execAsync('npm install');
	process.chdir(cwdBefore);
}
1255898
function resolvePackage(packageName) {
    try {
      // First, try to use require.resolve to find the package.
      // We add /package.json and then dirname the result because require.resolve follows the `main`
      // property in package.json to produce a path to a file deep inside the package, and we want
      // the path to the top-level directory.
      // This branch handles packages being symlinked into node_modules, for example with
      // `npm link` or in sku's test cases.
      const result = path.dirname(
        resolve(`${packageName}/package.json`, { paths: [cwd()] }),
      );
      debug(`Resolved ${packageName} to ${result}`);
      return result;
    } catch (error) {
      if (error.code === 'MODULE_NOT_FOUND') {
        const dependencies = getProjectDependencies(fs.readFileSync);

        if (!dependencies[packageName]) {
          // If it's not we can safely return a naive local path, which prevents webpack from
          // throwing config schema errors when this function is used to configure a loader.
          // This branch handles the scenario where we're trying to resolve a design system module because
          // it's in the default list of compilePackages, but it's not actually being used in the project.
          const localPackage = path.join(cwd(), 'node_modules', packageName);
          debug(`Resolved unused package ${packageName} to ${localPackage}`);
          return localPackage;
        }
      }

      // We've gotten this far because the package is listed as a project dependency and can't be
      // resolved, or because the error is not ENOENT. In either case we want to throw.
      throw error;
    }
  }
186017
function resolveDependencies (pkg, cb) {
  if (!pkg) return topCb(new Error(
    "Package not found to resolve dependencies"))
  // link foo-1.0.3 to ROOT/.npm/{pkg}/{version}/node_modules/foo

  // see if it's bundled already
  var bundleDir = path.join( npm.dir, pkg.name, pkg.version
                           , "package", "node_modules" )
   , deps = pkg.dependencies && Object.keys(pkg.dependencies) || []
  log.verbose([pkg, deps], "deps being resolved")
  fs.readdir(bundleDir, function (er, bundledDeps) {
    if (er) bundledDeps = []
    bundledDeps.forEach(function (bd) {
      var i = deps.indexOf(bd)
      if (i !== -1) deps.splice(i, 1)
    })

    asyncMap(deps, function (i, cb) {
      var req = { name:i, version:pkg.dependencies[i] }
      log.verbose(req.name+"@"+req.version, "required")

      // see if we have this thing installed.
      fs.readdir(path.join(npm.dir, req.name), function (er, versions) {
        if (er) return cb(new Error(
          "Required package: "+req.name+"("+req.version+") not found."+
          "\n(required by: "+pkg._id+")"))
        // TODO: Get the "stable" version if there is one.
        // Look that up from the registry.
        var satis = semver.maxSatisfying(versions, req.version)
        if (satis) return cb(null, {name:req.name, version:satis})
        return cb(new Error(
          "Required package: "+req.name+"("+req.version+") not found. "+
          "(Found: "+JSON.stringify(versions)+")"+
          "\n(required by: "+pkg._id+")"))
      })
    }, function (er, found) {
      // save the resolved dependencies on the pkg data for later
      pkg._resolvedDeps = found
      cb(er, found)
    })
  })
}
987731
def package_install(name, **kwargs):
    '''
    
    '''
    cmd = 'pkg_install ' + name
    if kwargs.get('version', False):
        cmd += ' ' + kwargs['version']

    # Send the command to execute
    out, err = DETAILS['server'].sendline(cmd)

    # "scrape" the output and return the right fields as a dict
    return parse(out)
987050
function createWebpack ({ alias = {}, context, name = 'index' }) {
  const pkgJson = require(path.join(context, 'package.json'));
  const ENV = process.env.NODE_ENV || 'development';
  const isProd = ENV === 'production';
  const hasPublic = fs.existsSync(path.join(context, 'public'));
  const plugins = hasPublic
    ? [new CopyWebpackPlugin([{ from: 'public' }])]
    : [];

  return {
    context,
    devtool: isProd ? 'source-map' : 'cheap-eval-source-map',
    entry: [
      `./src/${name}.tsx`,
      isProd
        ? null
        : 'webpack-plugin-serve/client'
    ].filter((entry) => entry),
    mode: ENV,
    output: {
      chunkFilename: `[name].[chunkhash:8].js`,
      filename: `[name].[hash:8].js`,
      globalObject: `(typeof self !== 'undefined' ? self : this)`,
      path: path.join(context, 'build')
    },
    resolve: {
      alias,
      extensions: ['.js', '.jsx', '.ts', '.tsx']
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          exclude: /(node_modules)/,
          use: [
            isProd
              ? MiniCssExtractPlugin.loader
              : require.resolve('style-loader'),
            {
              loader: require.resolve('css-loader'),
              options: {
                importLoaders: 1
              }
            },
            {
              loader: require.resolve('postcss-loader'),
              options: {
                ident: 'postcss',
                plugins: () => [
                  require('precss'),
                  require('autoprefixer'),
                  require('postcss-simple-vars'),
                  require('postcss-nested'),
                  require('postcss-import'),
                  require('postcss-clean')(),
                  require('postcss-flexbugs-fixes')
                ]
              }
            }
          ]
        },
        {
          test: /\.css$/,
          include: /node_modules/,
          use: [
            isProd
              ? MiniCssExtractPlugin.loader
              : require.resolve('style-loader'),
            require.resolve('css-loader')
          ]
        },
        {
          test: /\.(js|ts|tsx)$/,
          exclude: /(node_modules)/,
          use: [
            require.resolve('thread-loader'),
            {
              loader: require.resolve('babel-loader'),
              options: require('@polkadot/dev-react/config/babel')
            }
          ]
        },
        {
          test: /\.md$/,
          use: [
            require.resolve('html-loader'),
            require.resolve('markdown-loader')
          ]
        },
        {
          test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
          use: [
            {
              loader: require.resolve('url-loader'),
              options: {
                limit: 10000,
                name: 'static/[name].[hash:8].[ext]'
              }
            }
          ]
        },
        {
          test: [/\.eot$/, /\.ttf$/, /\.svg$/, /\.woff$/, /\.woff2$/],
          use: [
            {
              loader: require.resolve('file-loader'),
              options: {
                name: 'static/[name].[hash:8].[ext]'
              }
            }
          ]
        }
      ]
    },
    node: {
      child_process: 'empty',
      dgram: 'empty',
      fs: 'empty',
      net: 'empty',
      tls: 'empty'
    },
    optimization: {
      runtimeChunk: 'single',
      splitChunks: {
        cacheGroups: {
          vendorOther: {
            chunks: 'initial',
            enforce: true,
            name: 'vendor',
            test: /node_modules\/(asn1|bn\.js|buffer|cuint|elliptic|lodash|moment|readable-stream|rxjs)/
          },
          vendorReact: {
            chunks: 'initial',
            enforce: true,
            name: 'react',
            test: /node_modules\/(chart|i18next|react|semantic-ui)/
          },
          polkadotJs: {
            chunks: 'initial',
            enforce: true,
            name: 'polkadotjs',
            test: /node_modules\/(@polkadot\/wasm-(crypto|dalek-ed25519|schnorrkel))/
          }
        }
      }
    },
    performance: {
      hints: false
    },
    plugins: plugins.concat([
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(ENV),
          VERSION: JSON.stringify(pkgJson.version),
          WS_URL: JSON.stringify(process.env.WS_URL)
        }
      }),
      new HtmlWebpackPlugin({
        inject: true,
        template: path.join(context, `${hasPublic ? 'public/' : ''}${name}.html`),
        PAGE_TITLE: 'Polkadot/Substrate Portal'
      }),
      new webpack.optimize.SplitChunksPlugin(),
      new MiniCssExtractPlugin({
        filename: `[name].[contenthash:8].css`
      }),
      isProd
        ? null
        : new WebpackPluginServe({
          port: 3000,
          static: path.join(process.cwd(), '/build')
        })
    ]).filter((plugin) => plugin),
    watch: !isProd
  };
}
545350
function Package(name)
    {
        var dotBowerJson = Package._readBowerJson(name) || {};
        var overrides = globalOverrides[name] || {};

        this.name         = name;
        this.installed    = !! dotBowerJson.name;
        this.main         = overrides.main || dotBowerJson.main || [];
        this.dependencies = overrides.dependencies || dotBowerJson.dependencies || [];
    }
810989
def install(args, console, env, ciprcfg, opts):
    
    if len(args) == 0:
        # Is this a cipr project?
        if ciprcfg.exists:
            # Install all the packages for this project
            console.quiet('Installing current project packages...')
            for name, source in ciprcfg.packages.items():
                if opts.upgrade:
                    app.command.run(['install', '--upgrade', source])
                else:
                    app.command.run(['install', source])
        else:
            console.error('No cipr project or package found.')
        return
    else:
        for source in args:
            package, name, version, type = _package_info(source)

            if not path.exists(env.package_dir):
                os.makedirs(env.package_dir)

            package_dir = path.join(env.package_dir, name)

            if path.exists(package_dir):
                if opts.upgrade:
                    app.command.run(['uninstall', name])
                else:
                    console.quiet('Package %s already exists. Use --upgrade to force a re-install.' % name)
                    return

            console.quiet('Installing %s...' % name)


            if type == 'git':
                tmpdir = tempfile.mkdtemp(prefix='cipr')
                clom.git.clone(package, tmpdir).shell.execute()

                if version:
                    cmd = AND(clom.cd(tmpdir), clom.git.checkout(version))
                    cmd.shell.execute()

                package_json = path.join(tmpdir, 'package.json')
                if path.exists(package_json):
                    # Looks like a cipr package, copy directly
                    shutil.move(tmpdir, package_dir)
                else:
                    # Not a cipr package, sandbox in sub-directory
                    shutil.move(tmpdir, path.join(package_dir, name))

                console.quiet('`%s` installed from git repo to `%s`' % (name, package_dir))

            elif path.exists(package):
                # Local
                os.symlink(package, package_dir)
            else:
                console.error('Package `%s` type not recognized' % package)
                return

            pkg = Package(package_dir, source)
            ciprcfg.add_package(pkg)

            if pkg.dependencies:
                console.quiet('Installing dependancies...')
                for name, require in pkg.dependencies.items():
                    if opts.upgrade:
                        app.command.run(['install', '--upgrade', require])
                    else:
                        app.command.run(['install', require])
976676
def _install(self, args):
        '''
        
        '''
        if len(args) < 2:
            raise SPMInvocationError('A package must be specified')

        caller_opts = self.opts.copy()
        caller_opts['file_client'] = 'local'
        self.caller = salt.client.Caller(mopts=caller_opts)
        self.client = salt.client.get_local_client(self.opts['conf_file'])
        cache = salt.cache.Cache(self.opts)

        packages = args[1:]
        file_map = {}
        optional = []
        recommended = []
        to_install = []
        for pkg in packages:
            if pkg.endswith('.spm'):
                if self._pkgfiles_fun('path_exists', pkg):
                    comps = pkg.split('-')
                    comps = os.path.split('-'.join(comps[:-2]))
                    pkg_name = comps[-1]

                    formula_tar = tarfile.open(pkg, 'r:bz2')
                    formula_ref = formula_tar.extractfile('{0}/FORMULA'.format(pkg_name))
                    formula_def = salt.utils.yaml.safe_load(formula_ref)

                    file_map[pkg_name] = pkg
                    to_, op_, re_ = self._check_all_deps(
                        pkg_name=pkg_name,
                        pkg_file=pkg,
                        formula_def=formula_def
                    )
                    to_install.extend(to_)
                    optional.extend(op_)
                    recommended.extend(re_)
                    formula_tar.close()
                else:
                    raise SPMInvocationError('Package file {0} not found'.format(pkg))
            else:
                to_, op_, re_ = self._check_all_deps(pkg_name=pkg)
                to_install.extend(to_)
                optional.extend(op_)
                recommended.extend(re_)

        optional = set(filter(len, optional))
        if optional:
            self.ui.status('The following dependencies are optional:\n\t{0}\n'.format(
                '\n\t'.join(optional)
            ))
        recommended = set(filter(len, recommended))
        if recommended:
            self.ui.status('The following dependencies are recommended:\n\t{0}\n'.format(
                '\n\t'.join(recommended)
            ))

        to_install = set(filter(len, to_install))
        msg = 'Installing packages:\n\t{0}\n'.format('\n\t'.join(to_install))
        if not self.opts['assume_yes']:
            self.ui.confirm(msg)

        repo_metadata = self._get_repo_metadata()

        dl_list = {}
        for package in to_install:
            if package in file_map:
                self._install_indv_pkg(package, file_map[package])
            else:
                for repo in repo_metadata:
                    repo_info = repo_metadata[repo]
                    if package in repo_info['packages']:
                        dl_package = False
                        repo_ver = repo_info['packages'][package]['info']['version']
                        repo_rel = repo_info['packages'][package]['info']['release']
                        repo_url = repo_info['info']['url']
                        if package in dl_list:
                            # Check package version, replace if newer version
                            if repo_ver == dl_list[package]['version']:
                                # Version is the same, check release
                                if repo_rel > dl_list[package]['release']:
                                    dl_package = True
                                elif repo_rel == dl_list[package]['release']:
                                    # Version and release are the same, give
                                    # preference to local (file://) repos
                                    if dl_list[package]['source'].startswith('file://'):
                                        if not repo_url.startswith('file://'):
                                            dl_package = True
                            elif repo_ver > dl_list[package]['version']:
                                dl_package = True
                        else:
                            dl_package = True

                        if dl_package is True:
                            # Put together download directory
                            cache_path = os.path.join(
                                self.opts['spm_cache_dir'],
                                repo
                            )

                            # Put together download paths
                            dl_url = '{0}/{1}'.format(
                                repo_info['info']['url'],
                                repo_info['packages'][package]['filename']
                            )
                            out_file = os.path.join(
                                cache_path,
                                repo_info['packages'][package]['filename']
                            )
                            dl_list[package] = {
                                'version': repo_ver,
                                'release': repo_rel,
                                'source': dl_url,
                                'dest_dir': cache_path,
                                'dest_file': out_file,
                            }

        for package in dl_list:
            dl_url = dl_list[package]['source']
            cache_path = dl_list[package]['dest_dir']
            out_file = dl_list[package]['dest_file']

            # Make sure download directory exists
            if not os.path.exists(cache_path):
                os.makedirs(cache_path)

            # Download the package
            if dl_url.startswith('file://'):
                dl_url = dl_url.replace('file://', '')
                shutil.copyfile(dl_url, out_file)
            else:
                with salt.utils.files.fopen(out_file, 'w') as outf:
                    outf.write(self._query_http(dl_url, repo_info['info']))

        # First we download everything, then we install
        for package in dl_list:
            out_file = dl_list[package]['dest_file']
            # Kick off the install
            self._install_indv_pkg(package, out_file)
        return
727499
async function _expectPackageVersion(args) {
  const packageVersion = require(
    path.resolve(__dirname, '../../package.json')
  ).version;
  await _expectSuccessMessage(args, `${packageVersion}\n`);
}
926670
function installPackage(zipFileLocation, callback) {
        var formData = {
            'file': fs.createReadStream(zipFileLocation),
            'force': 'true',
            'install': 'true',
        };

        var postUri = uri()
            .scheme(options.deployScheme)
            .host(options.deployHost)
            .port(options.deployPort)
            .path('/crx/packmgr/service.jsp');

        gutil.log(PLUGIN_NAME, 'Installing CRX package to ' + postUri.toString());

        request.post({
            url: postUri.toString(),
            formData: formData,
            headers: {
                'Authorization': 'Basic ' +
                    new Buffer(options.deployUsername + ':' +
                           options.deployPassword).toString('base64')
            }
        }, callback);
    }
592885
function createPackage(next) {
    var pkg = JSON.parse(fs.readFileSync(path.join(scaffold, 'package.json'), 'utf8'));

    pkg.dependencies.flatiron = flatiron.version;

    flatiron.common.mixin(pkg, info);

    app.log.info('Writing ' + 'package.json'.grey);
    fs.writeFile(path.join(root, 'package.json'), JSON.stringify(pkg, null, 2) + '\n', next);
  }
1335698
function(o) {
        this.__base(o);
        this.root = o.root;
        this.target = o.target;
        this.npmPackages = o.npmPackages === undefined? ['package.json']: o.npmPackages;
    }