0
# Programmatic API
1
2
Internal modules and utilities for programmatic usage of Swagger CLI functionality in Node.js applications.
3
4
## Capabilities
5
6
### CLI Utilities
7
8
Interactive command-line interface utilities for prompts, validation, and command execution.
9
10
```javascript { .api }
11
const cli = require('swagger/lib/util/cli');
12
```
13
14
#### Interactive Prompts
15
16
```javascript { .api }
17
/**
18
* Require answers to questions, prompting user for missing values
19
* @param {Object[]} questions - Array of question objects
20
* @param {Object} results - Existing results object (optional)
21
* @param {Function} cb - Callback function with completed results
22
*/
23
function requireAnswers(questions, results, cb);
24
25
/**
26
* Update answers with new defaults and re-prompt
27
* @param {Object[]} questions - Array of question objects
28
* @param {Object} results - Existing results object
29
* @param {Function} cb - Callback function with updated results
30
*/
31
function updateAnswers(questions, results, cb);
32
33
/**
34
* Single choice selection from list
35
* @param {string} prompt - Prompt message
36
* @param {string[]} choices - Array of choice options
37
* @param {Function} cb - Callback function with selected choice
38
*/
39
function chooseOne(prompt, choices, cb);
40
41
/**
42
* Confirmation prompt
43
* @param {string} prompt - Prompt message
44
* @param {boolean} defaultBool - Default value (optional, default: true)
45
* @param {Function} cb - Callback function with boolean result
46
*/
47
function confirm(prompt, defaultBool, cb);
48
49
/**
50
* Text input prompt
51
* @param {string} prompt - Prompt message
52
* @param {string} defaultValue - Default value (optional)
53
* @param {Function} cb - Callback function with input value
54
*/
55
function prompt(prompt, defaultValue, cb);
56
```
57
58
**Usage Examples:**
59
60
```javascript
61
const cli = require('swagger/lib/util/cli');
62
63
// Interactive question flow
64
const questions = [
65
{ name: 'name', message: 'Project name?' },
66
{ name: 'framework', message: 'Framework?', type: 'list', choices: ['express', 'hapi'] }
67
];
68
69
cli.requireAnswers(questions, function(answers) {
70
console.log('Project:', answers.name, 'Framework:', answers.framework);
71
});
72
73
// Confirmation prompt
74
cli.confirm('Delete existing files?', false, function(confirmed) {
75
if (confirmed) {
76
console.log('Proceeding with deletion...');
77
}
78
});
79
80
// Choice selection
81
cli.chooseOne('Select environment:', ['development', 'staging', 'production'], function(env) {
82
console.log('Selected environment:', env);
83
});
84
```
85
86
#### Command Execution
87
88
```javascript { .api }
89
/**
90
* Execute command with error handling and output formatting
91
* @param {Function} command - Command function to execute
92
* @param {string} header - Optional header for output
93
* @returns {Function} Wrapped command function
94
*/
95
function execute(command, header);
96
97
/**
98
* Print output and exit process
99
* @param {Error} err - Error object (if any)
100
* @param {*} output - Output to print
101
* @param {number} code - Exit code (optional)
102
*/
103
function printAndExit(err, output, code);
104
105
/**
106
* Validate commander.js app configuration
107
* @param {Object} app - Commander.js app instance
108
*/
109
function validate(app);
110
111
/**
112
* Get package version
113
* @returns {string} Package version string
114
*/
115
function version();
116
```
117
118
### Feedback System
119
120
Event-based feedback system for capturing and displaying command output and progress messages.
121
122
```javascript { .api }
123
const feedback = require('swagger/lib/util/feedback');
124
```
125
126
#### Feedback Events
127
128
```javascript { .api }
129
/**
130
* Listen for feedback events
131
* @param {Function} cb - Callback function receiving feedback messages
132
*/
133
function on(cb);
134
135
/**
136
* Emit feedback message
137
* @param {string} string - Message string (supports util.format formatting)
138
* @param {...*} args - Additional formatting arguments
139
*/
140
function emit(string, ...args);
141
```
142
143
**Usage Examples:**
144
145
```javascript
146
const feedback = require('swagger/lib/util/feedback');
147
148
// Listen for feedback
149
feedback.on(function(message) {
150
console.log('[FEEDBACK]', message);
151
});
152
153
// Emit messages
154
feedback.emit('Starting operation...');
155
feedback.emit('Processing %d files in %s', 5, '/path/to/dir');
156
feedback.emit('Operation completed successfully');
157
```
158
159
### Project Management API
160
161
Programmatic access to project management functionality.
162
163
```javascript { .api }
164
const project = require('swagger/lib/commands/project/project');
165
```
166
167
#### Core Functions
168
169
```javascript { .api }
170
/**
171
* Create new Swagger project
172
* @param {string} name - Project name
173
* @param {Object} options - Creation options
174
* @param {string} options.framework - Target framework
175
* @param {Function} cb - Callback function
176
*/
177
function create(name, options, cb);
178
179
/**
180
* Start project development server
181
* @param {string} directory - Project directory
182
* @param {Object} options - Server options
183
* @param {Function} cb - Callback function
184
*/
185
function start(directory, options, cb);
186
187
/**
188
* Verify project configuration
189
* @param {string} directory - Project directory
190
* @param {Object} options - Verification options
191
* @param {Function} cb - Callback function
192
*/
193
function verify(directory, options, cb);
194
195
/**
196
* Launch Swagger editor
197
* @param {string} directory - Project directory
198
* @param {Object} options - Editor options
199
* @param {Function} cb - Callback function
200
*/
201
function edit(directory, options, cb);
202
203
/**
204
* Open project in browser
205
* @param {string} directory - Project directory
206
* @param {Object} options - Browser options
207
* @param {Function} cb - Callback function
208
*/
209
function open(directory, options, cb);
210
211
/**
212
* Run project tests
213
* @param {string} directory - Project directory or test file
214
* @param {Object} options - Test options
215
* @param {Function} cb - Callback function
216
*/
217
function test(directory, options, cb);
218
219
/**
220
* Generate test templates
221
* @param {string} directory - Project directory
222
* @param {Object} options - Generation options
223
* @param {Function} cb - Callback function
224
*/
225
function generateTest(directory, options, cb);
226
```
227
228
#### Project Configuration
229
230
```javascript { .api }
231
/**
232
* Read and parse project configuration
233
* @param {string} directory - Project directory
234
* @param {Object} options - Read options
235
* @param {Function} cb - Callback function with project object
236
*/
237
function read(directory, options, cb);
238
239
// Configuration constants
240
const frameworks = {
241
connect: { source: 'connect' },
242
express: { source: 'connect', overlay: 'express' },
243
hapi: { source: 'connect', overlay: 'hapi' },
244
restify: { source: 'connect', overlay: 'restify' },
245
sails: { source: 'sails' }
246
};
247
248
const assertiontypes = ['expect', 'should', 'assert'];
249
const testmodules = ['supertest', 'request'];
250
```
251
252
**Usage Examples:**
253
254
```javascript
255
const project = require('swagger/lib/commands/project/project');
256
257
// Create project programmatically
258
project.create('my-api', { framework: 'express' }, function(err, result) {
259
if (err) {
260
console.error('Project creation failed:', err);
261
} else {
262
console.log('Project created:', result);
263
}
264
});
265
266
// Read project configuration
267
project.read('./my-api', {}, function(err, projectConfig) {
268
if (err) {
269
console.error('Failed to read project:', err);
270
} else {
271
console.log('Project name:', projectConfig.api.name);
272
console.log('Project host:', projectConfig.api.host);
273
console.log('Swagger file:', projectConfig.api.swaggerFile);
274
}
275
});
276
```
277
278
### Command Modules
279
280
Direct access to command functionality for validation and conversion.
281
282
```javascript { .api }
283
const { convert, validate } = require('swagger/lib/commands/commands');
284
```
285
286
#### Validation Commands
287
288
```javascript { .api }
289
/**
290
* Validate Swagger document
291
* @param {string} file - File path or null for stdin
292
* @param {Object} options - Validation options
293
* @param {boolean} options.json - Output as JSON
294
* @param {Function} cb - Callback function
295
*/
296
function validate(file, options, cb);
297
```
298
299
#### Conversion Commands
300
301
```javascript { .api }
302
/**
303
* Convert Swagger 1.2 to 2.0
304
* @param {string} filePath - Main resource listing file
305
* @param {string[]} apiDeclarations - API declaration files
306
* @param {Object} options - Conversion options
307
* @param {string} options.outputFile - Output file path
308
* @param {Function} cb - Callback function
309
*/
310
function convert(filePath, apiDeclarations, options, cb);
311
```
312
313
### Swagger Specification Utilities
314
315
Utilities for validating Swagger documents programmatically.
316
317
```javascript { .api }
318
const spec = require('swagger/lib/util/spec');
319
```
320
321
#### Specification Validation
322
323
```javascript { .api }
324
/**
325
* Validate Swagger specification document
326
* @param {Object} swagger - Swagger specification object
327
* @param {Object} options - Validation options
328
* @param {boolean} options.json - Output as JSON format
329
* @param {Function} cb - Callback function with validation results
330
*/
331
function validateSwagger(swagger, options, cb);
332
```
333
334
**Usage Examples:**
335
336
```javascript
337
const spec = require('swagger/lib/util/spec');
338
const fs = require('fs');
339
const yaml = require('js-yaml');
340
341
// Load and validate YAML Swagger file
342
const swaggerDoc = yaml.safeLoad(fs.readFileSync('./api/swagger/swagger.yaml', 'utf8'));
343
344
spec.validateSwagger(swaggerDoc, {}, function(err, results) {
345
if (err) {
346
console.error('Validation failed:', err);
347
} else {
348
console.log('Validation results:', results);
349
}
350
});
351
352
// Get JSON formatted results
353
spec.validateSwagger(swaggerDoc, { json: true }, function(err, jsonResults) {
354
if (err) {
355
console.error('Validation failed:', err);
356
} else {
357
console.log('JSON Results:', jsonResults);
358
}
359
});
360
```
361
362
### Browser Integration
363
364
Cross-platform browser launching utilities for opening URLs.
365
366
```javascript { .api }
367
const browser = require('swagger/lib/util/browser');
368
```
369
370
#### Browser Control
371
372
```javascript { .api }
373
/**
374
* Open URL in system default browser
375
* @param {string} url - URL to open
376
* @param {Function} cb - Callback function
377
* @param {string} platform - Platform override for testing (optional)
378
*/
379
function open(url, cb, platform);
380
```
381
382
**Usage Examples:**
383
384
```javascript
385
const browser = require('swagger/lib/util/browser');
386
387
// Open Swagger documentation
388
browser.open('https://swagger.io/docs/', function(err) {
389
if (err) {
390
console.error('Failed to open browser:', err);
391
} else {
392
console.log('Browser opened successfully');
393
}
394
});
395
396
// Open local development server
397
browser.open('http://localhost:10010', function(err) {
398
if (err) {
399
console.error('Could not open local server:', err);
400
}
401
});
402
```
403
404
### Network Utilities
405
406
Network connectivity and port checking utilities.
407
408
```javascript { .api }
409
const net = require('swagger/lib/util/net');
410
```
411
412
#### Port Management
413
414
```javascript { .api }
415
/**
416
* Check if a port is open and available
417
* @param {number} port - Port number to check
418
* @param {number} timeout - Connection timeout in milliseconds (optional)
419
* @param {Function} cb - Callback function with boolean result
420
*/
421
function isPortOpen(port, timeout, cb);
422
```
423
424
**Usage Examples:**
425
426
```javascript
427
const net = require('swagger/lib/util/net');
428
429
// Check if default Swagger port is available
430
net.isPortOpen(10010, function(err, isOpen) {
431
if (err) {
432
console.error('Port check failed:', err);
433
} else if (isOpen) {
434
console.log('Port 10010 is available');
435
} else {
436
console.log('Port 10010 is in use');
437
}
438
});
439
440
// Check with custom timeout
441
net.isPortOpen(8080, 5000, function(err, isOpen) {
442
if (err) {
443
console.error('Port check timed out:', err);
444
} else {
445
console.log('Port 8080 status:', isOpen ? 'available' : 'in use');
446
}
447
});
448
```
449
450
### Configuration System
451
452
Access to configuration constants and environment variable handling.
453
454
```javascript { .api }
455
const config = require('swagger/config');
456
```
457
458
#### Configuration Properties
459
460
```javascript { .api }
461
const config = {
462
rootDir: string, // Root directory path (swagger package directory)
463
userHome: string, // User home directory
464
debug: boolean, // Debug mode flag (from DEBUG env var)
465
nodeModules: string, // Node modules path
466
swagger: {
467
fileName: string, // Default Swagger file path ('api/swagger/swagger.yaml')
468
editorDir: string, // Swagger editor directory
469
editorConfig: { // Editor configuration object
470
analytics: Object, // Analytics configuration
471
disableCodeGen: boolean, // Code generation toggle
472
disableNewUserIntro: boolean, // New user intro toggle
473
examplesFolder: string, // Examples directory path
474
exampleFiles: Array, // Example files list
475
autocompleteExtension: Object, // Autocomplete settings
476
useBackendForStorage: boolean, // Backend storage toggle
477
backendEndpoint: string, // Backend API endpoint
478
backendHealthCheckTimeout: number, // Health check timeout
479
useYamlBackend: boolean, // YAML backend toggle
480
disableFileMenu: boolean, // File menu toggle
481
enableTryIt: boolean, // Try-it functionality toggle
482
headerBranding: boolean, // Header branding toggle
483
brandingCssClass: string, // CSS class for branding
484
schemaUrl: string, // Schema validation URL
485
importProxyUrl: string // Import proxy URL
486
}
487
},
488
project: {
489
port: number, // Default project port (10010 or PORT env var)
490
skeletonsDir: string // Project templates directory
491
}
492
};
493
```
494
495
**Usage Examples:**
496
497
```javascript
498
const config = require('swagger/config');
499
500
console.log('Swagger CLI root:', config.rootDir);
501
console.log('Default project port:', config.project.port);
502
console.log('Swagger file location:', config.swagger.fileName);
503
504
// Check debug mode
505
if (config.debug) {
506
console.log('Debug mode is enabled');
507
}
508
```
509
510
## Error Handling
511
512
All programmatic APIs use Node.js error-first callback conventions:
513
514
```javascript
515
function(err, result) {
516
if (err) {
517
// Handle error
518
console.error('Operation failed:', err.message);
519
} else {
520
// Process result
521
console.log('Operation succeeded:', result);
522
}
523
}
524
```
525
526
Common error types:
527
- **File System Errors**: Missing files, permission issues
528
- **Validation Errors**: Invalid Swagger specifications
529
- **Network Errors**: Port binding, HTTP server issues
530
- **Configuration Errors**: Invalid project settings