0
# Core API Functions
1
2
Core package operations for fetching, extracting, and resolving packages from any source that npm supports. These functions work with any package specifier that npm can install - registry packages, git repositories, local files, directories, and remote tarballs.
3
4
## Capabilities
5
6
### Resolve Function
7
8
Resolves a package specifier to a tarball URL, file path, or git repository with commit hash.
9
10
```javascript { .api }
11
/**
12
* Resolve a package specifier to a concrete location
13
* @param {string} spec - Package specifier (name@version, git URL, file path, etc.)
14
* @param {Object} opts - Configuration options
15
* @returns {Promise<string>} Resolved tarball URL, file path, or git repo URL
16
*/
17
function resolve(spec, opts);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const pacote = require('pacote');
24
25
// Resolve registry package
26
const url = await pacote.resolve('lodash@4.17.21');
27
// Returns: 'https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz'
28
29
// Resolve git repository
30
const gitUrl = await pacote.resolve('github:facebook/react#v18.0.0');
31
// Returns: 'git+ssh://git@github.com/facebook/react.git#v18.0.0'
32
33
// Resolve with options
34
const resolved = await pacote.resolve('express@latest', {
35
registry: 'https://registry.npmjs.org'
36
});
37
```
38
39
### Extract Function
40
41
Extracts a package's tarball into a destination folder with proper file permissions.
42
43
```javascript { .api }
44
/**
45
* Extract a package to a destination directory
46
* @param {string} spec - Package specifier
47
* @param {string} dest - Destination directory path
48
* @param {Object} opts - Configuration options
49
* @returns {Promise<ExtractionResult>} Extraction metadata
50
*/
51
function extract(spec, dest, opts);
52
53
interface ExtractionResult {
54
from: string; // Original package specifier
55
resolved: string; // Resolved package URL
56
integrity: string; // Package integrity hash
57
}
58
```
59
60
**Usage Examples:**
61
62
```javascript
63
const pacote = require('pacote');
64
const path = require('path');
65
66
// Extract package to directory
67
const result = await pacote.extract('react@18.0.0', './node_modules/react');
68
console.log('Extracted:', result.from);
69
console.log('From URL:', result.resolved);
70
console.log('Integrity:', result.integrity);
71
72
// Extract with custom options
73
await pacote.extract('lodash@latest', './packages/lodash', {
74
cache: './custom-cache',
75
umask: 0o022
76
});
77
78
// Extract git repository
79
await pacote.extract('github:npm/cli', './packages/npm-cli', {
80
before: '2023-01-01T00:00:00.000Z'
81
});
82
```
83
84
### Manifest Function
85
86
Fetches (or simulates) a package's manifest - essentially the package.json file plus additional metadata.
87
88
```javascript { .api }
89
/**
90
* Fetch a package manifest
91
* @param {string} spec - Package specifier
92
* @param {Object} opts - Configuration options
93
* @returns {Promise<PackageManifest>} Package manifest with metadata
94
*/
95
function manifest(spec, opts);
96
97
interface PackageManifest {
98
name: string;
99
version: string;
100
description?: string;
101
main?: string;
102
dependencies?: { [name: string]: string };
103
devDependencies?: { [name: string]: string };
104
scripts?: { [name: string]: string };
105
_resolved: string; // Tarball URL or file path
106
_from: string; // Normalized spec
107
_integrity: string; // Integrity hash
108
_id: string; // Canonical spec (name@version)
109
// ... plus all other standard package.json fields
110
}
111
```
112
113
**Usage Examples:**
114
115
```javascript
116
const pacote = require('pacote');
117
118
// Get manifest for latest version
119
const manifest = await pacote.manifest('express@latest');
120
console.log('Name:', manifest.name);
121
console.log('Version:', manifest.version);
122
console.log('Dependencies:', manifest.dependencies);
123
124
// Get manifest with full metadata
125
const fullManifest = await pacote.manifest('lodash@4.17.21', {
126
fullMetadata: true,
127
fullReadJson: true
128
});
129
130
// Get manifest for git repository
131
const gitManifest = await pacote.manifest('github:facebook/react#main');
132
console.log('Git package:', gitManifest.name);
133
```
134
135
### Packument Function
136
137
Fetches (or simulates) a package's packument - the top-level package document listing all available versions and metadata.
138
139
```javascript { .api }
140
/**
141
* Fetch a package packument (full package document)
142
* @param {string} spec - Package specifier
143
* @param {Object} opts - Configuration options
144
* @returns {Promise<Packument>} Full package document
145
*/
146
function packument(spec, opts);
147
148
interface Packument {
149
name: string;
150
versions: { [version: string]: PackageManifest };
151
'dist-tags': { [tag: string]: string };
152
time?: { [version: string]: string };
153
_contentLength: number;
154
// ... additional registry metadata
155
}
156
```
157
158
**Usage Examples:**
159
160
```javascript
161
const pacote = require('pacote');
162
163
// Get packument for registry package
164
const packument = await pacote.packument('express');
165
console.log('Available versions:', Object.keys(packument.versions));
166
console.log('Latest version:', packument['dist-tags'].latest);
167
console.log('Beta version:', packument['dist-tags'].beta);
168
169
// Get packument with full metadata
170
const fullPackument = await pacote.packument('lodash', {
171
fullMetadata: true
172
});
173
174
// Use packument cache to avoid duplicate requests
175
const cache = new Map();
176
const pack1 = await pacote.packument('react', { packumentCache: cache });
177
const pack2 = await pacote.packument('react', { packumentCache: cache }); // Uses cache
178
```
179
180
### Tarball Functions
181
182
Get package tarball data as a buffer, stream it through a handler, or save it to a file.
183
184
```javascript { .api }
185
/**
186
* Get package tarball data as a buffer
187
* @param {string} spec - Package specifier
188
* @param {Object} opts - Configuration options
189
* @returns {Promise<TarballResult>} Tarball buffer with metadata
190
*/
191
function tarball(spec, opts);
192
193
/**
194
* Stream tarball through a handler function
195
* @param {string} spec - Package specifier
196
* @param {Function} handler - Stream handler function
197
* @param {Object} opts - Configuration options
198
* @returns {Promise<void>} Promise resolving when handler completes
199
*/
200
function tarball.stream(spec, handler, opts);
201
202
/**
203
* Save tarball to a file
204
* @param {string} spec - Package specifier
205
* @param {string} dest - Destination file path
206
* @param {Object} opts - Configuration options
207
* @returns {Promise<TarballResult>} Tarball metadata
208
*/
209
function tarball.file(spec, dest, opts);
210
211
interface TarballResult extends Buffer {
212
from: string; // Original package specifier
213
resolved: string; // Resolved package URL
214
integrity: string; // Package integrity hash
215
}
216
```
217
218
**Usage Examples:**
219
220
```javascript
221
const pacote = require('pacote');
222
const fs = require('fs');
223
224
// Get tarball as buffer
225
const tarballData = await pacote.tarball('express@4.18.0');
226
console.log('Tarball size:', tarballData.length, 'bytes');
227
console.log('From:', tarballData.from);
228
console.log('Integrity:', tarballData.integrity);
229
230
// Stream tarball data
231
await pacote.tarball.stream('lodash@latest', async (stream) => {
232
const writeStream = fs.createWriteStream('./lodash.tgz');
233
stream.pipe(writeStream);
234
235
return new Promise((resolve, reject) => {
236
writeStream.on('finish', resolve);
237
writeStream.on('error', reject);
238
});
239
});
240
241
// Save tarball to file
242
const result = await pacote.tarball.file('react@18.0.0', './react-18.0.0.tgz');
243
console.log('Saved tarball with integrity:', result.integrity);
244
245
// Download git repository as tarball
246
await pacote.tarball.file('github:npm/cli#latest', './npm-cli.tgz', {
247
cache: './git-cache'
248
});
249
```
250
251
## Error Handling
252
253
All core functions can throw various errors that should be handled appropriately:
254
255
```javascript
256
const pacote = require('pacote');
257
258
try {
259
const manifest = await pacote.manifest('nonexistent-package@1.0.0');
260
} catch (error) {
261
if (error.code === 'E404') {
262
console.log('Package not found');
263
} else if (error.code === 'EINTEGRITY') {
264
console.log('Integrity verification failed');
265
} else if (error.code === 'ENOTFOUND') {
266
console.log('Network error or registry unavailable');
267
} else if (error.code === 'EMISSINGSIGNATUREKEY') {
268
console.log('Missing signature verification key');
269
} else if (error.code === 'EEXPIREDSIGNATUREKEY') {
270
console.log('Signature verification key expired');
271
} else if (error.code === 'EINTEGRITYSIGNATURE') {
272
console.log('Invalid registry signature');
273
} else if (error.code === 'EATTESTATIONSUBJECT') {
274
console.log('Attestation subject mismatch');
275
} else if (error.code === 'EATTESTATIONVERIFY') {
276
console.log('Attestation verification failed');
277
} else {
278
console.log('Unexpected error:', error.message);
279
}
280
}
281
```
282
283
Common error codes:
284
- `E404`: Package or version not found
285
- `EINTEGRITY`: Integrity verification failed
286
- `ENOTFOUND`: Network error or DNS resolution failed
287
- `ETIMEDOUT`: Request timeout
288
- `EACCES`: Permission denied (file system operations)
289
- `ENOENT`: File or directory not found (local operations)
290
- `EMISSINGSIGNATUREKEY`: Missing signature keys for verification
291
- `EEXPIREDSIGNATUREKEY`: Expired signature keys
292
- `EINTEGRITYSIGNATURE`: Invalid registry signatures
293
- `EATTESTATIONSUBJECT`: Attestation subject mismatch
294
- `EATTESTATIONVERIFY`: Attestation verification failure
295
296
### Advanced Error Handling
297
298
```javascript
299
const pacote = require('pacote');
300
301
// Handle retriable vs non-retriable errors
302
try {
303
const result = await pacote.extract('package@1.0.0', './dest');
304
} catch (error) {
305
const fetcher = pacote.FetcherBase.get('package@1.0.0', {});
306
307
if (fetcher.isRetriableError(error)) {
308
console.log('Error can be retried:', error.message);
309
// Implement retry logic
310
} else if (fetcher.isDataCorruptionError(error)) {
311
console.log('Data corruption detected:', error.message);
312
// Clear cache and retry
313
await fetcher.cleanupCached();
314
} else {
315
console.log('Permanent error:', error.message);
316
throw error;
317
}
318
}
319
320
// Security-related error handling
321
try {
322
await pacote.manifest('package@1.0.0', {
323
verifySignatures: true,
324
verifyAttestations: true
325
});
326
} catch (error) {
327
if (error.code.startsWith('ESIGNATURE') || error.code.startsWith('EATTESTATION')) {
328
console.log('Security verification failed - package may be compromised');
329
// Handle security failure appropriately
330
}
331
}
332
```