• Stars
    star
    349
  • Rank 121,528 (Top 3 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 5 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

npm fetcher

pacote

Fetches package manifests and tarballs from the npm registry.

USAGE

const pacote = require('pacote')

// get a package manifest
pacote.manifest('[email protected]').then(manifest => console.log('got it', manifest))

// extract a package into a folder
pacote.extract('github:npm/cli', 'some/path', options)
  .then(({from, resolved, integrity}) => {
    console.log('extracted!', from, resolved, integrity)
  })

pacote.tarball('https://server.com/package.tgz').then(data => {
  console.log('got ' + data.length + ' bytes of tarball data')
})

pacote works with any kind of package specifier that npm can install. If you can pass it to the npm CLI, you can pass it to pacote. (In fact, that's exactly what the npm CLI does.)

Anything that you can do with one kind of package, you can do with another.

Data that isn't relevant (like a packument for a tarball) will be simulated.

prepare scripts will be run when generating tarballs from git and directory locations, to simulate what would be published to the registry, so that you get a working package instead of just raw source code that might need to be transpiled.

CLI

This module exports a command line interface that can do most of what is described below. Run pacote -h to learn more.

Pacote - The JavaScript Package Handler, v10.1.1

Usage:

  pacote resolve <spec>
    Resolve a specifier and output the fully resolved target
    Returns integrity and from if '--long' flag is set.

  pacote manifest <spec>
    Fetch a manifest and print to stdout

  pacote packument <spec>
    Fetch a full packument and print to stdout

  pacote tarball <spec> [<filename>]
    Fetch a package tarball and save to <filename>
    If <filename> is missing or '-', the tarball will be streamed to stdout.

  pacote extract <spec> <folder>
    Extract a package to the destination folder.

Configuration values all match the names of configs passed to npm, or
options passed to Pacote.  Additional flags for this executable:

  --long     Print an object from 'resolve', including integrity and spec.
  --json     Print result objects as JSON rather than node's default.
             (This is the default if stdout is not a TTY.)
  --help -h  Print this helpful text.

For example '--cache=/path/to/folder' will use that folder as the cache.

API

The spec refers to any kind of package specifier that npm can install. If you can pass it to the npm CLI, you can pass it to pacote. (In fact, that's exactly what the npm CLI does.)

See below for valid opts values.

  • pacote.resolve(spec, opts) Resolve a specifier like foo@latest or github:user/project all the way to a tarball url, tarball file, or git repo with commit hash.

  • pacote.extract(spec, dest, opts) Extract a package's tarball into a destination folder. Returns a promise that resolves to the {from,resolved,integrity} of the extracted package.

  • pacote.manifest(spec, opts) Fetch (or simulate) a package's manifest (basically, the package.json file, plus a bit of metadata). See below for more on manifests and packuments. Returns a Promise that resolves to the manifest object.

  • pacote.packument(spec, opts) Fetch (or simulate) a package's packument (basically, the top-level package document listing all the manifests that the registry returns). See below for more on manifests and packuments. Returns a Promise that resolves to the packument object.

  • pacote.tarball(spec, opts) Get a package tarball data as a buffer in memory. Returns a Promise that resolves to the tarball data Buffer, with from, resolved, and integrity fields attached.

  • pacote.tarball.file(spec, dest, opts) Save a package tarball data to a file on disk. Returns a Promise that resolves to {from,integrity,resolved} of the fetched tarball.

  • pacote.tarball.stream(spec, streamHandler, opts) Fetch a tarball and make the stream available to the streamHandler function.

    This is mostly an internal function, but it is exposed because it does provide some functionality that may be difficult to achieve otherwise.

    The streamHandler function MUST return a Promise that resolves when the stream (and all associated work) is ended, or rejects if the stream has an error.

    The streamHandler function MAY be called multiple times, as Pacote retries requests in some scenarios, such as cache corruption or retriable network failures.

Options

Options are passed to npm-registry-fetch and cacache, so in addition to these, anything for those modules can be given to pacote as well.

Options object is cloned, and mutated along the way to add integrity, resolved, and other properties, as they are determined.

  • cache Where to store cache entries and temp files. Passed to cacache. Defaults to the same cache directory that npm will use by default, based on platform and environment.
  • where Base folder for resolving relative file: dependencies.
  • resolved Shortcut for looking up resolved values. Should be specified if known.
  • integrity Expected integrity of fetched package tarball. If specified, tarballs with mismatched integrity values will raise an EINTEGRITY error.
  • umask Permission mode mask for extracted files and directories. Defaults to 0o22. See "Extracted File Modes" below.
  • fmode Minimum permission mode for extracted files. Defaults to 0o666. See "Extracted File Modes" below.
  • dmode Minimum permission mode for extracted directories. Defaults to 0o777. See "Extracted File Modes" below.
  • preferOnline Prefer to revalidate cache entries, even when it would not be strictly necessary. Default false.
  • before When picking a manifest from a packument, only consider packages published before the specified date. Default null.
  • defaultTag The default dist-tag to use when choosing a manifest from a packument. Defaults to latest.
  • registry The npm registry to use by default. Defaults to https://registry.npmjs.org/.
  • fullMetadata Fetch the full metadata from the registry for packuments, including information not strictly required for installation (author, description, etc.) Defaults to true when before is set, since the version publish time is part of the extended packument metadata.
  • fullReadJson Use the slower read-package-json package insted of read-package-json-fast in order to include extra fields like "readme" in the manifest. Defaults to false.
  • packumentCache For registry packuments only, you may provide a Map object which will be used to cache packument requests between pacote calls. This allows you to easily avoid hitting the registry multiple times (even just to validate the cache) for a given packument, since it is unlikely to change in the span of a single command.
  • silent A boolean that determines whether the banner is displayed when calling @npmcli/run-script.
  • verifySignatures A boolean that will make pacote verify the integrity signature of a manifest, if present. There must be a configured _keys entry in the config that is scoped to the registry the manifest is being fetched from.
  • verifyAttestations A boolean that will make pacote verify Sigstore attestations, if present. There must be a configured _keys entry in the config that is scoped to the registry the manifest is being fetched from.
  • tufCache Where to store metadata/target files when retrieving the package attestation key material via TUF. Defaults to the same cache directory that npm will use by default, based on platform and environment.

Advanced API

Each different type of fetcher is exposed for more advanced usage such as using helper methods from this classes:

  • DirFetcher
  • FileFetcher
  • GitFetcher
  • RegistryFetcher
  • RemoteFetcher

Extracted File Modes

Files are extracted with a mode matching the following formula:

( (tarball entry mode value) | (minimum mode option) ) ~ (umask)

This is in order to prevent unreadable files or unlistable directories from cluttering a project's node_modules folder, even if the package tarball specifies that the file should be inaccessible.

It also prevents files from being group- or world-writable without explicit opt-in by the user, because all file and directory modes are masked against the umask value.

So, a file which is 0o771 in the tarball, using the default fmode of 0o666 and umask of 0o22, will result in a file mode of 0o755:

(0o771 | 0o666) => 0o777
(0o777 ~ 0o22) => 0o755

In almost every case, the defaults are appropriate. To respect exactly what is in the package tarball (even if this makes an unusable system), set both dmode and fmode options to 0. Otherwise, the umask config should be used in most cases where file mode modifications are required, and this functions more or less the same as the umask value in most Unix systems.

Extracted File Ownership

When running as root on Unix systems, all extracted files and folders will have their owning uid and gid values set to match the ownership of the containing folder.

This prevents root-owned files showing up in a project's node_modules folder when a user runs sudo npm install.

Manifests

A manifest is similar to a package.json file. However, it has a few pieces of extra metadata, and sometimes lacks metadata that is inessential to package installation.

In addition to the common package.json fields, manifests include:

  • manifest._resolved The tarball url or file path where the package artifact can be found.

  • manifest._from A normalized form of the spec passed in as an argument.

  • manifest._integrity The integrity value for the package artifact.

  • manifest._id The canonical spec of this package version: name@version.

  • manifest.dist Registry manifests (those included in a packument) have a dist object. Only tarball is required, though at least one of shasum or integrity is almost always present.

    • tarball The url to the associated package artifact. (Copied by Pacote to manifest._resolved.)
    • integrity The integrity SRI string for the artifact. This may not be present for older packages on the npm registry. (Copied by Pacote to manifest._integrity.)
    • shasum Legacy integrity value. Hexadecimal-encoded sha1 hash. (Converted to an SRI string and copied by Pacote to manifest._integrity when dist.integrity is not present.)
    • fileCount Number of files in the tarball.
    • unpackedSize Size on disk of the package when unpacked.
    • signatures Signatures of the shasum. Includes the keyid that correlates to a key from the npm registry

Packuments

A packument is the top-level package document that lists the set of manifests for available versions for a package.

When a packument is fetched with accept: application/vnd.npm.install-v1+json in the HTTP headers, only the most minimum necessary metadata is returned. Additional metadata is returned when fetched with only accept: application/json.

For Pacote's purposes, the following fields are relevant:

  • versions An object where each key is a version, and each value is the manifest for that version.
  • dist-tags An object mapping dist-tags to version numbers. This is how foo@latest gets turned into [email protected].
  • time In the full packument, an object mapping version numbers to publication times, for the opts.before functionality.

Pacote adds the following field, regardless of the accept header:

  • _contentLength The size of the packument.

More Repositories

1

npm

This repository is moving to: https://github.com/npm/cli
17,473
star
2

cli

the package manager for JavaScript
JavaScript
8,303
star
3

node-semver

The semver parser for node (the one npm uses)
JavaScript
4,772
star
4

npm-expansions

Send us a pull request by editing expansions.txt
JavaScript
2,209
star
5

tink

a dependency unwinder for javascript
JavaScript
2,153
star
6

ini

An ini parser/serializer in JavaScript
JavaScript
733
star
7

npx

npm package executor
JavaScript
731
star
8

rfcs

Public change requests/proposals & ideation
JavaScript
726
star
9

npm-registry-couchapp

couchapp bits of registry.npmjs.org
JavaScript
615
star
10

nopt

Node/npm Option Parsing
JavaScript
527
star
11

registry

npm registry documentation
449
star
12

npmlog

The logger that npm uses
JavaScript
423
star
13

marky-markdown

npm's markdown parser
JavaScript
405
star
14

arborist

npm's tree doctor
JavaScript
369
star
15

documentation

Documentation for the npm registry, website, and command-line interface.
MDX
369
star
16

download-counts

Background jobs and a minimal service for collecting and delivering download counts
JavaScript
328
star
17

gauge

A terminal based horizontal guage aka, a progress bar
JavaScript
319
star
18

node-which

Like which(1) unix command. Find the first instance of an executable in the PATH.
JavaScript
305
star
19

init-package-json

A node module to get your node module started
JavaScript
284
star
20

validate-npm-package-name

Is the given string an acceptable npm package name?
JavaScript
282
star
21

cacache

npm's content-addressable cache
JavaScript
274
star
22

npm-merge-driver

git merge driver for resolving conflicts in npm-related files
JavaScript
271
star
23

npm-registry-client

JavaScript
264
star
24

lockfile

A very polite lock file utility, which endeavors to not litter, and to wait patiently for others.
JavaScript
259
star
25

registry-issue-archive

An archive of the old npm registry issue tracker
250
star
26

write-file-atomic

Write files in an atomic fashion w/configurable ownership
JavaScript
217
star
27

read-package-json

The thing npm uses to read package.json files with semantics and defaults and validation and stuff
JavaScript
214
star
28

roadmap

Public roadmap for npm
213
star
29

hosted-git-info

Provides metadata and conversions from repository urls for Github, Bitbucket and Gitlab
JavaScript
206
star
30

fstream

Advanced FS Streaming for Node
JavaScript
205
star
31

make-fetch-happen

making fetch happen for npm
JavaScript
190
star
32

read

read(1) for node.
JavaScript
187
star
33

normalize-package-data

normalizes package metadata, typically found in package.json file.
JavaScript
184
star
34

ndm

ndm allows you to deploy OS-specific service-wrappers directly from npm-packages.
JavaScript
181
star
35

are-we-there-yet

Track complex hiearchies of asynchronous task completion statuses.
JavaScript
173
star
36

abbrev-js

Like ruby's Abbrev module
JavaScript
158
star
37

statusboard

Public monitor/status/health board for @npm/cli-team's maintained projects
JavaScript
152
star
38

security-holder

An npm package that holds a spot.
145
star
39

osenv

Look up environment settings specific to different operating systems.
JavaScript
137
star
40

feedback

Public feedback discussions for npm
133
star
41

npm-registry-fetch

like fetch() but for the npm registry
JavaScript
130
star
42

npm-package-arg

Parse the things that can be arguments to `npm install`
JavaScript
116
star
43

libnpm

programmatic npm API
JavaScript
113
star
44

npm-collection-staff-picks

JavaScript
112
star
45

npm-packlist

Walk through a folder and figure out what goes in an npm package
JavaScript
110
star
46

promzard

A prompting json thingie
JavaScript
101
star
47

npm-remote-ls

Examine a package's dependency graph before you install it
JavaScript
89
star
48

npmconf

npm config thing
JavaScript
75
star
49

cmd-shim

The cmd-shim used in npm
JavaScript
75
star
50

npm-tips

A collection of short (5 words or so) tips and tricks that can be sprinkled about the npm site.
JavaScript
73
star
51

www

community space for the npm website
68
star
52

policies

Privacy policy, code of conduct, license, and other npm legal stuff
Shell
67
star
53

package-json

Programmatic API to update package.json
JavaScript
65
star
54

git

a util for spawning git from npm CLI contexts
JavaScript
62
star
55

npm_conf

A conference about npm, maybe. Not to be confused with npmconf.
59
star
56

ignore-walk

Nested/recursive `.gitignore`/`.npmignore` parsing and filtering.
JavaScript
57
star
57

registry-follower-tutorial

write you a registry follower for great good
JavaScript
56
star
58

ssri

subresource integrity for npm
JavaScript
55
star
59

minipass-fetch

An implementation of window.fetch in Node.js using Minipass streams
JavaScript
54
star
60

ci-detect

Detect what kind of CI environment the program is in
JavaScript
53
star
61

run-script

Run a lifecycle script for a package (descendant of npm-lifecycle)
JavaScript
53
star
62

read-installed

Read all the installed packages in a folder, and return a tree structure with all the data.
JavaScript
52
star
63

mute-stream

Bytes go in, but they don't come out (when muted).
JavaScript
49
star
64

fs-write-stream-atomic

Like `fs.createWriteStream(...)`, but atomic.
JavaScript
48
star
65

read-package-json-fast

Like read-package-json, but faster
JavaScript
48
star
66

libnpmpublish

programmatically publish and unpublish npm packages
JavaScript
46
star
67

logical-tree

Calculates a nested logical tree using a package.json and a package lock.
JavaScript
44
star
68

read-package-tree

Read the contents of node_modules
JavaScript
42
star
69

jobs

41
star
70

unique-filename

Generate a unique filename for use in temporary directories or caches.
JavaScript
40
star
71

lock-verify

Report if your package.json is out of sync with your package-lock.json
JavaScript
38
star
72

fstream-ignore

JavaScript
37
star
73

benchmarks

The npm CLI's benchmark suite
JavaScript
36
star
74

npm-lifecycle

npm lifecycle script runner
JavaScript
36
star
75

wombat-cli

The wombat cli tool.
JavaScript
35
star
76

npme-installer

npm Enterprise installer
JavaScript
35
star
77

couch-login

A module for doing logged-in requests against a couchdb server
JavaScript
33
star
78

libnpmexec

npm exec (npx) Programmatic API
JavaScript
33
star
79

npm-audit-report

npm audit security report
JavaScript
33
star
80

ansible-nagios

Ansible role for building Nagios 4.
Perl
32
star
81

config

Configuration management for https://github.com/npm/cli
JavaScript
32
star
82

parse-conflict-json

Parse a JSON string that has git merge conflicts, resolving if possible
JavaScript
32
star
83

npm-profile

Make changes to your npmjs.com profile via cli or library
JavaScript
31
star
84

unique-slug

Generate a unique character string suitible for use in files and URLs.
JavaScript
31
star
85

fstream-npm

fstream class for creating npm packages
JavaScript
30
star
86

redsess

Yet another redis session thing for node.
JavaScript
30
star
87

concurrent-couch-follower

a couch follower wrapper that you can use to be sure you don't miss any documents even if you process them asynchronously.
JavaScript
28
star
88

npm-registry-mock

mock the npm registry
JavaScript
27
star
89

lint

lint the npmcli way
JavaScript
26
star
90

fs

filesystem helper functions, wrappers, and promisification for the npm cli
JavaScript
25
star
91

template-oss

a template package for npm CLI team development
JavaScript
25
star
92

libnpmsearch

programmatic API for the shiny new npm search endpoint
JavaScript
25
star
93

bin-links

.bin/ script linker
JavaScript
24
star
94

libnpmaccess

programmatic api for `npm access`
JavaScript
24
star
95

logos

official logos for npm, Inc
22
star
96

types

Typescript definitions for npm registry content
JavaScript
22
star
97

public-api

21
star
98

deprecate-holder

An npm package that holds a spot.
21
star
99

map-workspaces

Retrieves a name:pathname Map for a given workspaces config
JavaScript
20
star
100

libnpmversion

library to do the things that 'npm version' does
JavaScript
20
star