-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.cjs
More file actions
executable file
·415 lines (354 loc) · 12.6 KB
/
build.cjs
File metadata and controls
executable file
·415 lines (354 loc) · 12.6 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/usr/bin/env node
/**
* Build script for EZCONTACTFORM Widget
*
* Updates version in widget.js and generates versioned distribution files.
*
* Usage:
* node build.js # Build from package.json version
* node build.js --tag # Build from Git tag
* node build.js --version 1.4.0 # Build with specific version
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// Minification libraries (loaded lazily)
let Terser = null;
let CleanCSS = null;
/**
* Load minification libraries
*/
function loadMinifiers() {
try {
Terser = require('terser');
CleanCSS = require('clean-css');
return true;
} catch (err) {
console.warn('⚠️ Minification libraries not installed. Run: npm install');
console.warn(' Skipping minification...');
return false;
}
}
/**
* Minify JavaScript file
*/
async function minifyJS(inputPath, outputPath) {
if (!Terser) return false;
const code = fs.readFileSync(inputPath, 'utf8');
const result = await Terser.minify(code, {
compress: {
drop_console: false, // Keep console.log for debugging
drop_debugger: true,
passes: 2
},
mangle: {
reserved: ['EZForm'] // Don't mangle the global EZForm object
},
format: {
comments: /^!/ // Keep comments starting with !
}
});
if (result.error) {
throw result.error;
}
// Add banner comment
const banner = `/*! EZForm Widget - https://ezcontactform.com */\n`;
fs.writeFileSync(outputPath, banner + result.code, 'utf8');
return true;
}
/**
* Minify CSS file
*/
function minifyCSS(inputPath, outputPath) {
if (!CleanCSS) return false;
const css = fs.readFileSync(inputPath, 'utf8');
const minifier = new CleanCSS({
level: 2,
format: false
});
const result = minifier.minify(css);
if (result.errors && result.errors.length > 0) {
throw new Error(result.errors.join(', '));
}
// Add banner comment
const banner = `/*! EZForm Widget Styles - https://ezcontactform.com */\n`;
fs.writeFileSync(outputPath, banner + result.styles, 'utf8');
return true;
}
// ANSI color codes for terminal output
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
green: '\x1b[32m',
yellow: '\x1b[33m',
red: '\x1b[31m',
blue: '\x1b[34m',
};
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
function error(message) {
log(`❌ ${message}`, 'red');
process.exit(1);
}
function success(message) {
log(`✅ ${message}`, 'green');
}
function info(message) {
log(`ℹ️ ${message}`, 'blue');
}
/**
* Get version from command line args, Git tag, or package.json
*/
function getVersion() {
const args = process.argv.slice(2);
// Check for --version flag
if (args.includes('--version')) {
const idx = args.indexOf('--version');
const version = args[idx + 1];
if (!version) {
error('--version flag requires a version number (e.g., --version 1.4.0)');
}
if (!isValidSemver(version)) {
error(`Invalid version format: ${version}. Use semantic versioning (e.g., 1.4.0)`);
}
return version;
}
// Check for --tag flag
if (args.includes('--tag')) {
try {
const tag = execSync('git describe --tags --exact-match HEAD 2>/dev/null', {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore']
}).trim();
const version = tag.replace(/^v/, ''); // Remove 'v' prefix
if (!isValidSemver(version)) {
error(`Git tag is not valid semver: ${tag}`);
}
info(`Using version from Git tag: ${tag}`);
return version;
} catch (err) {
error('No Git tag found for current commit. Use --version or create a tag first.');
}
}
// Default: read from package.json
try {
const pkgPath = path.join(process.cwd(), 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const version = pkg.version;
if (!version) {
error('No version found in package.json');
}
if (!isValidSemver(version)) {
error(`Invalid version in package.json: ${version}`);
}
info(`Using version from package.json: ${version}`);
return version;
} catch (err) {
error(`Failed to read package.json: ${err.message}`);
}
}
/**
* Validate semantic version format
*/
function isValidSemver(version) {
const semverRegex = /^\d+\.\d+\.\d+(-[a-zA-Z0-9-]+)?(\+[a-zA-Z0-9-]+)?$/;
return semverRegex.test(version);
}
/**
* Update version in widget.js file
*/
function updateVersion(filePath, version) {
if (!fs.existsSync(filePath)) {
error(`File not found: ${filePath}`);
}
let content = fs.readFileSync(filePath, 'utf8');
const originalContent = content;
// Check if version patterns exist before replacing
const versionPattern1 = /Version:\s*\d+\.\d+\.\d+(-[a-zA-Z0-9-]+)?(\+[a-zA-Z0-9-]+)?/g;
const versionPattern2 = /version:\s*['"]\d+\.\d+\.\d+(-[a-zA-Z0-9-]+)?(\+[a-zA-Z0-9-]+)?['"]/g;
const hasVersion1 = versionPattern1.test(content);
const hasVersion2 = versionPattern2.test(content);
if (!hasVersion1 && !hasVersion2) {
error(`No version patterns found in ${filePath}. Make sure the file contains 'Version: X.Y.Z' or version: 'X.Y.Z'`);
}
// Reset regex lastIndex for replace operations
versionPattern1.lastIndex = 0;
versionPattern2.lastIndex = 0;
// Update header comment: Version: X.Y.Z
content = content.replace(versionPattern1, `Version: ${version}`);
// Update code constant: version: 'X.Y.Z'
content = content.replace(versionPattern2, `version: '${version}'`);
fs.writeFileSync(filePath, content, 'utf8');
success(`Updated version in ${path.basename(filePath)}`);
}
/**
* Copy file to destination
*/
function copyFile(src, dest) {
const destDir = path.dirname(dest);
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
}
fs.copyFileSync(src, dest);
}
/**
* Main build function
*/
async function build() {
const version = getVersion();
log(`\n${colors.bright}Building widget v${version}...${colors.reset}\n`);
const srcDir = path.join(process.cwd(), 'src');
const distDir = path.join(process.cwd(), 'dist');
// Ensure src directory exists
if (!fs.existsSync(srcDir)) {
error(`Source directory not found: ${srcDir}`);
}
const widgetJsPath = path.join(srcDir, 'widget.js');
const widgetCssPath = path.join(srcDir, 'widget.css');
const ezformJsPath = path.join(srcDir, 'ezform.js');
// Check source files exist
if (!fs.existsSync(widgetJsPath)) {
error(`Widget JS file not found: ${widgetJsPath}`);
}
if (!fs.existsSync(widgetCssPath)) {
error(`Widget CSS file not found: ${widgetCssPath}`);
}
if (!fs.existsSync(ezformJsPath)) {
error(`EZForm JS file not found: ${ezformJsPath}`);
}
// Load minification libraries
const canMinify = loadMinifiers();
// Create dist directory
if (!fs.existsSync(distDir)) {
fs.mkdirSync(distDir, { recursive: true });
}
// --- Build widget.js ---
const tempWidgetJs = path.join(distDir, '.widget.js.tmp');
copyFile(widgetJsPath, tempWidgetJs);
updateVersion(tempWidgetJs, version);
const versionedJs = path.join(distDir, `widget-${version}.js`);
const versionedCss = path.join(distDir, `widget-${version}.css`);
const versionedJsMin = path.join(distDir, `widget-${version}.min.js`);
const versionedCssMin = path.join(distDir, `widget-${version}.min.css`);
copyFile(tempWidgetJs, versionedJs);
copyFile(widgetCssPath, versionedCss);
const latestJs = path.join(distDir, 'widget.js');
const latestCss = path.join(distDir, 'widget.css');
const latestJsMin = path.join(distDir, 'widget.min.js');
const latestCssMin = path.join(distDir, 'widget.min.css');
copyFile(versionedJs, latestJs);
copyFile(versionedCss, latestCss);
// Minify widget files
if (canMinify) {
await minifyJS(versionedJs, versionedJsMin);
minifyCSS(versionedCss, versionedCssMin);
copyFile(versionedJsMin, latestJsMin);
copyFile(versionedCssMin, latestCssMin);
success(`Minified widget.js and widget.css`);
}
fs.unlinkSync(tempWidgetJs);
// --- Build ezform.js ---
const tempEzformJs = path.join(distDir, '.ezform.js.tmp');
copyFile(ezformJsPath, tempEzformJs);
// ezform.js may not have version patterns, so we add one if needed
let ezformContent = fs.readFileSync(tempEzformJs, 'utf8');
// Check if version pattern exists, if not add it to header
const hasVersionHeader = /Version:\s*\d+\.\d+\.\d+/.test(ezformContent);
if (!hasVersionHeader) {
// Add version to the header comment
ezformContent = ezformContent.replace(
/\/\*\*\n \* EZForm Helper Script/,
`/**\n * EZForm Helper Script\n * Version: ${version}`
);
fs.writeFileSync(tempEzformJs, ezformContent, 'utf8');
success(`Added version to ezform.js header`);
} else {
// Update existing version
ezformContent = ezformContent.replace(
/Version:\s*\d+\.\d+\.\d+(-[a-zA-Z0-9-]+)?(\+[a-zA-Z0-9-]+)?/g,
`Version: ${version}`
);
fs.writeFileSync(tempEzformJs, ezformContent, 'utf8');
success(`Updated version in ezform.js`);
}
const versionedEzformJs = path.join(distDir, `ezform-${version}.js`);
const versionedEzformJsMin = path.join(distDir, `ezform-${version}.min.js`);
const latestEzformJs = path.join(distDir, 'ezform.js');
const latestEzformJsMin = path.join(distDir, 'ezform.min.js');
copyFile(tempEzformJs, versionedEzformJs);
copyFile(versionedEzformJs, latestEzformJs);
// Minify ezform files
if (canMinify) {
await minifyJS(versionedEzformJs, versionedEzformJsMin);
copyFile(versionedEzformJsMin, latestEzformJsMin);
success(`Minified ezform.js`);
}
fs.unlinkSync(tempEzformJs);
// Output summary
log(`\n${colors.bright}Build Summary:${colors.reset}`);
log(` Version: ${colors.green}${version}${colors.reset}`);
log(` Files generated:`);
log(` ${colors.blue}dist/widget-${version}.js${colors.reset}`);
log(` ${colors.blue}dist/widget-${version}.css${colors.reset}`);
if (canMinify) {
log(` ${colors.blue}dist/widget-${version}.min.js${colors.reset} (minified)`);
log(` ${colors.blue}dist/widget-${version}.min.css${colors.reset} (minified)`);
}
log(` ${colors.blue}dist/widget.js${colors.reset} (latest)`);
log(` ${colors.blue}dist/widget.css${colors.reset} (latest)`);
if (canMinify) {
log(` ${colors.blue}dist/widget.min.js${colors.reset} (latest, minified)`);
log(` ${colors.blue}dist/widget.min.css${colors.reset} (latest, minified)`);
}
log(` ${colors.blue}dist/ezform-${version}.js${colors.reset}`);
if (canMinify) {
log(` ${colors.blue}dist/ezform-${version}.min.js${colors.reset} (minified)`);
}
log(` ${colors.blue}dist/ezform.js${colors.reset} (latest)`);
if (canMinify) {
log(` ${colors.blue}dist/ezform.min.js${colors.reset} (latest, minified)`);
}
// Get file sizes
const jsSize = (fs.statSync(versionedJs).size / 1024).toFixed(2);
const cssSize = (fs.statSync(versionedCss).size / 1024).toFixed(2);
const ezformSize = (fs.statSync(versionedEzformJs).size / 1024).toFixed(2);
log(`\n File sizes:`);
log(` widget-${version}.js: ${jsSize} KB`);
log(` widget-${version}.css: ${cssSize} KB`);
log(` ezform-${version}.js: ${ezformSize} KB`);
if (canMinify) {
const jsMinSize = (fs.statSync(versionedJsMin).size / 1024).toFixed(2);
const cssMinSize = (fs.statSync(versionedCssMin).size / 1024).toFixed(2);
const ezformMinSize = (fs.statSync(versionedEzformJsMin).size / 1024).toFixed(2);
log(`\n Minified sizes:`);
log(` widget-${version}.min.js: ${jsMinSize} KB (${((1 - jsMinSize/jsSize) * 100).toFixed(0)}% smaller)`);
log(` widget-${version}.min.css: ${cssMinSize} KB (${((1 - cssMinSize/cssSize) * 100).toFixed(0)}% smaller)`);
log(` ezform-${version}.min.js: ${ezformMinSize} KB (${((1 - ezformMinSize/ezformSize) * 100).toFixed(0)}% smaller)`);
}
success(`\nBuild completed successfully!`);
return {
version,
files: {
versionedJs,
versionedCss,
versionedJsMin: canMinify ? versionedJsMin : null,
versionedCssMin: canMinify ? versionedCssMin : null,
latestJs,
latestCss,
latestJsMin: canMinify ? latestJsMin : null,
latestCssMin: canMinify ? latestCssMin : null,
versionedEzformJs,
versionedEzformJsMin: canMinify ? versionedEzformJsMin : null,
latestEzformJs,
latestEzformJsMin: canMinify ? latestEzformJsMin : null
}
};
}
// Run build if executed directly
if (require.main === module) {
build().catch(err => {
error(err.message);
});
}
module.exports = { build, getVersion };