UNPKG

2.8 kBJavaScriptView Raw
1#!/usr/bin/env node
2if (module.parent) {
3 module.exports = bin
4} else {
5 bin(
6 process.stdin,
7 process.stdout,
8 process.stderr,
9 process.argv.slice(1),
10 function (status) {
11 process.exit(status)
12 }
13 )
14}
15
16function bin (stdin, stdout, stderr, argv, done) {
17 var args = require('yargs')
18 .scriptName('commonform-html')
19 .option('html5', {
20 describe: 'output HTML5',
21 type: 'boolean'
22 })
23 .option('lists', {
24 alias: 'l',
25 describe: 'output lists',
26 type: 'boolean'
27 })
28 .option('title', {
29 alias: 't',
30 describe: 'form title',
31 type: 'string'
32 })
33 .option('edition', {
34 alias: 'e',
35 describe: 'form edition',
36 type: 'string'
37 })
38 .option('values', {
39 alias: 'v',
40 describe: 'JSON file with blank values',
41 normalize: true,
42 demandOption: false
43 })
44 .option('directions', {
45 alias: 'd',
46 describe: 'JSON file with directions',
47 normalize: true,
48 demandOption: false
49 })
50 .implies('directions', 'values')
51 .coerce({
52 values: readJSON,
53 directions: readJSON
54 })
55 .version()
56 .help()
57 .alias('h', 'help')
58 .parse(argv)
59
60 // Prepare fill-in-the-blank values.
61 var directions = args.directions
62 var values = args.values
63 if (directions && !Array.isArray(directions)) {
64 stderr.write('Directions must be an array.\n')
65 return done(1)
66 }
67 var blanks = []
68 if (values) {
69 if (Array.isArray(values)) {
70 blanks = values
71 } else {
72 Object.keys(values).forEach(function (label) {
73 var value = values[label]
74 directions.forEach(function (direction) {
75 if (direction.label !== label) return
76 blanks.push({ value: value, blank: direction.blank })
77 })
78 })
79 }
80 }
81
82 // Prepare rendering options.
83 var options = {}
84 if (args.edition) options.edition = args.edition
85 if (args.title) options.title = args.title
86 if (args.html5) options.html5 = true
87 if (args.lists) options.lists = true
88
89 // Read the form to be rendered.
90 var chunks = []
91 stdin
92 .on('data', function (chunk) {
93 chunks.push(chunk)
94 })
95 .once('error', function (error) {
96 return fail(error)
97 })
98 .once('end', function () {
99 var buffer = Buffer.concat(chunks)
100 try {
101 var form = JSON.parse(buffer)
102 } catch (error) {
103 return fail(error)
104 }
105
106 // Render.
107 try {
108 var rendered = require('./')(form, blanks, options)
109 } catch (error) {
110 return fail(error)
111 }
112 stdout.write(rendered + '\n')
113 return done(0)
114 })
115
116 function fail (error) {
117 stderr.write(error.toString() + '\n')
118 done(1)
119 }
120}
121
122function readJSON (file) {
123 return JSON.parse(require('fs').readFileSync(file))
124}