Programmatic API for the bits behind npm pack
npx @tessl/cli install tessl/npm-libnpmpack@9.0.00
# libnpmpack
1
2
libnpmpack is a Node.js library for programmatically packing tarballs from local directories or from registry/GitHub specifications. It serves as the programmatic API behind the `npm pack` command, enabling developers to generate compressed .tgz archives without using the command-line interface.
3
4
## Package Information
5
6
- **Package Name**: libnpmpack
7
- **Package Type**: npm
8
- **Language**: JavaScript (Node.js)
9
- **Installation**: `npm install libnpmpack`
10
11
## Core Imports
12
13
```javascript
14
const pack = require('libnpmpack');
15
```
16
17
## Basic Usage
18
19
```javascript
20
const pack = require('libnpmpack');
21
22
// Pack from current directory
23
const tarball = await pack();
24
25
// Pack from a local directory
26
const localTar = await pack('/path/to/my-package');
27
28
// Pack from a registry spec
29
const registryTar = await pack('abbrev@1.0.3');
30
31
// Pack from a GitHub spec
32
const githubTar = await pack('isaacs/rimraf#PR-192');
33
34
// Pack with options - write to disk (must provide packDestination)
35
const tarball = await pack('file:.', {
36
dryRun: false,
37
packDestination: '/tmp',
38
silent: true
39
});
40
```
41
42
## Architecture
43
44
libnpmpack is built around several key components:
45
46
- **Specification Parsing**: Uses `npm-package-arg` to parse various package specifications (local, registry, GitHub)
47
- **Manifest Resolution**: Integrates with `pacote` to resolve package manifests and fetch package data
48
- **Lifecycle Scripts**: Executes prepack/postpack scripts using `@npmcli/run-script` for local directory packing
49
- **Dependency Management**: Uses `@npmcli/arborist` for dependency tree analysis
50
- **File System Operations**: Handles tarball writing with configurable destination paths
51
52
## Capabilities
53
54
### Package Packing
55
56
Creates npm package tarballs from various sources including local directories, registry specifications, and GitHub repositories.
57
58
```javascript { .api }
59
/**
60
* Packs a tarball from a local directory or from a registry or github spec
61
* @param {string} [spec='file:.'] - Package specification to pack
62
* @param {PackOptions} [opts={}] - Options for packing
63
* @returns {Promise<Buffer>} - Promise that resolves to tarball data Buffer with attached metadata
64
*/
65
async function pack(spec = 'file:.', opts = {});
66
```
67
68
## Types
69
70
```javascript { .api }
71
interface PackOptions {
72
/** If explicitly false, writes tarball to disk (default: undefined, no writing) */
73
dryRun?: boolean;
74
75
/** Directory path where to write the tarball file (required when dryRun is false) */
76
packDestination?: string;
77
78
/** If true, skips prepack/postpack lifecycle scripts (default: false) */
79
ignoreScripts?: boolean;
80
81
/** If true, runs scripts with inherit stdio instead of pipe (default: false) */
82
foregroundScripts?: boolean;
83
84
/** Suppresses output (default: false) */
85
silent?: boolean;
86
87
/** Additional pacote options (registry, cache, etc.) */
88
[key: string]: any;
89
}
90
91
interface TarballBuffer extends Buffer {
92
/** Source specification that was packed */
93
from: string;
94
95
/** Resolved package identifier */
96
resolved: string;
97
98
/** Integrity hash of the tarball */
99
integrity: string;
100
}
101
```
102
103
## Detailed API
104
105
### pack(spec, opts)
106
107
#### Parameters
108
109
**spec** (string, optional)
110
- Default: `'file:.'`
111
- Package specification to pack
112
- Supported formats:
113
- Local directory: `'file:.'` (current directory) or `'/path/to/directory'`
114
- Registry spec: `'package-name@version'` or `'package-name'`
115
- GitHub spec: `'user/repo#branch-or-tag'`
116
117
**opts** (object, optional)
118
- Default: `{}`
119
- Configuration options object
120
121
#### Key Options
122
123
**dryRun** (boolean)
124
- Default: `undefined` (no file writing)
125
- Set to `false` to write tarball to disk
126
- When explicitly `false`, creates file named `${name}-${version}.tgz`
127
128
**packDestination** (string)
129
- Default: `undefined`
130
- Directory path where tarball file should be written
131
- Required when `dryRun: false` (will throw error if undefined)
132
133
**ignoreScripts** (boolean)
134
- Default: `false`
135
- Set to `true` to skip prepack/postpack lifecycle scripts
136
- Only applies to local directory packing
137
138
**foregroundScripts** (boolean)
139
- Default: `false`
140
- Set to `true` to run scripts with inherit stdio instead of pipe
141
- Allows script output to be visible in console
142
143
**silent** (boolean)
144
- Default: `false`
145
- Suppresses output during packing process
146
147
#### Return Value
148
149
Returns a Promise that resolves to a Buffer containing the tarball data. The Buffer has additional properties:
150
151
- `from`: Source specification that was packed
152
- `resolved`: Resolved package identifier
153
- `integrity`: Integrity hash of the tarball
154
155
#### Lifecycle Script Behavior
156
157
For local directory packing (when `spec.type === 'directory'` and `!opts.ignoreScripts`):
158
159
1. **prepack**: Executed before tarball creation
160
- Runs with stdio mode based on `opts.foregroundScripts`
161
- Uses package manifest from the directory
162
163
2. **postpack**: Executed after tarball creation
164
- Runs with stdio mode based on `opts.foregroundScripts`
165
- Receives environment variables:
166
- `npm_package_from`: tarball.from
167
- `npm_package_resolved`: tarball.resolved
168
- `npm_package_integrity`: tarball.integrity
169
170
#### File Writing Behavior
171
172
- By default, tarball is NOT written to disk (unless `opts.dryRun === false`)
173
- To write to disk, explicitly set `opts.dryRun = false` and provide `packDestination`
174
- Filename format: `${manifest.name}-${manifest.version}.tgz`
175
- Scoped package names are normalized:
176
- Remove leading `@`
177
- Replace `/` with `-`
178
- Example: `@angular/core` → `angular-core-1.0.0.tgz`
179
- Destination: `path.resolve(opts.packDestination, filename)`
180
- **Important**: `packDestination` is required when `dryRun: false` - will throw TypeError if undefined
181
182
#### Error Handling
183
184
The function may throw errors in the following cases:
185
- Invalid package specifications
186
- Network errors when accessing registry or GitHub
187
- TypeError when `dryRun: false` but `packDestination` is undefined
188
- File system errors during tarball writing
189
- Script execution errors (unless `ignoreScripts: true`)
190
- Permission errors when writing to destination directory
191
192
#### Usage Examples
193
194
```javascript
195
const pack = require('libnpmpack');
196
197
// Pack current directory (no file written)
198
const tarball = await pack();
199
console.log(`Packed ${tarball.from}, size: ${tarball.length} bytes`);
200
201
// Pack and write to disk (packDestination is required)
202
const tarball = await pack('file:.', {
203
dryRun: false,
204
packDestination: './dist'
205
});
206
207
// Pack from registry with custom registry
208
const registryTar = await pack('lodash@4.17.21', {
209
registry: 'https://registry.npmjs.org/'
210
});
211
212
// Pack from GitHub
213
const githubTar = await pack('lodash/lodash#4.17.21');
214
215
// Pack with script handling
216
const tarball = await pack('/path/to/my-package', {
217
dryRun: false,
218
foregroundScripts: true, // Show script output
219
packDestination: './builds'
220
});
221
222
// Pack without running lifecycle scripts
223
const tarball = await pack('file:.', {
224
ignoreScripts: true,
225
silent: true
226
});
227
```