slicejs-cli 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +260 -257
  3. package/client.js +927 -823
  4. package/commands/Print.js +163 -163
  5. package/commands/Validations.js +92 -92
  6. package/commands/build/build.js +97 -107
  7. package/commands/buildProduction/buildProduction.js +613 -613
  8. package/commands/bundle/bundle.js +251 -239
  9. package/commands/createComponent/VisualComponentTemplate.js +55 -55
  10. package/commands/createComponent/createComponent.js +128 -128
  11. package/commands/deleteComponent/deleteComponent.js +81 -81
  12. package/commands/docs/docs.js +365 -365
  13. package/commands/doctor/doctor.js +677 -563
  14. package/commands/getComponent/getComponent.js +842 -842
  15. package/commands/init/init.js +526 -475
  16. package/commands/lint/lint.js +75 -0
  17. package/commands/lint/types.js +85 -0
  18. package/commands/listComponents/listComponents.js +172 -172
  19. package/commands/seo/check.js +91 -0
  20. package/commands/seo/images.js +586 -0
  21. package/commands/seo/sitemap.js +106 -0
  22. package/commands/seo/support.js +130 -0
  23. package/commands/setup/lint.js +151 -0
  24. package/commands/skill/skill.js +236 -236
  25. package/commands/startServer/startServer.js +240 -240
  26. package/commands/startServer/watchServer.js +66 -66
  27. package/commands/typecheck/typecheck.js +83 -0
  28. package/commands/types/types.js +1378 -1097
  29. package/commands/utils/JsMinifier.js +230 -230
  30. package/commands/utils/LocalCliDelegation.js +78 -53
  31. package/commands/utils/PackageManager.js +148 -148
  32. package/commands/utils/PathHelper.js +87 -75
  33. package/commands/utils/ProjectValidation.js +274 -0
  34. package/commands/utils/SourceDiagnostics.js +201 -201
  35. package/commands/utils/VersionChecker.js +169 -169
  36. package/commands/utils/analyzeSource.js +77 -77
  37. package/commands/utils/bundling/BundleGenerator.js +3748 -3776
  38. package/commands/utils/bundling/DependencyAnalyzer.js +976 -976
  39. package/commands/utils/bundling/ExternalModuleBundler.js +298 -298
  40. package/commands/utils/componentAudit.js +74 -0
  41. package/commands/utils/compressAssets.js +103 -103
  42. package/commands/utils/cssScope.js +83 -0
  43. package/commands/utils/loadConfig.js +31 -31
  44. package/commands/utils/semver.js +66 -0
  45. package/commands/utils/sliceConfigSchema.js +72 -0
  46. package/commands/utils/sliceScripts.js +48 -48
  47. package/commands/utils/updateManager.js +471 -471
  48. package/eslint-config.js +128 -0
  49. package/package.json +19 -13
