-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
executable file
·302 lines (256 loc) · 8.52 KB
/
build.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env node
const { exit } = require('process');
const { join } = require('node:path');
const { spawnSync } = require('node:child_process');
const {
readFileSync, writeFileSync,
mkdirSync, existsSync,
} = require('node:fs');
const installDependencies = () => {
console.log('Build dependencies missing, running `npm install`...')
const result = spawnSync('npm', ['install'], {
stdio: ['ignore', 'inherit', 'inherit'],
});
return result.status == 0;
};
const loadDependencies = (installed = false) => {
try {
return {
ts: require('typescript'),
terser: require('terser'),
AdmZip: require('adm-zip'),
};
} catch (_) {
if (!installed) {
if (installDependencies()) {
return loadDependencies(true);
}
}
console.error('Could not install build dependencies!');
exit(1);
}
}
// load dependencies
const { ts, terser, AdmZip } = loadDependencies();
const { useCaseSensitiveFileNames, newLine, } = ts.sys;
const baseDir = '.';
const outDir = join(baseDir, 'dist');
const constFn = (c) => () => c;
const isPlainObject = (obj) => Object.getPrototypeOf(obj) === Object.prototype;
const getCanonicalPath = useCaseSensitiveFileNames ? s => s : s => s.toLowerCase();
const getNewline = constFn(newLine);
const reportDiagnostics = (diag, dir = baseDir) => {
if (!diag.length) return;
console.log(ts.formatDiagnosticsWithColorAndContext(
ts.sortAndDeduplicateDiagnostics(diag),
{
getCurrentDirectory: constFn(dir),
getCanonicalFileName: getCanonicalPath,
getNewLine: getNewline,
}
));
};
const readFileCached = (() => {
const cache = new Map();
return (fileName) => {
if (!(fileName in cache)) {
cache[fileName] = readFileSync(fileName, 'utf-8');
}
return cache[fileName];
};
})();
const getVersion = (fileName) => {
const content = readFileCached(fileName);
// e.g.: const VERSION = '1.2.3.4';
const match = (/^.+\bVERSION\s+=\s+['"`]([0-9.]+)['"`];$/m).exec(content);
return match ? match[1] : match;
};
const _TSREF_RE = new RegExp('/// <reference path="([^"]+)"/>', 'mg');
const getReferences = (fileName, visited = null) => {
visited ||= new Set([fileName]);
const content = readFileCached(fileName);
const matches = content.matchAll(_TSREF_RE);
const references = new Set();
if (matches) {
for (const item of Array.from(matches).map(match => match[1])) {
references.add(item);
if (!visited.has(item)) {
for (const reference of getReferences(item, visited)) {
references.add(reference);
}
}
}
}
return references;
};
const toModule = (fileName, outFile) => {
const content = readFileCached(fileName);
const stem = fileName.split('.')[0].replace(/.*\//, '');
const re = new RegExp(`^(const ${stem} = )`, 'm');
return writeFileSync(outFile, content.replace(re, 'export $1'));
};
const filterWriter = (writeFile, filter) => (fileName, contents) => {
return writeFile(fileName, filter(fileName, contents));
};
const dedupLicense = (fileName, content) => {
const linesIn = content.split(newLine);
const linesOut = [];
const seen = new Set();
for (line of linesIn) {
if (line.match(/^\/\/.+(Copyright|SPDX-License-Identifier)/i)) {
if (seen.has(line)) {
continue;
} else {
seen.add(line);
}
}
linesOut.push(line);
}
return linesOut.join(newLine);
};
const compile = (fileNames, outFileOrCompilerOptions, compilerOptions) => {
// accept a string or array for the first argument
if (typeof fileNames === 'string') fileNames = [fileNames];
// we also handle (fileNames, outFile) and (fileNames, compilerOptions)
if (typeof outFileOrCompilerOptions === 'object') {
if (typeof compilerOptions === 'undefined') {
compilerOptions = outFileOrCompilerOptions;
} else {
throw new Error('Invalid arguments to `compile(...)`!');
}
} else if (typeof outFileOrCompilerOptions === 'string') {
if (typeof compilerOptions === 'undefined') {
compilerOptions = { outFile: outFileOrCompilerOptions };
} else if (typeof compilerOptions === 'object') {
compilerOptions.outFile = outFileOrCompilerOptions;
} else {
throw new Error('Invalid arguments to `compile(...)`!');
}
} else if (typeof outFileOrCompilerOptions === 'undefined') {
throw new Error('Invalid arguments to `compile(...)`!');
}
const { options } = ts.parseJsonConfigFileContent({
compilerOptions: compilerOptions,
}, ts.sys, '');
const host = ts.createCompilerHost(options);
host.writeFile = filterWriter(host.writeFile, dedupLicense);
const program = ts.createProgram(fileNames, options, host);
const result = program.emit();
const diag = ts.getPreEmitDiagnostics(program).concat(result.diagnostics);
reportDiagnostics(diag);
if (result.emitSkipped) {
if (compilerOptions.outFile) {
console.error(`Failed to compile: ${fileNames} -> ${compilerOptions.outFile}`);
} else {
console.error(`Failed to compile: ${fileNames}`);
}
exit(1);
}
return !result.emitSkipped;
}
const mergeOptions = (a, b) => {
const [ merged, added ] = [ structuredClone(a), structuredClone(b) ];
for (const key in added) {
const value = added[key];
if (!(key in merged)) {
merged[key] = value;
} else if (Array.isArray(value) && Array.isArray(merged[key])) {
for (const item of value) {
if (!merged[key].includes(item)) {
merged[key].push(item);
}
}
} else if (isPlainObject(value) && isPlainObject(merged[key])) {
merged[key] = mergeOptions(merged[key], value);
} else if (typeof value !== 'object' && typeof merged[key] !== 'object') {
merged[key] = value;
} else {
throw new Error(`Can't merge ${key}!`);
}
}
return merged;
};
const commonOptions = {
lib: ['dom'],
allowJs: true,
moduleResolution: 'node',
noEmitOnError: true,
};
const targets = [
// baseline
// support: Chrome/19+, Safari/6+, Firefox/4+, Opera/12.1+, Edge/12+, IE/9+
['smartpixel.ts', 'smartpixel.js', {target: 'es5', lib: ['es6']}],
// generator functions, arrow functions, const, let, etc added
// support: Chrome/51+, Safari/10+, Firefox/54+, Opera/38+, Edge/15+
['smartpixel.ts', 'smartpixel.es6.js', {target: 'es6', lib: ['es6']}],
// async/await, Object.{values,entries,getOwnPropertyDescriptors} added
// support: Chrome/55+, Safari/11+, Firefox/54+, Opera/42+, Edge/15+
// ['smartpixel.ts', 'smartpixel.es8.js', {target: 'es2017', lib: ['es2017']}],
['smartpixel.ts', 'smartpixel.d.ts', {
target: 'es5',
lib: ['es6'],
declaration: true,
emitDeclarationOnly: true,
}],
];
// create output directory if required
if (!existsSync(outDir)) mkdirSync(outDir);
for (const [ fileNames, outFile, options ] of targets) {
const target = join(outDir, outFile);
console.log(`Compiling TypeScript: ${fileNames} -> ${target}...`);
compile(fileNames, target, mergeOptions(commonOptions, options));
}
const output_es6 = join(outDir, 'smartpixel.es6.js');
const output_mjs = join(outDir, 'smartpixel.mjs');
const output_min = join(outDir, 'smartpixel.min.mjs');
if (existsSync(output_es6)) {
console.log(`Building ES6 module: ${output_es6} -> ${output_mjs}...`);
toModule(output_es6, output_mjs);
if (existsSync(output_mjs)) {
console.log(`Minifying ES6 module: ${output_mjs} -> ${output_min}...`);
const source = readFileCached(output_mjs);
const result = terser.minify_sync(source, {
mangle: {},
compress: {
passes: 5,
unsafe: true,
ecma: 2015,
},
format: {
ascii_only: true,
comments: false,
ecma: 2015,
},
});
writeFileSync(output_min, result.code);
}
}
const zip = new AdmZip();
const version = getVersion('smartpixel.ts');
const zip_dir = `smartpixel_${version}/`;
const zip_name = `smartpixel_${version}.zip`;
const zip_content = [
'LICENSE',
'smartpixel.ts',
'smartpixel.js',
'smartpixel.es6.js',
'smartpixel.mjs',
'smartpixel.d.ts',
];
for (const fileName of zip_content) {
if (existsSync(fileName) && fileName.endsWith('.ts')) {
for (const ref of getReferences(fileName)) {
if (!zip_content.includes(ref)) {
zip_content.push(ref);
}
}
}
}
for (const fileName of zip_content) {
const srcPath = existsSync(fileName) ? fileName : join(outDir, fileName);
const srcData = Buffer.from(readFileCached(srcPath), 'utf-8');
const dstPath = zip_dir + fileName;
console.log(`Adding to zip: ${srcPath} -> ${zip_name}:${dstPath}`);
zip.addFile(dstPath, srcData);
}
zip.writeZip(zip_name);