0
# Programmatic API
1
2
Standard Version provides a Node.js API for integrating automated versioning into build scripts, CI/CD pipelines, and custom automation workflows. The API mirrors the CLI functionality while providing programmatic access to configuration and results.
3
4
## Capabilities
5
6
### Main Function
7
8
Core function for executing the standard-version workflow programmatically.
9
10
```javascript { .api }
11
/**
12
* Execute standard-version workflow with provided configuration
13
* @param {Object} argv - Configuration options object
14
* @returns {Promise<void>} Promise that resolves when process completes
15
* @throws {Error} If version bumping, changelog generation, or git operations fail
16
*/
17
async function standardVersion(argv);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const standardVersion = require('standard-version');
24
25
// Basic usage with default configuration
26
try {
27
await standardVersion({});
28
console.log('Release completed successfully');
29
} catch (error) {
30
console.error('Release failed:', error.message);
31
process.exit(1);
32
}
33
34
// Custom configuration
35
await standardVersion({
36
releaseAs: 'minor',
37
infile: 'CHANGELOG.md',
38
silent: false,
39
dryRun: true,
40
scripts: {
41
prebump: 'npm run test',
42
postbump: 'npm run build'
43
}
44
});
45
46
// First release
47
await standardVersion({
48
firstRelease: true,
49
tagPrefix: 'v',
50
header: '# Release Notes\n\nAll notable changes documented here.\n'
51
});
52
```
53
54
### Configuration Loading
55
56
Load configuration from standard-version configuration files.
57
58
```javascript { .api }
59
/**
60
* Load configuration from .versionrc files and package.json
61
* @returns {Object} Merged configuration object from all sources
62
* @throws {Error} If configuration file contains invalid JSON or structure
63
*/
64
function getConfiguration();
65
```
66
67
**Usage Examples:**
68
69
```javascript
70
const { getConfiguration } = require('standard-version/lib/configuration');
71
72
// Load configuration from files
73
const config = getConfiguration();
74
console.log('Loaded config:', config);
75
76
// Merge with runtime options
77
const runtimeOptions = { dryRun: true, silent: false };
78
const finalConfig = { ...config, ...runtimeOptions };
79
80
await standardVersion(finalConfig);
81
```
82
83
### Default Configuration
84
85
Access default configuration values used by standard-version.
86
87
```javascript { .api }
88
/**
89
* Default configuration object with all standard-version defaults
90
*/
91
const defaults = {
92
infile: 'CHANGELOG.md',
93
firstRelease: false,
94
sign: false,
95
noVerify: false,
96
commitAll: false,
97
silent: false,
98
tagPrefix: 'v',
99
scripts: {},
100
skip: {},
101
dryRun: false,
102
gitTagFallback: true,
103
preset: 'conventional-changelog-conventionalcommits',
104
packageFiles: ['package.json', 'bower.json', 'manifest.json'],
105
bumpFiles: ['package.json', 'bower.json', 'manifest.json', 'package-lock.json', 'npm-shrinkwrap.json'],
106
header: '# Changelog\n\nAll notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.\n'
107
};
108
```
109
110
**Usage Examples:**
111
112
```javascript
113
const defaults = require('standard-version/defaults');
114
115
// Extend defaults with custom values
116
const customConfig = {
117
...defaults,
118
tagPrefix: 'release-',
119
infile: 'HISTORY.md',
120
scripts: {
121
prebump: 'npm run lint',
122
postbump: 'npm run build'
123
}
124
};
125
126
await standardVersion(customConfig);
127
128
// Override specific defaults
129
const config = {
130
...defaults,
131
packageFiles: [...defaults.packageFiles, 'VERSION'],
132
bumpFiles: [...defaults.bumpFiles, 'VERSION']
133
};
134
```
135
136
### Error Handling
137
138
Standard Version throws errors for various failure conditions that should be handled programmatically.
139
140
```javascript { .api }
141
/**
142
* Common error scenarios that may be thrown:
143
* - No package file found and gitTagFallback disabled
144
* - Git repository not initialized or not clean
145
* - Conventional changelog preset not found
146
* - Custom lifecycle script execution failure
147
* - File system permission errors
148
* - Invalid configuration format
149
*/
150
```
151
152
**Usage Examples:**
153
154
```javascript
155
const standardVersion = require('standard-version');
156
157
try {
158
await standardVersion({
159
gitTagFallback: false,
160
packageFiles: ['nonexistent.json']
161
});
162
} catch (error) {
163
if (error.message.includes('no package file found')) {
164
console.error('No valid package files found for version reading');
165
// Handle missing package files
166
} else if (error.message.includes('not a git repository')) {
167
console.error('Standard-version requires a git repository');
168
// Handle git repository requirement
169
} else {
170
console.error('Unexpected error:', error.message);
171
}
172
173
process.exit(1);
174
}
175
```
176
177
### Integration Patterns
178
179
Common patterns for integrating standard-version into build workflows.
180
181
**CI/CD Integration:**
182
183
```javascript
184
const standardVersion = require('standard-version');
185
186
async function release() {
187
// Ensure clean working directory
188
const { execSync } = require('child_process');
189
const status = execSync('git status --porcelain', { encoding: 'utf8' });
190
191
if (status.trim()) {
192
throw new Error('Working directory not clean');
193
}
194
195
// Run tests before release
196
console.log('Running tests...');
197
execSync('npm test', { stdio: 'inherit' });
198
199
// Execute standard-version
200
await standardVersion({
201
silent: false,
202
scripts: {
203
prebump: 'npm run build',
204
postbump: 'npm run package'
205
}
206
});
207
208
// Push changes and tags
209
execSync('git push --follow-tags origin main', { stdio: 'inherit' });
210
}
211
212
release().catch(error => {
213
console.error('Release failed:', error.message);
214
process.exit(1);
215
});
216
```
217
218
**Custom Release Script:**
219
220
```javascript
221
const standardVersion = require('standard-version');
222
const { getConfiguration } = require('standard-version/lib/configuration');
223
224
async function customRelease(releaseType) {
225
// Load base configuration
226
const baseConfig = getConfiguration();
227
228
// Add environment-specific overrides
229
const config = {
230
...baseConfig,
231
releaseAs: releaseType,
232
scripts: {
233
...baseConfig.scripts,
234
prebump: 'npm run validate',
235
precommit: 'npm run security-check',
236
postcommit: 'npm run deploy-docs'
237
}
238
};
239
240
if (process.env.CI) {
241
config.silent = true;
242
config.noVerify = true;
243
}
244
245
await standardVersion(config);
246
}
247
248
// Export for use in other scripts
249
module.exports = { customRelease };
250
```
251
252
## Configuration Options
253
254
The programmatic API accepts the same configuration options as the CLI, provided as object properties:
255
256
```javascript { .api }
257
interface StandardVersionOptions {
258
// Release configuration
259
releaseAs?: string; // 'major'|'minor'|'patch' or specific version
260
prerelease?: string | boolean; // Pre-release tag or true for default
261
firstRelease?: boolean; // Skip version bump for first release
262
263
// File configuration
264
infile?: string; // Changelog file path
265
packageFiles?: string[]; // Files to read version from
266
bumpFiles?: string[]; // Files to update with version
267
268
// Git configuration
269
sign?: boolean; // Sign git commit and tag
270
noVerify?: boolean; // Bypass git hooks
271
commitAll?: boolean; // Commit all staged changes
272
tagPrefix?: string; // Git tag prefix
273
274
// Behavior configuration
275
silent?: boolean; // Suppress output
276
dryRun?: boolean; // Preview mode
277
gitTagFallback?: boolean; // Use git tags if no package file
278
279
// Advanced configuration
280
scripts?: { // Lifecycle hook scripts
281
prebump?: string;
282
postbump?: string;
283
prechangelog?: string;
284
postchangelog?: string;
285
precommit?: string;
286
postcommit?: string;
287
pretag?: string;
288
posttag?: string;
289
};
290
skip?: { // Skip specific steps
291
bump?: boolean;
292
changelog?: boolean;
293
commit?: boolean;
294
tag?: boolean;
295
};
296
preset?: string; // Conventional changelog preset
297
path?: string; // Include only commits under path
298
header?: string; // Custom changelog header
299
releaseCommitMessageFormat?: string; // Commit message template
300
}
301
```
302
303
### Utility Functions
304
305
Standard Version exposes several utility functions that can be useful for advanced programmatic usage and custom integrations.
306
307
#### Git Tag Utilities
308
309
Get the latest semantic version tag from git repository.
310
311
```javascript { .api }
312
/**
313
* Get latest semver tag from git repository
314
* @param {string} [tagPrefix] - Optional tag prefix to filter tags (default: undefined)
315
* @returns {Promise<string>} Promise resolving to latest version string or '1.0.0' if no tags
316
*/
317
async function latestSemverTag(tagPrefix);
318
```
319
320
**Usage Examples:**
321
322
```javascript
323
const latestSemverTag = require('standard-version/lib/latest-semver-tag');
324
325
// Get latest version with default prefix
326
const currentVersion = await latestSemverTag();
327
console.log('Current version:', currentVersion); // "2.1.4"
328
329
// Get latest with custom prefix
330
const currentVersion = await latestSemverTag('release-');
331
console.log('Current version:', currentVersion); // "2.1.4" (from tag "release-2.1.4")
332
333
// Handle no existing tags
334
const firstVersion = await latestSemverTag();
335
console.log('First version:', firstVersion); // "1.0.0"
336
```
337
338
#### Message Formatting
339
340
Format commit messages with version placeholders.
341
342
```javascript { .api }
343
/**
344
* Format commit message template with version substitution
345
* @param {string} rawMsg - Raw commit message template with {{currentTag}} placeholder
346
* @param {string} newVersion - Version string to substitute
347
* @returns {string} Formatted commit message
348
*/
349
function formatCommitMessage(rawMsg, newVersion);
350
```
351
352
**Usage Examples:**
353
354
```javascript
355
const formatCommitMessage = require('standard-version/lib/format-commit-message');
356
357
// Basic formatting
358
const message = formatCommitMessage('chore(release): {{currentTag}}', '1.2.3');
359
console.log(message); // "chore(release): 1.2.3"
360
361
// Custom message template
362
const customMessage = formatCommitMessage(
363
'release: bump to {{currentTag}} [skip ci]',
364
'2.0.0'
365
);
366
console.log(customMessage); // "release: bump to 2.0.0 [skip ci]"
367
```
368
369
#### File Operations
370
371
Safe file writing with consistent behavior and error handling.
372
373
```javascript { .api }
374
/**
375
* Write content to file with standard-version error handling
376
* @param {Object} args - Configuration object with silent flag
377
* @param {string} filePath - Path to file to write
378
* @param {string} content - Content to write to file
379
* @returns {void}
380
* @throws {Error} If file cannot be written
381
*/
382
function writeFile(args, filePath, content);
383
```
384
385
**Usage Examples:**
386
387
```javascript
388
const writeFile = require('standard-version/lib/write-file');
389
390
// Write file with error handling
391
try {
392
writeFile(
393
{ silent: false },
394
'VERSION',
395
'1.2.3'
396
);
397
console.log('Version file updated');
398
} catch (error) {
399
console.error('Failed to write version file:', error.message);
400
}
401
402
// Silent mode
403
writeFile({ silent: true }, 'RELEASE_INFO.txt', 'Release 1.2.3');
404
```
405
406
#### Command Execution
407
408
Execute external commands and shell scripts with consistent error handling.
409
410
```javascript { .api }
411
/**
412
* Execute external command with arguments
413
* @param {Object} args - Configuration object with dryRun and silent flags
414
* @param {string} cmd - Command to execute
415
* @param {string[]} cmdArgs - Array of command arguments
416
* @returns {Promise<void>} Promise that resolves when command completes
417
* @throws {Error} If command execution fails
418
*/
419
async function runExecFile(args, cmd, cmdArgs);
420
421
/**
422
* Execute shell command string
423
* @param {Object} args - Configuration object with dryRun and silent flags
424
* @param {string} cmd - Shell command string to execute
425
* @returns {Promise<void>} Promise that resolves when command completes
426
* @throws {Error} If command execution fails
427
*/
428
async function runExec(args, cmd);
429
```
430
431
**Usage Examples:**
432
433
```javascript
434
const runExecFile = require('standard-version/lib/run-execFile');
435
const runExec = require('standard-version/lib/run-exec');
436
437
// Execute command with arguments
438
try {
439
await runExecFile(
440
{ dryRun: false, silent: false },
441
'git',
442
['add', 'package.json']
443
);
444
console.log('Files staged successfully');
445
} catch (error) {
446
console.error('Git add failed:', error.message);
447
}
448
449
// Execute shell command
450
await runExec({ dryRun: false, silent: false }, 'npm run build');
451
452
// Dry run mode
453
await runExec({ dryRun: true, silent: false }, 'git push'); // Only logs command
454
```
455
456
#### Preset Loading
457
458
Load and configure conventional changelog presets.
459
460
```javascript { .api }
461
/**
462
* Load conventional changelog preset with configuration
463
* @param {Object} args - Configuration object with preset and other changelog options
464
* @returns {Object} Loaded preset configuration object
465
* @throws {Error} If preset cannot be loaded or is invalid
466
*/
467
function presetLoader(args);
468
```
469
470
**Usage Examples:**
471
472
```javascript
473
const presetLoader = require('standard-version/lib/preset-loader');
474
475
// Load default preset
476
const preset = presetLoader({
477
preset: 'conventional-changelog-conventionalcommits'
478
});
479
console.log('Preset loaded:', preset.name);
480
481
// Load with custom configuration
482
const customPreset = presetLoader({
483
preset: 'conventional-changelog-angular',
484
types: [
485
{ type: 'feat', section: 'Features' },
486
{ type: 'fix', section: 'Bug Fixes' }
487
]
488
});
489
```