@@ -1,613 +1,613 @@
1
- // commands/buildProduction/buildProduction.js - CLEAN VERSION
2
-
3
- import fs from 'fs-extra';
4
- import path from 'path';
5
- import { createRequire } from 'module';
6
- import { minify } from 'html-minifier-terser';
7
- import CleanCSS from 'clean-css';
8
- import Print from '../Print.js';
9
- import { minifyJs, sourceFileOptions, componentsRegistryOptions } from '../utils/JsMinifier.js';
10
- import { describeSyntaxError } from '../utils/SourceDiagnostics.js';
11
- import { getSrcPath, getDistPath, getConfigPath, getProjectRoot } from '../utils/PathHelper.js';
12
- import { resolvePackageManager, runScriptCommand } from '../utils/PackageManager.js';
13
-
14
- /**
15
- * Loads configuration from sliceConfig.json
16
- */
17
- const loadConfig = () => {
18
- try {
19
- const configPath = getConfigPath(import.meta.url);
20
- const rawData = fs.readFileSync(configPath, 'utf-8');
21
- return JSON.parse(rawData);
22
- } catch (error) {
23
- Print.error(`Loading configuration: ${error.message}`);
24
- return null;
25
- }
26
- };
27
-
28
- /**
29
- * Checks necessary build dependencies
30
- */
31
- async function checkBuildDependencies() {
32
- const srcDir = getSrcPath(import.meta.url);
33
-
34
- if (!await fs.pathExists(srcDir)) {
35
- Print.error('Source directory (/src) not found');
36
- Print.info('Run "slice init" to initialize your project');
37
- return false;
38
- }
39
-
40
- try {
41
- await import('terser');
42
- await import('clean-css');
43
- await import('html-minifier-terser');
44
- Print.success('Build dependencies available');
45
- return true;
46
- } catch (error) {
47
- // This used to return true, so a build with no minifier installed reported
48
- // success while shipping every file unoptimized. They are declared
49
- // dependencies of the CLI — if they are missing the install is broken, and
50
- // saying so beats producing a build nobody knows is unoptimized.
51
- Print.error(`Build dependencies missing: ${error.message}`);
52
- Print.info('Reinstall the project dependencies, then build again.');
53
- Print.info('To build anyway with files copied unoptimized, pass --allow-unoptimized.');
54
- return false;
55
- }
56
- }
57
-
58
- /**
59
- * Verifies that critical Slice.js files exist
60
- */
61
- async function verifySliceFiles(srcDir) {
62
- Print.info('Verifying Slice.js critical files...');
63
-
64
- const criticalFiles = [
65
- 'sliceConfig.json',
66
- 'Components/components.js',
67
- 'App/index.js'
68
- ];
69
-
70
- for (const file of criticalFiles) {
71
- const filePath = path.join(srcDir, file);
72
- if (!await fs.pathExists(filePath)) {
73
- throw new Error(`Critical Slice.js file missing: ${file}`);
74
- }
75
- }
76
-
77
- Print.success('All critical Slice.js files verified');
78
- }
79
-
80
- /**
81
- * Verifies build integrity for Slice.js
82
- */
83
- async function verifyBuildIntegrity(distDir) {
84
- Print.info('Verifying build integrity for Slice.js...');
85
-
86
- const criticalBuiltFiles = [
87
- 'sliceConfig.json',
88
- 'Components/components.js',
89
- 'App/index.js'
90
- ];
91
-
92
- for (const file of criticalBuiltFiles) {
93
- const filePath = path.join(distDir, file);
94
- if (!await fs.pathExists(filePath)) {
95
- throw new Error(`Critical built file missing: ${file}`);
96
- }
97
-
98
- if (file === 'Components/components.js') {
99
- const content = await fs.readFile(filePath, 'utf8');
100
- if (!content.includes('const components') || !content.includes('export default')) {
101
- throw new Error('components.js structure corrupted during build');
102
- }
103
- }
104
- }
105
-
106
- Print.success('Build integrity verified - all Slice.js components preserved');
107
- }
108
-
109
- /**
110
- * Copies sliceConfig.json to the dist directory
111
- */
112
- async function copySliceConfig() {
113
- const srcConfig = getConfigPath(import.meta.url);
114
- const distConfig = getDistPath(import.meta.url, 'sliceConfig.json');
115
-
116
- if (await fs.pathExists(srcConfig)) {
117
- await fs.copy(srcConfig, distConfig);
118
- Print.info('sliceConfig.json copied to dist');
119
- }
120
- }
121
-
122
- /**
123
- * Copies the Slice.js framework runtime entry into dist so the production build
124
- * is self-contained.
125
- *
126
- * The app bootstraps with `import Slice from '/Slice/Slice.js'`, which the server
127
- * serves in production. Reading it from node_modules at runtime is unreliable on
128
- * serverless platforms (Vercel only ships traced imports + `includeFiles: dist/**`,
129
- * and pnpm stores the package behind a symlink), so we emit a physical copy into
130
- * `dist/Slice/Slice.js`. The package's "." export resolves to that single,
131
- * self-contained bundle; resolution is done from the *project* root so the
132
- * project's installed framework is used (following pnpm symlinks to the real file).
133
- */
134
- async function copyFrameworkRuntime() {
135
- const projectRoot = getProjectRoot(import.meta.url);
136
- try {
137
- const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
138
- const frameworkEntry = projectRequire.resolve('slicejs-web-framework');
139
- const distSlice = getDistPath(import.meta.url, 'Slice', 'Slice.js');
140
-
141
- await fs.ensureDir(path.dirname(distSlice));
142
- await fs.copy(frameworkEntry, distSlice);
143
-
144
- const stat = await fs.stat(distSlice);
145
- Print.info(`Framework runtime bundled to dist/Slice/Slice.js (${(stat.size / 1024).toFixed(1)} KB)`);
146
- } catch (error) {
147
- Print.warning(`Could not bundle framework runtime into dist: ${error.message}`);
148
- Print.warning('Production servers that serve /Slice/Slice.js from dist may 404 until this is resolved.');
149
- }
150
- }
151
-
152
- /**
153
- * Processes a complete directory
154
- */
155
- async function processDirectory(srcPath, distPath, baseSrcPath, options) {
156
- // Sorted, not raw readdir order: readdir gives no ordering guarantee and it
157
- // varies by filesystem, so an unstable walk would make build output and its
158
- // logs differ between machines. Cheap insurance for reproducible builds and
159
- // any content-hash caching built on them.
160
- const items = (await fs.readdir(srcPath)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
161
-
162
- for (const item of items) {
163
- const srcItemPath = path.join(srcPath, item);
164
- const distItemPath = path.join(distPath, item);
165
- const stat = await fs.stat(srcItemPath);
166
-
167
- if (stat.isDirectory()) {
168
- await fs.ensureDir(distItemPath);
169
- await processDirectory(srcItemPath, distItemPath, baseSrcPath, options);
170
- } else {
171
- await processFile(srcItemPath, distItemPath, options);
172
- }
173
- }
174
- }
175
-
176
- // Files that could not be optimized and were copied through instead. A build
177
- // that quietly degrades is worse than one that fails: every one of the bundler
178
- // bugs found so far shipped unoptimized output behind a red line nobody read.
179
- // Reset per build (buildProduction) and reported before it returns.
180
- let degradations = [];
181
-
182
-
183
- function resetDegradations() {
184
- degradations = [];
185
- }
186
-
187
-
188
- function recordDegradation(entry) {
189
- degradations.push(entry);
190
- }
191
-
192
- /**
193
- * Prints what fell back, if anything.
194
- * @returns {boolean} true when the build was fully optimized
195
- */
196
- function reportDegradations() {
197
- if (degradations.length === 0) return true;
198
-
199
- Print.newLine();
200
- Print.error(`${degradations.length} file(s) could not be optimized and were copied unoptimized:`);
201
- for (const { file, reason } of degradations) {
202
- console.log(` • ${file}: ${reason}`);
203
- }
204
- Print.newLine();
205
- Print.info('These files ship as-is: unminified, comments and all. Fix the cause, or');
206
- Print.info('pass --allow-unoptimized to accept it and let the build succeed.');
207
- return false;
208
- }
209
-
210
- /**
211
- * Processes an individual file
212
- */
213
- async function processFile(srcFilePath, distFilePath, options) {
214
- const ext = path.extname(srcFilePath).toLowerCase();
215
- const fileName = path.basename(srcFilePath);
216
- const isBundleConfig = fileName === 'bundle.config.json' || fileName === 'bundle.config.js';
217
- const isBundleFolder = srcFilePath.includes(`${path.sep}bundles${path.sep}`);
218
-
219
- if (isBundleConfig && isBundleFolder) {
220
- const renamed = fileName.replace('bundle.config', 'bundle.build.config');
221
- distFilePath = path.join(path.dirname(distFilePath), renamed);
222
- }
223
-
224
- try {
225
- if (fileName === 'components.js') {
226
- if (options?.minify === false) {
227
- await fs.copy(srcFilePath, distFilePath);
228
- const stat = await fs.stat(srcFilePath);
229
- const sizeKB = (stat.size / 1024).toFixed(1);
230
- Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
231
- } else {
232
- await processComponentsFile(srcFilePath, distFilePath);
233
- }
234
- } else if (ext === '.js') {
235
- if (options?.minify === false) {
236
- await fs.copy(srcFilePath, distFilePath);
237
- const stat = await fs.stat(srcFilePath);
238
- const sizeKB = (stat.size / 1024).toFixed(1);
239
- Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
240
- } else {
241
- await minifyJavaScript(srcFilePath, distFilePath);
242
- }
243
- } else if (ext === '.css') {
244
- if (options?.minify === false) {
245
- await fs.copy(srcFilePath, distFilePath);
246
- const stat = await fs.stat(srcFilePath);
247
- const sizeKB = (stat.size / 1024).toFixed(1);
248
- Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
249
- } else {
250
- await minifyCSS(srcFilePath, distFilePath);
251
- }
252
- } else if (ext === '.html') {
253
- if (options?.minify === false) {
254
- await fs.copy(srcFilePath, distFilePath);
255
- const stat = await fs.stat(srcFilePath);
256
- const sizeKB = (stat.size / 1024).toFixed(1);
257
- Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
258
- } else {
259
- await minifyHTML(srcFilePath, distFilePath);
260
- }
261
- } else if (fileName === 'sliceConfig.json') {
262
- await fs.copy(srcFilePath, distFilePath);
263
- Print.info(`📄 Preserved: ${fileName} (configuration file)`);
264
- } else {
265
- await fs.copy(srcFilePath, distFilePath);
266
- const stat = await fs.stat(srcFilePath);
267
- const sizeKB = (stat.size / 1024).toFixed(1);
268
- Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
269
- }
270
- } catch (error) {
271
- // Copying the source through keeps the build usable, but the file ships
272
- // unoptimized — and this used to be the whole story: a red line in the
273
- // middle of a green build. Record it so the build can report and fail on it.
274
- Print.error(`Processing ${fileName}: ${error.message}`);
275
- recordDegradation({
276
- file: path.relative(getSrcPath(import.meta.url), srcFilePath) || fileName,
277
- reason: error.message
278
- });
279
- await fs.copy(srcFilePath, distFilePath);
280
- }
281
- }
282
-
283
- /**
284
- * Processes the components.js file in a special way
285
- */
286
- async function processComponentsFile(srcPath, distPath) {
287
- const content = await fs.readFile(srcPath, 'utf8');
288
- const originalSize = Buffer.byteLength(content, 'utf8');
289
-
290
- const result = await minifyJs(content, componentsRegistryOptions);
291
-
292
- await fs.writeFile(distPath, result.code, 'utf8');
293
-
294
- const minifiedSize = Buffer.byteLength(result.code, 'utf8');
295
- const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);
296
-
297
- Print.minificationResult(`${path.basename(srcPath)} (preserved structure)`, originalSize, minifiedSize, savings);
298
- }
299
-
300
- /**
301
- * Minifies JavaScript files preserving Slice.js architecture
302
- */
303
- async function minifyJavaScript(srcPath, distPath) {
304
- const content = await fs.readFile(srcPath, 'utf8');
305
- const originalSize = Buffer.byteLength(content, 'utf8');
306
-
307
- let result;
308
- try {
309
- result = await minifyJs(content, sourceFileOptions);
310
- } catch (minifyError) {
311
- // Terser reports its own parse failures without a location and in its own
312
- // vocabulary ("Unexpected token punc «(»"). When the file simply does not
313
- // parse, say so against the developer's source instead.
314
- const diagnosis = describeSyntaxError(content, srcPath);
315
- if (!diagnosis.ok) {
316
- throw new Error(`Syntax error at ${diagnosis.message}\nFix the source above.`);
317
- }
318
- throw minifyError;
319
- }
320
-
321
- await fs.writeFile(distPath, result.code, 'utf8');
322
-
323
- const minifiedSize = Buffer.byteLength(result.code, 'utf8');
324
- const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);
325
-
326
- Print.minificationResult(path.basename(srcPath), originalSize, minifiedSize, savings);
327
- }
328
-
329
- /**
330
- * Minifies CSS files
331
- */
332
- async function minifyCSS(srcPath, distPath) {
333
- const content = await fs.readFile(srcPath, 'utf8');
334
- const originalSize = Buffer.byteLength(content, 'utf8');
335
-
336
- const cleanCSS = new CleanCSS({
337
- level: 2,
338
- returnPromise: false
339
- });
340
-
341
- const result = cleanCSS.minify(content);
342
-
343
- if (result.errors.length > 0) {
344
- throw new Error(`CleanCSS errors: ${result.errors.join(', ')}`);
345
- }
346
-
347
- await fs.writeFile(distPath, result.styles, 'utf8');
348
-
349
- const minifiedSize = Buffer.byteLength(result.styles, 'utf8');
350
- const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);
351
-
352
- Print.minificationResult(path.basename(srcPath), originalSize, minifiedSize, savings);
353
- }
354
-
355
- /**
356
- * Minifies HTML files
357
- */
358
- async function minifyHTML(srcPath, distPath) {
359
- const content = await fs.readFile(srcPath, 'utf8');
360
- const originalSize = Buffer.byteLength(content, 'utf8');
361
-
362
- const minified = await minify(content, {
363
- collapseWhitespace: true,
364
- removeComments: true,
365
- removeRedundantAttributes: true,
366
- removeScriptTypeAttributes: true,
367
- removeStyleLinkTypeAttributes: true,
368
- useShortDoctype: true,
369
- minifyCSS: true,
370
- minifyJS: {
371
- mangle: {
372
- reserved: ['slice', 'Slice', 'SliceJS', 'sliceId', 'sliceConfig']
373
- }
374
- },
375
- ignoreCustomFragments: [
376
- /slice-[\w-]+="[^"]*"/g
377
- ]
378
- });
379
-
380
- await fs.writeFile(distPath, minified, 'utf8');
381
-
382
- const minifiedSize = Buffer.byteLength(minified, 'utf8');
383
- const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);
384
-
385
- Print.minificationResult(path.basename(srcPath), originalSize, minifiedSize, savings);
386
- }
387
-
388
- /**
389
- * Creates an optimized bundle of the main file
390
- */
391
- async function createOptimizedBundle() {
392
- Print.buildProgress('Creating optimized bundle...');
393
-
394
- const mainJSPath = getDistPath(import.meta.url, 'App', 'index.js');
395
-
396
- if (await fs.pathExists(mainJSPath)) {
397
- Print.success('Main bundle optimized');
398
- } else {
399
- Print.warning('No main JavaScript file found for bundling');
400
- }
401
- }
402
-
403
- /**
404
- * Generates build statistics
405
- */
406
- async function generateBuildStats(srcDir, distDir) {
407
- Print.buildProgress('Generating build statistics...');
408
-
409
- const getDirectorySize = async (dirPath) => {
410
- let totalSize = 0;
411
- const items = await fs.readdir(dirPath);
412
-
413
- for (const item of items) {
414
- const itemPath = path.join(dirPath, item);
415
- const stat = await fs.stat(itemPath);
416
-
417
- if (stat.isDirectory()) {
418
- totalSize += await getDirectorySize(itemPath);
419
- } else {
420
- totalSize += stat.size;
421
- }
422
- }
423
-
424
- return totalSize;
425
- };
426
-
427
- try {
428
- const srcSize = await getDirectorySize(srcDir);
429
- const distSize = await getDirectorySize(distDir);
430
- const savings = Math.round(((srcSize - distSize) / srcSize) * 100);
431
-
432
- Print.newLine();
433
- Print.info(`📊 Build Statistics:`);
434
- console.log(` Source: ${(srcSize / 1024).toFixed(1)} KB`);
435
- console.log(` Built: ${(distSize / 1024).toFixed(1)} KB`);
436
- console.log(` Saved: ${savings}% smaller`);
437
-
438
- } catch (error) {
439
- Print.warning('Could not generate build statistics');
440
- }
441
- }
442
-
443
- /**
444
- * Analyzes the build without building
445
- */
446
- async function analyzeBuild() {
447
- const distDir = getDistPath(import.meta.url);
448
-
449
- if (!await fs.pathExists(distDir)) {
450
- Print.error('No build found to analyze. Run "slice build" first.');
451
- return;
452
- }
453
-
454
- Print.info('Analyzing production build...');
455
- await generateBuildStats(
456
- getSrcPath(import.meta.url),
457
- distDir
458
- );
459
- }
460
-
461
- /**
462
- * MAIN BUILD FUNCTION
463
- */
464
- export default async function buildProduction(options = {}) {
465
- const startTime = Date.now();
466
- const packageManager = resolvePackageManager(getProjectRoot(import.meta.url)).name;
467
- resetDegradations();
468
-
469
- try {
470
- Print.title('🔨 Building Slice.js project for production...');
471
- Print.newLine();
472
-
473
- const srcDir = getSrcPath(import.meta.url);
474
- const distDir = getDistPath(import.meta.url);
475
-
476
- if (!await fs.pathExists(srcDir)) {
477
- throw new Error('Source directory not found. Run "slice init" first.');
478
- }
479
-
480
- await verifySliceFiles(srcDir);
481
-
482
- // Clean dist directory
483
- if (await fs.pathExists(distDir)) {
484
- if (!options.skipClean) {
485
- Print.info('Cleaning previous build...');
486
- await fs.remove(distDir);
487
- Print.success('Previous build cleaned');
488
- }
489
- }
490
-
491
- await fs.ensureDir(distDir);
492
- await copySliceConfig();
493
-
494
- // Process files
495
- Print.info('Processing and optimizing source files for Slice.js...');
496
- await processDirectory(srcDir, distDir, srcDir, options);
497
- Print.success('All source files processed and optimized');
498
-
499
- // Make dist self-contained: the framework runtime the app imports at
500
- // /Slice/Slice.js must live under dist so it ships with serverless deploys.
501
- await copyFrameworkRuntime();
502
-
503
- await verifyBuildIntegrity(distDir);
504
- await createOptimizedBundle();
505
- await generateBuildStats(srcDir, distDir);
506
-
507
- const fullyOptimized = reportDegradations();
508
- if (!fullyOptimized && !options.allowUnoptimized) {
509
- Print.error('Build failed: not every file could be optimized (see above).');
510
- return false;
511
- }
512
-
513
- const buildTime = ((Date.now() - startTime) / 1000).toFixed(1);
514
-
515
- Print.newLine();
516
- Print.success(`✨ Slice.js production build completed in ${buildTime}s`);
517
- Print.info('Your optimized project is ready in the /dist directory');
518
- Print.newLine();
519
- Print.info('Next steps:');
520
- console.log(` • Use "${runScriptCommand(packageManager, 'start')}" to test the production build`);
521
- console.log(' • All Slice.js components and architecture preserved');
522
-
523
- return true;
524
-
525
- } catch (error) {
526
- Print.error(`Build failed: ${error.message}`);
527
- return false;
528
- }
529
- }
530
-
531
- /**
532
- * Preview server for testing the production build
533
- */
534
- export async function serveProductionBuild(port) {
535
- try {
536
- const packageManager = resolvePackageManager(getProjectRoot(import.meta.url)).name;
537
- const config = loadConfig();
538
- const defaultPort = config?.server?.port || 3001;
539
- const finalPort = port || defaultPort;
540
-
541
- const distDir = getDistPath(import.meta.url);
542
-
543
- if (!await fs.pathExists(distDir)) {
544
- throw new Error('No production build found. Run "slice build" first.');
545
- }
546
-
547
- Print.info(`Starting production preview server on port ${finalPort}...`);
548
-
549
- const express = await import('express');
550
- const app = express.default();
551
-
552
- app.use(express.default.static(distDir));
553
-
554
- app.get('*', (req, res) => {
555
- const indexPath = path.join(distDir, 'App/index.html');
556
- const fallbackPath = path.join(distDir, 'index.html');
557
-
558
- if (fs.existsSync(indexPath)) {
559
- res.sendFile(indexPath);
560
- } else if (fs.existsSync(fallbackPath)) {
561
- res.sendFile(fallbackPath);
562
- } else {
563
- res.status(404).send('Production build index.html not found');
564
- }
565
- });
566
-
567
- app.listen(finalPort, () => {
568
- Print.success(`Production preview server running at http://localhost:${finalPort}`);
569
- Print.info('Press Ctrl+C to stop the server');
570
- Print.info('This server previews your production build from /dist');
571
- Print.warning(`This is a preview server - use "${runScriptCommand(packageManager, 'start')}" for the full production server`);
572
- });
573
-
574
- } catch (error) {
575
- Print.error(`Error starting production preview server: ${error.message}`);
576
- throw error;
577
- }
578
- }
579
-
580
- /**
581
- * Build command with options
582
- */
583
- export async function buildCommand(options = {}) {
584
- const config = loadConfig();
585
- const defaultPort = config?.server?.port || 3001;
586
-
587
- // Missing minifiers are fatal unless the caller explicitly accepts an
588
- // unoptimized build.
589
- if (!await checkBuildDependencies() && !options.allowUnoptimized) {
590
- return false;
591
- }
592
-
593
- if (options.serve) {
594
- await serveProductionBuild(options.port || defaultPort);
595
- return true;
596
- }
597
-
598
- if (options.analyze) {
599
- await analyzeBuild();
600
- return true;
601
- }
602
-
603
- const success = await buildProduction(options);
604
-
605
- if (success && options.preview) {
606
- Print.newLine();
607
- Print.info('✨ Build completed successfully!');
608
- Print.info(`Starting preview server on port ${options.port || defaultPort}...`);
609
- await serveProductionBuild(options.port || defaultPort);
610
- }
611
-
612
- return success;
613
- }
1
+ // commands/buildProduction/buildProduction.js - CLEAN VERSION
2
+
3
+ import fs from 'fs-extra';
4
+ import path from 'path';
5
+ import { createRequire } from 'module';
6
+ import { minify } from 'html-minifier-terser';
7
+ import CleanCSS from 'clean-css';
8
+ import Print from '../Print.js';
9
+ import { minifyJs, sourceFileOptions, componentsRegistryOptions } from '../utils/JsMinifier.js';
10
+ import { describeSyntaxError } from '../utils/SourceDiagnostics.js';
11
+ import { getSrcPath, getDistPath, getConfigPath, getProjectRoot } from '../utils/PathHelper.js';
12
+ import { resolvePackageManager, runScriptCommand } from '../utils/PackageManager.js';
13
+
14
+ /**
15
+ * Loads configuration from sliceConfig.json
16
+ */
17
+ const loadConfig = () => {
18
+ try {
19
+ const configPath = getConfigPath(import.meta.url);
20
+ const rawData = fs.readFileSync(configPath, 'utf-8');
21
+ return JSON.parse(rawData);
22
+ } catch (error) {
23
+ Print.error(`Loading configuration: ${error.message}`);
24
+ return null;
25
+ }
26
+ };
27
+
28
+ /**
29
+ * Checks necessary build dependencies
30
+ */
31
+ async function checkBuildDependencies() {
32
+ const srcDir = getSrcPath(import.meta.url);
33
+
34
+ if (!await fs.pathExists(srcDir)) {
35
+ Print.error('Source directory (/src) not found');
36
+ Print.info('Run "slice init" to initialize your project');
37
+ return false;
38
+ }
39
+
40
+ try {
41
+ await import('terser');
42
+ await import('clean-css');
43
+ await import('html-minifier-terser');
44
+ Print.success('Build dependencies available');
45
+ return true;
46
+ } catch (error) {
47
+ // This used to return true, so a build with no minifier installed reported
48
+ // success while shipping every file unoptimized. They are declared
49
+ // dependencies of the CLI — if they are missing the install is broken, and
50
+ // saying so beats producing a build nobody knows is unoptimized.
51
+ Print.error(`Build dependencies missing: ${error.message}`);
52
+ Print.info('Reinstall the project dependencies, then build again.');
53
+ Print.info('To build anyway with files copied unoptimized, pass --allow-unoptimized.');
54
+ return false;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Verifies that critical Slice.js files exist
60
+ */
61
+ async function verifySliceFiles(srcDir) {
62
+ Print.info('Verifying Slice.js critical files...');
63
+
64
+ const criticalFiles = [
65
+ 'sliceConfig.json',
66
+ 'Components/components.js',
67
+ 'App/index.js'
68
+ ];
69
+
70
+ for (const file of criticalFiles) {
71
+ const filePath = path.join(srcDir, file);
72
+ if (!await fs.pathExists(filePath)) {
73
+ throw new Error(`Critical Slice.js file missing: ${file}`);
74
+ }
75
+ }
76
+
77
+ Print.success('All critical Slice.js files verified');
78
+ }
79
+
80
+ /**
81
+ * Verifies build integrity for Slice.js
82
+ */
83
+ async function verifyBuildIntegrity(distDir) {
84
+ Print.info('Verifying build integrity for Slice.js...');
85
+
86
+ const criticalBuiltFiles = [
87
+ 'sliceConfig.json',
88
+ 'Components/components.js',
89
+ 'App/index.js'
90
+ ];
91
+
92
+ for (const file of criticalBuiltFiles) {
93
+ const filePath = path.join(distDir, file);
94
+ if (!await fs.pathExists(filePath)) {
95
+ throw new Error(`Critical built file missing: ${file}`);
96
+ }
97
+
98
+ if (file === 'Components/components.js') {
99
+ const content = await fs.readFile(filePath, 'utf8');
100
+ if (!content.includes('const components') || !content.includes('export default')) {
101
+ throw new Error('components.js structure corrupted during build');
102
+ }
103
+ }
104
+ }
105
+
106
+ Print.success('Build integrity verified - all Slice.js components preserved');
107
+ }
108
+
109
+ /**
110
+ * Copies sliceConfig.json to the dist directory
111
+ */
112
+ async function copySliceConfig() {
113
+ const srcConfig = getConfigPath(import.meta.url);
114
+ const distConfig = getDistPath(import.meta.url, 'sliceConfig.json');
115
+
116
+ if (await fs.pathExists(srcConfig)) {
117
+ await fs.copy(srcConfig, distConfig);
118
+ Print.info('sliceConfig.json copied to dist');
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Copies the Slice.js framework runtime entry into dist so the production build
124
+ * is self-contained.
125
+ *
126
+ * The app bootstraps with `import Slice from '/Slice/Slice.js'`, which the server
127
+ * serves in production. Reading it from node_modules at runtime is unreliable on
128
+ * serverless platforms (Vercel only ships traced imports + `includeFiles: dist/**`,
129
+ * and pnpm stores the package behind a symlink), so we emit a physical copy into
130
+ * `dist/Slice/Slice.js`. The package's "." export resolves to that single,
131
+ * self-contained bundle; resolution is done from the *project* root so the
132
+ * project's installed framework is used (following pnpm symlinks to the real file).
133
+ */
134
+ async function copyFrameworkRuntime() {
135
+ const projectRoot = getProjectRoot(import.meta.url);
136
+ try {
137
+ const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
138
+ const frameworkEntry = projectRequire.resolve('slicejs-web-framework');
139
+ const distSlice = getDistPath(import.meta.url, 'Slice', 'Slice.js');
140
+
141
+ await fs.ensureDir(path.dirname(distSlice));
142
+ await fs.copy(frameworkEntry, distSlice);
143
+
144
+ const stat = await fs.stat(distSlice);
145
+ Print.info(`Framework runtime bundled to dist/Slice/Slice.js (${(stat.size / 1024).toFixed(1)} KB)`);
146
+ } catch (error) {
147
+ Print.warning(`Could not bundle framework runtime into dist: ${error.message}`);
148
+ Print.warning('Production servers that serve /Slice/Slice.js from dist may 404 until this is resolved.');
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Processes a complete directory
154
+ */
155
+ async function processDirectory(srcPath, distPath, baseSrcPath, options) {
156
+ // Sorted, not raw readdir order: readdir gives no ordering guarantee and it
157
+ // varies by filesystem, so an unstable walk would make build output and its
158
+ // logs differ between machines. Cheap insurance for reproducible builds and
159
+ // any content-hash caching built on them.
160
+ const items = (await fs.readdir(srcPath)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
161
+
162
+ for (const item of items) {
163
+ const srcItemPath = path.join(srcPath, item);
164
+ const distItemPath = path.join(distPath, item);
165
+ const stat = await fs.stat(srcItemPath);
166
+
167
+ if (stat.isDirectory()) {
168
+ await fs.ensureDir(distItemPath);
169
+ await processDirectory(srcItemPath, distItemPath, baseSrcPath, options);
170
+ } else {
171
+ await processFile(srcItemPath, distItemPath, options);
172
+ }
173
+ }
174
+ }
175
+
176
+ // Files that could not be optimized and were copied through instead. A build
177
+ // that quietly degrades is worse than one that fails: every one of the bundler
178
+ // bugs found so far shipped unoptimized output behind a red line nobody read.
179
+ // Reset per build (buildProduction) and reported before it returns.
180
+ let degradations = [];
181
+
182
+
183
+ function resetDegradations() {
184
+ degradations = [];
185
+ }
186
+
187
+
188
+ function recordDegradation(entry) {
189
+ degradations.push(entry);
190
+ }
191
+
192
+ /**
193
+ * Prints what fell back, if anything.
194
+ * @returns {boolean} true when the build was fully optimized
195
+ */
196
+ function reportDegradations() {
197
+ if (degradations.length === 0) return true;
198
+
199
+ Print.newLine();
200
+ Print.error(`${degradations.length} file(s) could not be optimized and were copied unoptimized:`);
201
+ for (const { file, reason } of degradations) {
202
+ console.log(` • ${file}: ${reason}`);
203
+ }
204
+ Print.newLine();
205
+ Print.info('These files ship as-is: unminified, comments and all. Fix the cause, or');
206
+ Print.info('pass --allow-unoptimized to accept it and let the build succeed.');
207
+ return false;
208
+ }
209
+
210
+ /**
211
+ * Processes an individual file
212
+ */
213
+ async function processFile(srcFilePath, distFilePath, options) {
214
+ const ext = path.extname(srcFilePath).toLowerCase();
215
+ const fileName = path.basename(srcFilePath);
216
+ const isBundleConfig = fileName === 'bundle.config.json' || fileName === 'bundle.config.js';
217
+ const isBundleFolder = srcFilePath.includes(`${path.sep}bundles${path.sep}`);
218
+
219
+ if (isBundleConfig && isBundleFolder) {
220
+ const renamed = fileName.replace('bundle.config', 'bundle.build.config');
221
+ distFilePath = path.join(path.dirname(distFilePath), renamed);
222
+ }
223
+
224
+ try {
225
+ if (fileName === 'components.js') {
226
+ if (options?.minify === false) {
227
+ await fs.copy(srcFilePath, distFilePath);
228
+ const stat = await fs.stat(srcFilePath);
229
+ const sizeKB = (stat.size / 1024).toFixed(1);
230
+ Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
231
+ } else {
232
+ await processComponentsFile(srcFilePath, distFilePath);
233
+ }
234
+ } else if (ext === '.js') {
235
+ if (options?.minify === false) {
236
+ await fs.copy(srcFilePath, distFilePath);
237
+ const stat = await fs.stat(srcFilePath);
238
+ const sizeKB = (stat.size / 1024).toFixed(1);
239
+ Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
240
+ } else {
241
+ await minifyJavaScript(srcFilePath, distFilePath);
242
+ }
243
+ } else if (ext === '.css') {
244
+ if (options?.minify === false) {
245
+ await fs.copy(srcFilePath, distFilePath);
246
+ const stat = await fs.stat(srcFilePath);
247
+ const sizeKB = (stat.size / 1024).toFixed(1);
248
+ Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
249
+ } else {
250
+ await minifyCSS(srcFilePath, distFilePath);
251
+ }
252
+ } else if (ext === '.html') {
253
+ if (options?.minify === false) {
254
+ await fs.copy(srcFilePath, distFilePath);
255
+ const stat = await fs.stat(srcFilePath);
256
+ const sizeKB = (stat.size / 1024).toFixed(1);
257
+ Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
258
+ } else {
259
+ await minifyHTML(srcFilePath, distFilePath);
260
+ }
261
+ } else if (fileName === 'sliceConfig.json') {
262
+ await fs.copy(srcFilePath, distFilePath);
263
+ Print.info(`📄 Preserved: ${fileName} (configuration file)`);
264
+ } else {
265
+ await fs.copy(srcFilePath, distFilePath);
266
+ const stat = await fs.stat(srcFilePath);
267
+ const sizeKB = (stat.size / 1024).toFixed(1);
268
+ Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
269
+ }
270
+ } catch (error) {
271
+ // Copying the source through keeps the build usable, but the file ships
272
+ // unoptimized — and this used to be the whole story: a red line in the
273
+ // middle of a green build. Record it so the build can report and fail on it.
274
+ Print.error(`Processing ${fileName}: ${error.message}`);
275
+ recordDegradation({
276
+ file: path.relative(getSrcPath(import.meta.url), srcFilePath) || fileName,
277
+ reason: error.message
278
+ });
279
+ await fs.copy(srcFilePath, distFilePath);
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Processes the components.js file in a special way
285
+ */
286
+ async function processComponentsFile(srcPath, distPath) {
287
+ const content = await fs.readFile(srcPath, 'utf8');
288
+ const originalSize = Buffer.byteLength(content, 'utf8');
289
+
290
+ const result = await minifyJs(content, componentsRegistryOptions);
291
+
292
+ await fs.writeFile(distPath, result.code, 'utf8');
293
+
294
+ const minifiedSize = Buffer.byteLength(result.code, 'utf8');
295
+ const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);
296
+
297
+ Print.minificationResult(`${path.basename(srcPath)} (preserved structure)`, originalSize, minifiedSize, savings);
298
+ }
299
+
300
+ /**
301
+ * Minifies JavaScript files preserving Slice.js architecture
302
+ */
303
+ async function minifyJavaScript(srcPath, distPath) {
304
+ const content = await fs.readFile(srcPath, 'utf8');
305
+ const originalSize = Buffer.byteLength(content, 'utf8');
306
+
307
+ let result;
308
+ try {
309
+ result = await minifyJs(content, sourceFileOptions);
310
+ } catch (minifyError) {
311
+ // Terser reports its own parse failures without a location and in its own
312
+ // vocabulary ("Unexpected token punc «(»"). When the file simply does not
313
+ // parse, say so against the developer's source instead.
314
+ const diagnosis = describeSyntaxError(content, srcPath);
315
+ if (!diagnosis.ok) {
316
+ throw new Error(`Syntax error at ${diagnosis.message}\nFix the source above.`, { cause: minifyError });
317
+ }
318
+ throw minifyError;
319
+ }
320
+
321
+ await fs.writeFile(distPath, result.code, 'utf8');
322
+
323
+ const minifiedSize = Buffer.byteLength(result.code, 'utf8');
324
+ const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);
325
+
326
+ Print.minificationResult(path.basename(srcPath), originalSize, minifiedSize, savings);
327
+ }
328
+
329
+ /**
330
+ * Minifies CSS files
331
+ */
332
+ async function minifyCSS(srcPath, distPath) {
333
+ const content = await fs.readFile(srcPath, 'utf8');
334
+ const originalSize = Buffer.byteLength(content, 'utf8');
335
+
336
+ const cleanCSS = new CleanCSS({
337
+ level: 2,
338
+ returnPromise: false
339
+ });
340
+
341
+ const result = cleanCSS.minify(content);
342
+
343
+ if (result.errors.length > 0) {
344
+ throw new Error(`CleanCSS errors: ${result.errors.join(', ')}`);
345
+ }
346
+
347
+ await fs.writeFile(distPath, result.styles, 'utf8');
348
+
349
+ const minifiedSize = Buffer.byteLength(result.styles, 'utf8');
350
+ const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);
351
+
352
+ Print.minificationResult(path.basename(srcPath), originalSize, minifiedSize, savings);
353
+ }
354
+
355
+ /**
356
+ * Minifies HTML files
357
+ */
358
+ async function minifyHTML(srcPath, distPath) {
359
+ const content = await fs.readFile(srcPath, 'utf8');
360
+ const originalSize = Buffer.byteLength(content, 'utf8');
361
+
362
+ const minified = await minify(content, {
363
+ collapseWhitespace: true,
364
+ removeComments: true,
365
+ removeRedundantAttributes: true,
366
+ removeScriptTypeAttributes: true,
367
+ removeStyleLinkTypeAttributes: true,
368
+ useShortDoctype: true,
369
+ minifyCSS: true,
370
+ minifyJS: {
371
+ mangle: {
372
+ reserved: ['slice', 'Slice', 'SliceJS', 'sliceId', 'sliceConfig']
373
+ }
374
+ },
375
+ ignoreCustomFragments: [
376
+ /slice-[\w-]+="[^"]*"/g
377
+ ]
378
+ });
379
+
380
+ await fs.writeFile(distPath, minified, 'utf8');
381
+
382
+ const minifiedSize = Buffer.byteLength(minified, 'utf8');
383
+ const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);
384
+
385
+ Print.minificationResult(path.basename(srcPath), originalSize, minifiedSize, savings);
386
+ }
387
+
388
+ /**
389
+ * Creates an optimized bundle of the main file
390
+ */
391
+ async function createOptimizedBundle() {
392
+ Print.buildProgress('Creating optimized bundle...');
393
+
394
+ const mainJSPath = getDistPath(import.meta.url, 'App', 'index.js');
395
+
396
+ if (await fs.pathExists(mainJSPath)) {
397
+ Print.success('Main bundle optimized');
398
+ } else {
399
+ Print.warning('No main JavaScript file found for bundling');
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Generates build statistics
405
+ */
406
+ async function generateBuildStats(srcDir, distDir) {
407
+ Print.buildProgress('Generating build statistics...');
408
+
409
+ const getDirectorySize = async (dirPath) => {
410
+ let totalSize = 0;
411
+ const items = await fs.readdir(dirPath);
412
+
413
+ for (const item of items) {
414
+ const itemPath = path.join(dirPath, item);
415
+ const stat = await fs.stat(itemPath);
416
+
417
+ if (stat.isDirectory()) {
418
+ totalSize += await getDirectorySize(itemPath);
419
+ } else {
420
+ totalSize += stat.size;
421
+ }
422
+ }
423
+
424
+ return totalSize;
425
+ };
426
+
427
+ try {
428
+ const srcSize = await getDirectorySize(srcDir);
429
+ const distSize = await getDirectorySize(distDir);
430
+ const savings = Math.round(((srcSize - distSize) / srcSize) * 100);
431
+
432
+ Print.newLine();
433
+ Print.info(`📊 Build Statistics:`);
434
+ console.log(` Source: ${(srcSize / 1024).toFixed(1)} KB`);
435
+ console.log(` Built: ${(distSize / 1024).toFixed(1)} KB`);
436
+ console.log(` Saved: ${savings}% smaller`);
437
+
438
+ } catch (error) {
439
+ Print.warning('Could not generate build statistics');
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Analyzes the build without building
445
+ */
446
+ async function analyzeBuild() {
447
+ const distDir = getDistPath(import.meta.url);
448
+
449
+ if (!await fs.pathExists(distDir)) {
450
+ Print.error('No build found to analyze. Run "slice build" first.');
451
+ return;
452
+ }
453
+
454
+ Print.info('Analyzing production build...');
455
+ await generateBuildStats(
456
+ getSrcPath(import.meta.url),
457
+ distDir
458
+ );
459
+ }
460
+
461
+ /**
462
+ * MAIN BUILD FUNCTION
463
+ */
464
+ export default async function buildProduction(options = {}) {
465
+ const startTime = Date.now();
466
+ const packageManager = resolvePackageManager(getProjectRoot(import.meta.url)).name;
467
+ resetDegradations();
468
+
469
+ try {
470
+ Print.title('🔨 Building Slice.js project for production...');
471
+ Print.newLine();
472
+
473
+ const srcDir = getSrcPath(import.meta.url);
474
+ const distDir = getDistPath(import.meta.url);
475
+
476
+ if (!await fs.pathExists(srcDir)) {
477
+ throw new Error('Source directory not found. Run "slice init" first.');
478
+ }
479
+
480
+ await verifySliceFiles(srcDir);
481
+
482
+ // Clean dist directory
483
+ if (await fs.pathExists(distDir)) {
484
+ if (!options.skipClean) {
485
+ Print.info('Cleaning previous build...');
486
+ await fs.remove(distDir);
487
+ Print.success('Previous build cleaned');
488
+ }
489
+ }
490
+
491
+ await fs.ensureDir(distDir);
492
+ await copySliceConfig();
493
+
494
+ // Process files
495
+ Print.info('Processing and optimizing source files for Slice.js...');
496
+ await processDirectory(srcDir, distDir, srcDir, options);
497
+ Print.success('All source files processed and optimized');
498
+
499
+ // Make dist self-contained: the framework runtime the app imports at
500
+ // /Slice/Slice.js must live under dist so it ships with serverless deploys.
501
+ await copyFrameworkRuntime();
502
+
503
+ await verifyBuildIntegrity(distDir);
504
+ await createOptimizedBundle();
505
+ await generateBuildStats(srcDir, distDir);
506
+
507
+ const fullyOptimized = reportDegradations();
508
+ if (!fullyOptimized && !options.allowUnoptimized) {
509
+ Print.error('Build failed: not every file could be optimized (see above).');
510
+ return false;
511
+ }
512
+
513
+ const buildTime = ((Date.now() - startTime) / 1000).toFixed(1);
514
+
515
+ Print.newLine();
516
+ Print.success(`✨ Slice.js production build completed in ${buildTime}s`);
517
+ Print.info('Your optimized project is ready in the /dist directory');
518
+ Print.newLine();
519
+ Print.info('Next steps:');
520
+ console.log(` • Use "${runScriptCommand(packageManager, 'start')}" to test the production build`);
521
+ console.log(' • All Slice.js components and architecture preserved');
522
+
523
+ return true;
524
+
525
+ } catch (error) {
526
+ Print.error(`Build failed: ${error.message}`);
527
+ return false;
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Preview server for testing the production build
533
+ */
534
+ export async function serveProductionBuild(port) {
535
+ try {
536
+ const packageManager = resolvePackageManager(getProjectRoot(import.meta.url)).name;
537
+ const config = loadConfig();
538
+ const defaultPort = config?.server?.port || 3001;
539
+ const finalPort = port || defaultPort;
540
+
541
+ const distDir = getDistPath(import.meta.url);
542
+
543
+ if (!await fs.pathExists(distDir)) {
544
+ throw new Error('No production build found. Run "slice build" first.');
545
+ }
546
+
547
+ Print.info(`Starting production preview server on port ${finalPort}...`);
548
+
549
+ const express = await import('express');
550
+ const app = express.default();
551
+
552
+ app.use(express.default.static(distDir));
553
+
554
+ app.get('*', (req, res) => {
555
+ const indexPath = path.join(distDir, 'App/index.html');
556
+ const fallbackPath = path.join(distDir, 'index.html');
557
+
558
+ if (fs.existsSync(indexPath)) {
559
+ res.sendFile(indexPath);
560
+ } else if (fs.existsSync(fallbackPath)) {
561
+ res.sendFile(fallbackPath);
562
+ } else {
563
+ res.status(404).send('Production build index.html not found');
564
+ }
565
+ });
566
+
567
+ app.listen(finalPort, () => {
568
+ Print.success(`Production preview server running at http://localhost:${finalPort}`);
569
+ Print.info('Press Ctrl+C to stop the server');
570
+ Print.info('This server previews your production build from /dist');
571
+ Print.warning(`This is a preview server - use "${runScriptCommand(packageManager, 'start')}" for the full production server`);
572
+ });
573
+
574
+ } catch (error) {
575
+ Print.error(`Error starting production preview server: ${error.message}`);
576
+ throw error;
577
+ }
578
+ }
579
+
580
+ /**
581
+ * Build command with options
582
+ */
583
+ export async function buildCommand(options = {}) {
584
+ const config = loadConfig();
585
+ const defaultPort = config?.server?.port || 3001;
586
+
587
+ // Missing minifiers are fatal unless the caller explicitly accepts an
588
+ // unoptimized build.
589
+ if (!await checkBuildDependencies() && !options.allowUnoptimized) {
590
+ return false;
591
+ }
592
+
593
+ if (options.serve) {
594
+ await serveProductionBuild(options.port || defaultPort);
595
+ return true;
596
+ }
597
+
598
+ if (options.analyze) {
599
+ await analyzeBuild();
600
+ return true;
601
+ }
602
+
603
+ const success = await buildProduction(options);
604
+
605
+ if (success && options.preview) {
606
+ Print.newLine();
607
+ Print.info('✨ Build completed successfully!');
608
+ Print.info(`Starting preview server on port ${options.port || defaultPort}...`);
609
+ await serveProductionBuild(options.port || defaultPort);
610
+ }
611
+
612
+ return success;
613
+ }