forked from w3c/respec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.js
executable file
·188 lines (180 loc) · 5.26 KB
/
builder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env node
"use strict";
const colors = require("colors");
const fsp = require("fs-extra");
const loading = require("loading-indicator");
const path = require("path");
const presets = require("loading-indicator/presets");
const r = require("requirejs");
const UglifyJS = require("uglify-es");
const commandLineArgs = require("command-line-args");
const getUsage = require("command-line-usage");
colors.setTheme({
error: "red",
info: "green",
});
const optionList = [
{
alias: "h",
defaultValue: false,
description: "Display this usage guide.",
name: "help",
type: Boolean,
},
{
alias: "p",
defaultOption: true,
description: "Name of profile to build. Profile must be " +
"in the js/ folder, and start with 'profile-' (e.g., profile-w3c-common.js)",
multiple: false,
name: "profile",
type: String,
},
];
const usageSections = [
{
header: "builder",
content: "Builder builds a ReSpec profile",
},
{
header: "Options",
optionList,
},
{
header: "Examples",
content: [
{
desc: "1. Build W3C Profile ",
example: "$ ./tools/builder.js --profile=w3c-common",
},
],
},
{
content: "Project home: [underline]{https://github.com/w3c/respec}",
raw: true,
},
];
/**
* Async function that appends the boilerplate to the generated script
* and writes out the result. It also creates the source map file.
*
* @private
* @param {String} outPath Where to write the output to.
* @param {String} version The version of the script.
* @return {Promise} Resolves when done writing the files.
*/
function appendBoilerplate(outPath, version, name) {
return async(optimizedJs, sourceMap) => {
const respecJs = `"use strict";
/* ReSpec ${version}
Created by Robin Berjon, http://berjon.com/ (@robinberjon)
Documentation: http://w3.org/respec/.
See original source for licenses: https://github.com/w3c/respec */
window.respecVersion = "${version}";
${optimizedJs}
require(['profile-${name}']);`;
const result = UglifyJS.minify(respecJs, {
toplevel: true,
sourceMap: {
filename: `respec-${name}.js`,
url: `respec-${name}.build.js.map`,
},
});
if ("error" in result) {
throw new Error(result.error);
}
const mapPath = path.dirname(outPath) + `/respec-${name}.build.js.map`;
const promiseToWriteJs = fsp.writeFile(outPath, result.code, "utf-8");
const promiseToWriteMap = fsp.writeFile(mapPath, sourceMap, "utf-8");
await Promise.all([promiseToWriteJs, promiseToWriteMap]);
};
}
const Builder = {
/**
* Async function that gets the current version of ReSpec from package.json
*
* @returns {Promise<String>} The version string.
*/
getRespecVersion: async() => {
const packagePath = path.join(__dirname, "../package.json");
const content = await fsp.readFile(packagePath, "utf-8");
return JSON.parse(content).version;
},
/**
* Async function runs Requirejs' optimizer to generate the output.
*
* using a custom configuration.
* @param {[type]} options [description]
* @return {[type]} [description]
*/
async build({ name }) {
if (!name) {
throw new TypeError("name is required");
}
const buildPath = path.join(__dirname, "../builds");
const outFile = `respec-${name}.js`;
const outPath = path.join(buildPath, outFile);
const loadingMsg = colors.info(` Generating ${outFile}. Please wait... `);
const timer = loading.start(loadingMsg, {
frames: presets.clock,
delay: 1,
});
// optimisation settings
const buildVersion = await this.getRespecVersion();
const outputWritter = appendBoilerplate(outPath, buildVersion, name);
const config = {
baseUrl: path.join(__dirname, "../js/"),
deps: ["deps/require"],
generateSourceMaps: true,
inlineText: true,
logLevel: 2, // Show uglify warnings and errors.
mainConfigFile: `js/profile-${name}.js`,
name: `profile-${name}`,
optimize: "none",
preserveLicenseComments: false,
useStrict: true,
};
const promiseToWrite = new Promise((resolve, reject) => {
config.out = (concatinatedJS, sourceMap) => {
outputWritter(concatinatedJS, sourceMap).then(resolve).catch(reject);
};
});
r.optimize(config);
const buildDir = path.resolve(__dirname, "../builds/");
const workerDir = path.resolve(__dirname, "../worker/");
// copy respec-worker
fsp
.createReadStream(`${workerDir}/respec-worker.js`)
.pipe(fsp.createWriteStream(`${buildDir}/respec-worker.js`));
await promiseToWrite;
loading.stop(timer);
},
};
exports.Builder = Builder;
if (require.main === module) {
(async function run() {
let parsedArgs;
try {
parsedArgs = commandLineArgs(optionList);
} catch (err) {
console.info(getUsage(usageSections));
console.error(colors.error(err.stack));
return process.exit(127);
}
if (parsedArgs.help) {
console.info(getUsage(usageSections));
return process.exit(0);
}
const { profile: name } = parsedArgs;
if (!name) {
return;
}
try {
await Builder.build({ name });
} catch (err) {
console.error(colors.error(err.stack));
return process.exit(1);
}
process.exit(0);
})();
}