@eserstack/laroux-bundler 0.0.0-stage → 5.0.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 (103) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +431 -2
  3. package/dist/adapters/fonts/font-optimizer.d.ts +28 -0
  4. package/dist/adapters/fonts/font-optimizer.js +74 -0
  5. package/dist/adapters/fonts/index.d.ts +18 -0
  6. package/dist/adapters/fonts/index.js +78 -0
  7. package/dist/adapters/fonts/mod.d.ts +6 -0
  8. package/dist/adapters/fonts/mod.js +7 -0
  9. package/dist/adapters/lightningcss/css-processor.d.ts +39 -0
  10. package/dist/adapters/lightningcss/css-processor.js +103 -0
  11. package/dist/adapters/lightningcss/mod.d.ts +5 -0
  12. package/dist/adapters/lightningcss/mod.js +6 -0
  13. package/dist/adapters/mod.d.ts +13 -0
  14. package/dist/adapters/mod.js +21 -0
  15. package/dist/adapters/prebuilt-bundler/mod.d.ts +5 -0
  16. package/dist/adapters/prebuilt-bundler/mod.js +6 -0
  17. package/dist/adapters/prebuilt-bundler/prebuilt-bundler.d.ts +22 -0
  18. package/dist/adapters/prebuilt-bundler/prebuilt-bundler.js +60 -0
  19. package/dist/adapters/react/mod.d.ts +10 -0
  20. package/dist/adapters/react/mod.js +16 -0
  21. package/dist/adapters/react/plugin.d.ts +17 -0
  22. package/dist/adapters/react/plugin.js +62 -0
  23. package/dist/adapters/react/rsc-analyze.d.ts +29 -0
  24. package/dist/adapters/react/rsc-analyze.js +116 -0
  25. package/dist/adapters/react/rsc-client-entry.d.ts +26 -0
  26. package/dist/adapters/react/rsc-client-entry.js +145 -0
  27. package/dist/adapters/react/rsc-module-map.d.ts +41 -0
  28. package/dist/adapters/react/rsc-module-map.js +81 -0
  29. package/dist/adapters/react/rsc-rewrite-imports.d.ts +38 -0
  30. package/dist/adapters/react/rsc-rewrite-imports.js +409 -0
  31. package/dist/adapters/react/rsc-transform.d.ts +26 -0
  32. package/dist/adapters/react/rsc-transform.js +101 -0
  33. package/dist/adapters/runtime-bundler/mod.d.ts +6 -0
  34. package/dist/adapters/runtime-bundler/mod.js +6 -0
  35. package/dist/adapters/runtime-bundler/runtime-bundler.d.ts +85 -0
  36. package/dist/adapters/runtime-bundler/runtime-bundler.js +244 -0
  37. package/dist/adapters/sharp/image-optimizer.d.ts +52 -0
  38. package/dist/adapters/sharp/image-optimizer.js +261 -0
  39. package/dist/adapters/sharp/mod.d.ts +6 -0
  40. package/dist/adapters/sharp/mod.js +6 -0
  41. package/dist/adapters/tailwindcss/compile.d.ts +22 -0
  42. package/dist/adapters/tailwindcss/compile.js +29 -0
  43. package/dist/adapters/tailwindcss/critical-css-config.d.ts +46 -0
  44. package/dist/adapters/tailwindcss/critical-css-config.js +78 -0
  45. package/dist/adapters/tailwindcss/critical-page-css.d.ts +61 -0
  46. package/dist/adapters/tailwindcss/critical-page-css.js +431 -0
  47. package/dist/adapters/tailwindcss/critical-universal-css.d.ts +68 -0
  48. package/dist/adapters/tailwindcss/critical-universal-css.js +250 -0
  49. package/dist/adapters/tailwindcss/mod.d.ts +10 -0
  50. package/dist/adapters/tailwindcss/mod.js +11 -0
  51. package/dist/adapters/tailwindcss/plugin.d.ts +16 -0
  52. package/dist/adapters/tailwindcss/plugin.js +107 -0
  53. package/dist/adapters/tailwindcss/stylesheet-loader.d.ts +15 -0
  54. package/dist/adapters/tailwindcss/stylesheet-loader.js +83 -0
  55. package/dist/config.d.ts +27 -0
  56. package/dist/config.js +31 -0
  57. package/dist/css-modules.d.ts +49 -0
  58. package/dist/css-modules.js +146 -0
  59. package/dist/domain/build-cache.d.ts +107 -0
  60. package/dist/domain/build-cache.js +128 -0
  61. package/dist/domain/build-validator.d.ts +68 -0
  62. package/dist/domain/build-validator.js +207 -0
  63. package/dist/domain/bundler.d.ts +136 -0
  64. package/dist/domain/bundler.js +225 -0
  65. package/dist/domain/chunk-manifest.d.ts +40 -0
  66. package/dist/domain/chunk-manifest.js +188 -0
  67. package/dist/domain/client-action-stub.d.ts +30 -0
  68. package/dist/domain/client-action-stub.js +167 -0
  69. package/dist/domain/copy-path.d.ts +15 -0
  70. package/dist/domain/copy-path.js +29 -0
  71. package/dist/domain/css-plugin.d.ts +91 -0
  72. package/dist/domain/css-plugin.js +6 -0
  73. package/dist/domain/css-processor.d.ts +57 -0
  74. package/dist/domain/css-processor.js +33 -0
  75. package/dist/domain/font-optimizer.d.ts +46 -0
  76. package/dist/domain/font-optimizer.js +17 -0
  77. package/dist/domain/framework-plugin.d.ts +106 -0
  78. package/dist/domain/framework-plugin.js +20 -0
  79. package/dist/domain/image-optimizer.d.ts +74 -0
  80. package/dist/domain/image-optimizer.js +16 -0
  81. package/dist/domain/import-map.d.ts +90 -0
  82. package/dist/domain/import-map.js +187 -0
  83. package/dist/domain/mod.d.ts +32 -0
  84. package/dist/domain/mod.js +20 -0
  85. package/dist/domain/route-generator.d.ts +34 -0
  86. package/dist/domain/route-generator.js +305 -0
  87. package/dist/domain/route-scanner.d.ts +72 -0
  88. package/dist/domain/route-scanner.js +282 -0
  89. package/dist/domain/server-action-transform.d.ts +28 -0
  90. package/dist/domain/server-action-transform.js +147 -0
  91. package/dist/domain/virtual-source.d.ts +63 -0
  92. package/dist/domain/virtual-source.js +238 -0
  93. package/dist/import-map-resolver-plugin.d.ts +47 -0
  94. package/dist/import-map-resolver-plugin.js +109 -0
  95. package/dist/mod.d.ts +57 -0
  96. package/dist/mod.js +56 -0
  97. package/dist/server-externals-plugin.d.ts +29 -0
  98. package/dist/server-externals-plugin.js +63 -0
  99. package/dist/system.d.ts +157 -0
  100. package/dist/system.js +1401 -0
  101. package/dist/types.d.ts +60 -0
  102. package/dist/types.js +38 -0
  103. package/package.json +83 -3
package/dist/system.js ADDED
@@ -0,0 +1,1401 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Unified Build System
4
+ *
5
+ * Framework-agnostic build orchestration.
6
+ * Framework-specific functionality (like React Server Components) is provided
7
+ * through the FrameworkPlugin interface.
8
+ */
9
+ import * as crossRuntime from "@eserstack/standards/cross-runtime";
10
+ import * as logging from "@eserstack/logging";
11
+ import * as directiveAnalysis from "@eserstack/codebase/directive-analysis";
12
+ import * as patterns from "@eserstack/standards/patterns";
13
+ import * as serverActionTransform from "./domain/server-action-transform.js";
14
+ import * as clientActionStub from "./domain/client-action-stub.js";
15
+ import * as buildValidator from "./domain/build-validator.js";
16
+ import * as copyPath from "./domain/copy-path.js";
17
+ import * as frameworkPlugin from "./domain/framework-plugin.js";
18
+ import * as types from "./types.js";
19
+ import * as cssProcessor from "./domain/css-processor.js";
20
+ import * as fontOptimizer from "./domain/font-optimizer.js";
21
+ import * as imageOptimizer from "./domain/image-optimizer.js";
22
+ import * as importMapResolverPlugin from "./import-map-resolver-plugin.js";
23
+ import * as routeScanner from "./domain/route-scanner.js";
24
+ import * as routeGenerator from "./domain/route-generator.js";
25
+ import * as virtualSource from "./domain/virtual-source.js";
26
+ import * as buildCache from "./domain/build-cache.js";
27
+ import * as bundler from "./domain/bundler.js";
28
+ import * as chunkManifest from "./domain/chunk-manifest.js";
29
+ import * as settings from "./config.js";
30
+ import * as cssModules from "./css-modules.js";
31
+ import * as serverExternalsPlugin from "./server-externals-plugin.js";
32
+ const buildLogger = logging.logger.getLogger(["laroux-bundler", "build"]);
33
+ // Constants
34
+ const MANIFEST_FILENAME = "manifest.json";
35
+ const MODULE_MAP_FILENAME = "module-map.json";
36
+ const SERVER_DIR = "server";
37
+ const CLIENT_DIR = "client";
38
+ const PUBLIC_DIR = "public";
39
+ /**
40
+ * Project files besides the source and public directories whose changes make
41
+ * a build stale: the laroux config and the package.json the bundler reads.
42
+ */
43
+ const PROJECT_BUILD_INPUTS = ["laroux.config.ts", "package.json"];
44
+ /** Entries the staleness check skips: dependencies and hidden files. */
45
+ const STALENESS_SKIP_PATTERNS = [
46
+ /(?:^|[\\/])node_modules$/,
47
+ /(?:^|[\\/])\.[^\\/]*$/,
48
+ ];
49
+ /**
50
+ * Create build context from configuration
51
+ * @param config - Build configuration
52
+ * @param plugins - Plugins for framework, CSS, and bundler (explicit composition)
53
+ * @returns Build context with all paths and dependencies
54
+ */
55
+ export function createBuildContext(config, plugins) {
56
+ const projectRoot = config.projectRoot;
57
+ const srcDir = config.srcDir;
58
+ const distDir = config.distDir;
59
+ // Client entry is no longer hardcoded - provided by the plugin
60
+ const clientEntry = "";
61
+ const chunkManifestFile = crossRuntime.runtime.path.resolve(distDir, CLIENT_DIR, MANIFEST_FILENAME);
62
+ return {
63
+ config,
64
+ projectRoot,
65
+ srcDir,
66
+ distDir,
67
+ clientEntry,
68
+ chunkManifestFile,
69
+ bundlerBackend: plugins?.bundlerBackend,
70
+ plugin: plugins?.framework ?? frameworkPlugin.noopPlugin,
71
+ cssPlugin: plugins?.css,
72
+ cssProcessor: plugins?.cssProcessor ?? cssProcessor.noopCssProcessor,
73
+ fontOptimizer: plugins?.fontOptimizer ?? fontOptimizer.noopFontOptimizer,
74
+ imageOptimizer: plugins?.imageOptimizer ?? imageOptimizer.noopImageOptimizer,
75
+ };
76
+ }
77
+ /**
78
+ * Main build function
79
+ * Performs complete build: analyze → transform → bundle → generate maps
80
+ * @param context - Build context with configuration and paths
81
+ * @param options - Build options
82
+ * - skipCss: for JS-only changes; keeps styles.css and skips the global
83
+ * stylesheet, but still compiles the CSS modules the bundles import
84
+ * - cssOnly: for CSS-only changes; rewrites styles.css and the CSS derived
85
+ * from it as a full build does, and keeps the JavaScript and its build id
86
+ * - changedFiles: set of changed file paths for incremental builds
87
+ * @returns Build result with success status and metrics
88
+ */
89
+ export async function build(context, options) {
90
+ const { srcDir, distDir, projectRoot } = context;
91
+ const startTime = performance.now();
92
+ // A unique id per build. It busts caches and tells builds apart and is
93
+ // only ever compared for equality, so it needs no time order.
94
+ const buildId = crypto.randomUUID();
95
+ buildLogger.info(`🚀 Starting RSC build...`);
96
+ buildLogger.debug(`🆔 Build ID: ${buildId}`);
97
+ try {
98
+ // CSS-only fast path for HMR: the JavaScript in dist/ stays as it is
99
+ if (options?.cssOnly === true) {
100
+ return await rebuildStylesheets(context, buildId, startTime);
101
+ }
102
+ // Step 1: Clean if requested (preserve CSS files when skipCss is true)
103
+ await cleanBuildDir(distDir, options?.skipCss);
104
+ // Step 2: Ensure dist directory exists
105
+ await crossRuntime.runtime.fs.ensureDir(distDir);
106
+ // Build timestamp will be written to chunk manifest at the end
107
+ const buildTimestamp = Date.now();
108
+ // Step 3: Parallel scan - routes, client components, and CSS modules
109
+ // These operations are independent and can run concurrently for faster builds
110
+ buildLogger.debug("🔍 Step 3: Parallel scanning (routes, components, CSS modules)...");
111
+ const routesDir = crossRuntime.runtime.path.resolve(srcDir, "app/routes");
112
+ const { plugin } = context;
113
+ const [scanResult, clientComponents, cssModulePaths] = await Promise.all([
114
+ routeScanner.scanRoutes(routesDir, projectRoot, { cache: context.cache }),
115
+ plugin.analyzeClientComponents
116
+ ? plugin.analyzeClientComponents(srcDir, projectRoot, context.cache)
117
+ : Promise.resolve([]),
118
+ scanCssModuleFiles(srcDir),
119
+ ]);
120
+ // Generate route files to dist/server/ (NOT src/) for build isolation
121
+ const serverDir = crossRuntime.runtime.path.resolve(distDir, SERVER_DIR);
122
+ await crossRuntime.runtime.fs.ensureDir(serverDir);
123
+ const generatedRoutesPath = crossRuntime.runtime.path.resolve(serverDir, "_generated-routes.ts");
124
+ // Get srcDir name relative to project root (e.g., "src")
125
+ const srcDirName = crossRuntime.runtime.path.relative(projectRoot, srcDir);
126
+ await routeGenerator.generateRouteFile({
127
+ scanResult,
128
+ outputPath: generatedRoutesPath,
129
+ projectRoot,
130
+ srcDirName,
131
+ moduleVersion: buildId,
132
+ });
133
+ buildLogger.debug(`✓ Generated ${scanResult.routes.length} page route(s) to dist/`);
134
+ // Generate API routes file if any exist
135
+ if (scanResult.apiRoutes.length > 0) {
136
+ const apiRoutesPath = crossRuntime.runtime.path.resolve(distDir, "server", "api-routes.ts");
137
+ await crossRuntime.runtime.fs.ensureDir(crossRuntime.runtime.path.dirname(apiRoutesPath));
138
+ await routeGenerator.generateApiRouteFile(scanResult, apiRoutesPath, projectRoot);
139
+ buildLogger.debug(`✓ Generated ${scanResult.apiRoutes.length} API route(s)`);
140
+ }
141
+ // Generate proxy registry if any exist
142
+ if (scanResult.proxies.length > 0) {
143
+ const proxyPath = crossRuntime.runtime.path.resolve(distDir, "server", "proxy-registry.ts");
144
+ await crossRuntime.runtime.fs.ensureDir(crossRuntime.runtime.path.dirname(proxyPath));
145
+ await routeGenerator.generateProxyFile(scanResult, proxyPath, projectRoot);
146
+ buildLogger.debug(`✓ Generated ${scanResult.proxies.length} proxy definition(s)`);
147
+ }
148
+ if (clientComponents.length === 0) {
149
+ buildLogger.warn("⚠️ Warning: No client components found!");
150
+ }
151
+ // Step 4: Transform client components (proxies)
152
+ buildLogger.debug("🔄 Step 4: Transforming client components...");
153
+ const transformResults = plugin.transformClientComponents
154
+ ? await plugin.transformClientComponents(clientComponents, crossRuntime.runtime.path.resolve(distDir, SERVER_DIR), projectRoot)
155
+ : [];
156
+ // Generate transform manifest
157
+ if (plugin.generateTransformManifest) {
158
+ await plugin.generateTransformManifest(transformResults, crossRuntime.runtime.path.resolve(distDir, "transform-manifest.json"), projectRoot);
159
+ }
160
+ // Step 5: Rewrite server component imports
161
+ buildLogger.debug("✏️ Step 5: Rewriting server component imports...");
162
+ const allComponents = plugin.getAllComponents
163
+ ? await plugin.getAllComponents(srcDir)
164
+ : [];
165
+ const clientComponentPaths = new Set(clientComponents.map((c) => c.filePath));
166
+ const serverComponentPaths = allComponents.filter((path) => !clientComponentPaths.has(path));
167
+ if (plugin.rewriteServerComponents) {
168
+ await plugin.rewriteServerComponents(serverComponentPaths, transformResults, cssModulePaths, crossRuntime.runtime.path.resolve(distDir, SERVER_DIR), projectRoot);
169
+ }
170
+ // Step 5b: Transform server actions to add React server reference symbols
171
+ // This must happen AFTER server components are copied but BEFORE bundling
172
+ buildLogger.debug("🔄 Step 5b: Transforming server actions with React symbols...");
173
+ const serverDistDir = crossRuntime.runtime.path.resolve(distDir, SERVER_DIR);
174
+ const serverActionResults = await serverActionTransform.transformServerActions(serverDistDir);
175
+ if (serverActionResults.length > 0) {
176
+ const totalActions = serverActionResults.reduce((sum, r) => sum + r.transformedActions.length, 0);
177
+ buildLogger.info(` ✅ Transformed ${serverActionResults.length} file(s) with ${totalActions} action(s)`);
178
+ }
179
+ // Step 6: Generate module map
180
+ buildLogger.debug("🗺️ Step 6: Generating module map...");
181
+ const clientOutputDir = crossRuntime.runtime.path.resolve(distDir, CLIENT_DIR);
182
+ await crossRuntime.runtime.fs.ensureDir(clientOutputDir);
183
+ const moduleMap = plugin.createModuleMap
184
+ ? await plugin.createModuleMap(clientComponents)
185
+ : {};
186
+ if (plugin.saveModuleMap) {
187
+ await plugin.saveModuleMap(moduleMap, crossRuntime.runtime.path.resolve(clientOutputDir, MODULE_MAP_FILENAME));
188
+ }
189
+ if (plugin.createClientManifest) {
190
+ await plugin.createClientManifest(clientComponents);
191
+ }
192
+ // Use provided CSS plugin (or skip CSS if none)
193
+ const cssPlugin = context.cssPlugin;
194
+ // Step 7: Process global CSS with CSS plugin (skippable for JS-only changes)
195
+ if (!options?.skipCss && cssPlugin) {
196
+ buildLogger.debug("🎨 Step 7: Processing CSS with CSS plugin + Lightning CSS...");
197
+ await processCssFiles({
198
+ plugin: cssPlugin,
199
+ processor: context.cssProcessor,
200
+ srcDir,
201
+ projectRoot,
202
+ outputDir: clientOutputDir,
203
+ });
204
+ }
205
+ else if (!cssPlugin) {
206
+ buildLogger.debug("⏭️ No CSS plugin provided, skipping CSS processing");
207
+ }
208
+ else {
209
+ buildLogger.debug("⏭️ Skipping CSS processing (JS-only change)");
210
+ }
211
+ // Step 8: Create virtual source for bundling (build isolation)
212
+ // This copies src/ to dist/_bundle_src/ so we can modify imports without touching original source
213
+ // In watch mode, only copy changed files for faster rebuilds
214
+ buildLogger.debug("📁 Step 8: Creating virtual source for bundling...");
215
+ const virtualSourceResult = await virtualSource.createVirtualSource({
216
+ projectRoot,
217
+ distDir,
218
+ srcDir,
219
+ changedFiles: options?.changedFiles,
220
+ });
221
+ const virtualSrcDir = virtualSourceResult.virtualSrcDir;
222
+ // The virtual source is removed when this scope ends, whether the
223
+ // bundling below succeeds or throws.
224
+ let clientBundle;
225
+ try {
226
+ // Step 8b: Generate client stubs for "use server" files in virtual source
227
+ // This replaces server action files with client-side stubs that call /action
228
+ // Must happen BEFORE client bundling so imports resolve to stubs
229
+ buildLogger.debug("🔌 Step 8b: Generating client action stubs in virtual source...");
230
+ const virtualSrcSubdirForStubs = crossRuntime.runtime.path.join(virtualSrcDir, srcDirName);
231
+ const clientStubResults = await clientActionStub.generateClientActionStubs(virtualSrcSubdirForStubs, virtualSrcDir);
232
+ if (clientStubResults.length > 0) {
233
+ const totalActions = clientStubResults.reduce((sum, r) => sum + r.exportedActions.length, 0);
234
+ buildLogger.info(` ✅ Generated ${clientStubResults.length} stub file(s) with ${totalActions} action(s)`);
235
+ }
236
+ // Step 9: Process CSS Modules to virtual source (NOT original src/)
237
+ // Generate JSON files in the virtual source directory. A JS-only
238
+ // rebuild (skipCss) needs them too: the bundles import a component's
239
+ // class names from them, and without the rewrite in Step 10 the client
240
+ // bundler meets a raw .module.css import and fails.
241
+ // Map to store pre-processed CSS module results (translated to original paths)
242
+ const cssModuleResults = new Map();
243
+ if (cssModulePaths.length > 0) {
244
+ buildLogger.debug("🎨 Step 9: Processing CSS Modules to virtual source...");
245
+ // Translate CSS module paths to virtual source
246
+ const virtualCssModulePaths = cssModulePaths.map((p) => virtualSource.translateToVirtualPath(p, srcDir, virtualSrcDir));
247
+ // Process and generate JSON files in virtual source
248
+ // Use real projectRoot for Tailwind (needs node_modules for @import "tailwindcss")
249
+ // Pass pre-translated virtual paths to avoid redundant scan
250
+ const virtualResults = await processCssModulesFiles(projectRoot, virtualSrcDir, context.config, {
251
+ skipCss: true,
252
+ cssModulePaths: virtualCssModulePaths,
253
+ cache: context.cache,
254
+ plugin: cssPlugin,
255
+ });
256
+ // Translate virtual paths back to original paths for reuse in appendCssModulesToStyles
257
+ // This avoids duplicate CSS module processing
258
+ // Use srcDirName computed from config (e.g., "src") for virtual path translation
259
+ const virtualSrcSubdir = crossRuntime.runtime.path.join(virtualSrcDir, srcDirName);
260
+ for (const [virtualPath, result] of virtualResults) {
261
+ // Convert virtual path back to original path
262
+ const relativePath = crossRuntime.runtime.path.relative(virtualSrcSubdir, virtualPath);
263
+ const originalPath = crossRuntime.runtime.path.resolve(srcDir, relativePath);
264
+ cssModuleResults.set(originalPath, result);
265
+ }
266
+ // Rewrite CSS imports in virtual source (NOT original src/)
267
+ if (virtualCssModulePaths.length > 0) {
268
+ buildLogger.debug("✏️ Step 10: Rewriting CSS module imports in virtual source...");
269
+ if (plugin.rewriteCssModuleImports) {
270
+ await plugin.rewriteCssModuleImports(virtualSrcSubdir, virtualCssModulePaths, projectRoot);
271
+ }
272
+ }
273
+ }
274
+ // Step 11: Bundle client code from virtual source
275
+ // Translate component paths to use virtual source
276
+ buildLogger.debug("📦 Step 11: Bundling client code from virtual source...");
277
+ const virtualClientComponents = virtualSource.translateClientComponents(clientComponents, srcDir, virtualSrcDir);
278
+ clientBundle = await bundleClient({ ...context, srcDir: virtualSrcDir }, virtualClientComponents, buildId, buildTimestamp);
279
+ // Step 12: Copy CSS Module JSON files from virtual source to dist/
280
+ if (cssModulePaths.length > 0) {
281
+ // Copy JSON files from virtual source to dist/client/
282
+ buildLogger.debug(`📋 Step 12: Copying ${cssModulePaths.length} CSS Module JSON file(s) to client/...`);
283
+ await copyCssModuleJsonFilesFromSrc(cssModulePaths.map((p) => virtualSource.translateToVirtualPath(p, srcDir, virtualSrcDir)), virtualSrcDir, clientOutputDir);
284
+ // Copy JSON files from virtual source to dist/server/
285
+ buildLogger.debug(`📋 Step 13: Copying ${cssModulePaths.length} CSS Module JSON file(s) to server/...`);
286
+ await copyCssModuleJsonFilesFromSrc(cssModulePaths.map((p) => virtualSource.translateToVirtualPath(p, srcDir, virtualSrcDir)), virtualSrcDir, crossRuntime.runtime.path.resolve(distDir, SERVER_DIR));
287
+ // Append CSS module styles to main styles.css bundle. A JS-only
288
+ // rebuild kept the styles.css of the build before it, which has them
289
+ // already. Pass pre-processed results to avoid duplicate processing
290
+ if (!options?.skipCss) {
291
+ buildLogger.debug("🎨 Step 14: Appending CSS modules to styles.css...");
292
+ await appendCssModulesToStyles(cssModuleResults, clientOutputDir);
293
+ }
294
+ }
295
+ }
296
+ finally {
297
+ // Step 15: Clean up virtual source
298
+ buildLogger.debug("🧹 Step 15: Cleaning up virtual source...");
299
+ await virtualSourceResult.cleanup();
300
+ }
301
+ // Steps 16 and 17: Critical, deferred and universal CSS (requires CSS plugin)
302
+ if (cssPlugin) {
303
+ await writeDerivedStylesheets(cssPlugin, clientOutputDir);
304
+ }
305
+ // Step 18: Optimize fonts for self-hosting (output to client/)
306
+ buildLogger.debug("🔤 Step 18: Optimizing Fonts...");
307
+ await optimizeFonts(context.fontOptimizer, clientOutputDir, context.config.fonts);
308
+ // Step 19: Optimize images (WebP, AVIF, responsive variants)
309
+ buildLogger.debug("🖼️ Step 19: Optimizing Images...");
310
+ await optimizeImagesStep(context.imageOptimizer, projectRoot, clientOutputDir, context.config);
311
+ // Step 20: Copy translation JSON files to server directory
312
+ buildLogger.debug("🌐 Step 20: Copying translation files...");
313
+ await copyTranslationFiles(srcDir, crossRuntime.runtime.path.resolve(distDir, SERVER_DIR), projectRoot);
314
+ const serverOutputDir = crossRuntime.runtime.path.resolve(distDir, SERVER_DIR);
315
+ // Step 22: Bundle server components
316
+ // This resolves all bare specifiers (react, lucide-react, etc.) via the bundler
317
+ // and keeps external ones bare instead of rewriting them (ADR 0004)
318
+ const serverBundlerBackend = context.bundlerBackend ?? "rolldown";
319
+ buildLogger.info(`📦 Step 22: Server bundling check - components: ${serverComponentPaths.length}`);
320
+ if (serverComponentPaths.length > 0) {
321
+ buildLogger.info(`📦 Step 22: Bundling ${serverComponentPaths.length} server component(s) with ${serverBundlerBackend}...`);
322
+ // Get server component files from dist/server (already copied with rewrites)
323
+ // Files are in dist/server/src/... (preserving source directory structure)
324
+ const candidatePaths = serverComponentPaths.map((srcPath) =>
325
+ // "src/app/page.tsx" becomes "dist/server/src/app/page.tsx"
326
+ crossRuntime.runtime.path.join(serverOutputDir, crossRuntime.runtime.path.relative(projectRoot, srcPath)));
327
+ const candidateExists = await Promise.all(candidatePaths.map((distPath) => crossRuntime.runtime.fs.exists(distPath)));
328
+ const serverEntrypoints = candidatePaths.filter((_, index) => candidateExists[index] === true);
329
+ buildLogger.info(` Found ${serverEntrypoints.length} server entrypoints to bundle`);
330
+ if (serverEntrypoints.length > 0) {
331
+ // Server externals from config (default: @eserstack/laroux, @eserstack/laroux-server)
332
+ // These resolve from the app's node_modules at run time.
333
+ // Everything else (react, lucide-react, etc.) gets bundled.
334
+ // See ADR: 0002-bundler-external-import-specifiers.md
335
+ const serverExternals = context.config.serverExternals;
336
+ // Create server externals plugin with prefix matching for subpath imports
337
+ // e.g., "@eserstack/laroux-server" matches "@eserstack/laroux-server/action-registry"
338
+ // This ensures singleton modules like action-registry are shared between
339
+ // bundled server components and the laroux-server runtime.
340
+ const externalsPlugin = serverExternalsPlugin.createServerExternalsPlugin({
341
+ externals: serverExternals,
342
+ });
343
+ // Rolldown bundles the server with platform: "node", running the
344
+ // externals plugin so the listed packages stay imports
345
+ const serverBundleResult = await bundler.bundleServerComponents({
346
+ entrypoints: serverEntrypoints,
347
+ outputDir: serverOutputDir,
348
+ projectRoot: serverOutputDir,
349
+ sourcemap: false,
350
+ minify: false,
351
+ externals: serverExternals,
352
+ plugins: [externalsPlugin],
353
+ }, serverBundlerBackend);
354
+ buildLogger.info(` ✅ Bundled ${serverBundleResult.fileCount} server file(s)`);
355
+ }
356
+ }
357
+ // Step 22b: Generate server actions manifest
358
+ // Use analyzeServerActions which scans ALL files for "use server" directive
359
+ // This finds action files regardless of naming (not just actions.ts)
360
+ buildLogger.debug("📋 Step 22b: Generating server actions manifest...");
361
+ const serverActionMatches = await directiveAnalysis.analyzeServerActions(srcDir, {
362
+ projectRoot,
363
+ });
364
+ // Convert source paths to bundled output paths:
365
+ // Preserves full path structure (src/app/actions.ts → src/app/actions.js)
366
+ const actionFiles = serverActionMatches.map((match) => patterns.replaceJsExtension(match.relativePath, ".js"));
367
+ // Write actions manifest
368
+ const actionsManifestPath = crossRuntime.runtime.path.resolve(serverOutputDir, "actions-manifest.json");
369
+ await crossRuntime.runtime.fs.writeTextFile(actionsManifestPath, JSON.stringify({ actions: actionFiles }, null, 2));
370
+ buildLogger.debug(`✓ Generated actions manifest: ${actionFiles.length} action file(s)`);
371
+ // Step 23: Copy public assets to dist root (server expects them there)
372
+ await copyPublicAssets(projectRoot, distDir);
373
+ // Step 24: Write the chunk manifest last. Its presence marks a build
374
+ // that finished, which ensureBuildIsReady relies on to skip a build.
375
+ await chunkManifest.saveChunkManifest(clientBundle.manifest, context.chunkManifestFile);
376
+ const duration = performance.now() - startTime;
377
+ buildLogger.info(`📊 Build Summary:`);
378
+ buildLogger.info(` Client components: ${clientComponents.length}`);
379
+ buildLogger.info(` Build time: ${duration.toFixed(0)}ms`);
380
+ return {
381
+ success: true,
382
+ buildId,
383
+ clientBundle: crossRuntime.runtime.path.resolve(clientOutputDir, clientBundle.entrypoint),
384
+ moduleMap,
385
+ clientComponents: clientComponents.length,
386
+ duration,
387
+ timestamp: buildTimestamp,
388
+ };
389
+ }
390
+ catch (error) {
391
+ // The build handles every step's error here and logs it once, with the
392
+ // whole cause chain; the steps return errors without logging them.
393
+ buildLogger.with({ error }).error("❌ Build failed");
394
+ return {
395
+ success: false,
396
+ buildId,
397
+ clientBundle: "",
398
+ moduleMap: {},
399
+ clientComponents: 0,
400
+ duration: performance.now() - startTime,
401
+ timestamp: Date.now(),
402
+ };
403
+ }
404
+ }
405
+ /**
406
+ * Ensure build is ready - builds if needed, skips if up-to-date
407
+ *
408
+ * The build is up to date when the chunk manifest of a finished build exists
409
+ * and no build input changed after its timestamp: no file under the source
410
+ * directory or public/ (at any depth, skipping node_modules and hidden
411
+ * entries) and neither laroux.config.ts nor package.json.
412
+ * @param context - Build context with configuration and paths
413
+ * @returns Build result; a skipped build returns the existing build's
414
+ * timestamp, module map and client bundle, with a duration of 0
415
+ */
416
+ export async function ensureBuildIsReady(context) {
417
+ if (await needsRebuild(context)) {
418
+ buildLogger.info("🔄 Build needed, running build...");
419
+ return await build(context);
420
+ }
421
+ else {
422
+ buildLogger.info("✅ Build is up-to-date, skipping...");
423
+ return await loadExistingBuild(context);
424
+ }
425
+ }
426
+ /**
427
+ * Check if rebuild is needed based on file timestamps
428
+ * @param context - Build context
429
+ * @returns True if rebuild is needed
430
+ */
431
+ async function needsRebuild(context) {
432
+ const manifest = await readChunkManifest(context.chunkManifestFile);
433
+ if (manifest === null || typeof manifest.timestamp !== "number") {
434
+ return true;
435
+ }
436
+ const changedFile = await findChangedBuildInput(context, manifest.timestamp);
437
+ if (changedFile === null) {
438
+ return false;
439
+ }
440
+ buildLogger.debug(` Changed: ${crossRuntime.runtime.path.relative(context.projectRoot, changedFile)}`);
441
+ return true;
442
+ }
443
+ /**
444
+ * Read the chunk manifest a finished build wrote, or null when there is none
445
+ * or it is not valid JSON (a build that was interrupted while writing it).
446
+ */
447
+ async function readChunkManifest(chunkManifestFile) {
448
+ let content;
449
+ try {
450
+ content = await crossRuntime.runtime.fs.readTextFile(chunkManifestFile);
451
+ }
452
+ catch (error) {
453
+ if (error instanceof crossRuntime.NotFoundError) {
454
+ return null;
455
+ }
456
+ throw error;
457
+ }
458
+ try {
459
+ return JSON.parse(content);
460
+ }
461
+ catch (error) {
462
+ if (error instanceof SyntaxError) {
463
+ buildLogger.debug(` ${chunkManifestFile} is not valid JSON, so the build runs again`);
464
+ return null;
465
+ }
466
+ throw error;
467
+ }
468
+ }
469
+ /**
470
+ * Find a build input modified after the build at buildTimestamp.
471
+ * @param context - Build context; its srcDir, projectRoot and distDir are read
472
+ * @param buildTimestamp - Timestamp of the existing build, in milliseconds
473
+ * @returns The path of one changed input, or null when every input is older
474
+ */
475
+ async function findChangedBuildInput(context, buildTimestamp) {
476
+ const { srcDir, projectRoot, distDir } = context;
477
+ const [sourceFiles, publicFiles] = await Promise.all([
478
+ listBuildInputFiles(srcDir, distDir),
479
+ listBuildInputFiles(crossRuntime.runtime.path.resolve(projectRoot, PUBLIC_DIR), distDir),
480
+ ]);
481
+ const inputFiles = [
482
+ ...sourceFiles,
483
+ ...publicFiles,
484
+ ...PROJECT_BUILD_INPUTS.map((name) => crossRuntime.runtime.path.resolve(projectRoot, name)),
485
+ ];
486
+ const modifiedTimes = await Promise.all(inputFiles.map(readModifiedTime));
487
+ const changedIndex = modifiedTimes.findIndex((mtime) => mtime !== null && mtime > buildTimestamp);
488
+ return changedIndex === -1 ? null : (inputFiles[changedIndex] ?? null);
489
+ }
490
+ /**
491
+ * List every file under dir at any depth, except node_modules, hidden entries
492
+ * and the output directory. A missing dir has no files.
493
+ */
494
+ async function listBuildInputFiles(dir, distDir) {
495
+ if (!(await crossRuntime.runtime.fs.exists(dir))) {
496
+ return [];
497
+ }
498
+ const files = [];
499
+ for await (const entry of crossRuntime.runtime.fs.walk(dir, {
500
+ includeDirs: false,
501
+ skip: STALENESS_SKIP_PATTERNS,
502
+ })) {
503
+ if (!buildValidator.isWithinOutputDir(entry.path, distDir)) {
504
+ files.push(entry.path);
505
+ }
506
+ }
507
+ return files;
508
+ }
509
+ /**
510
+ * Modification time of a file in milliseconds, or null when it does not
511
+ * exist or the file system reports none.
512
+ */
513
+ async function readModifiedTime(filePath) {
514
+ try {
515
+ const fileStat = await crossRuntime.runtime.fs.stat(filePath);
516
+ return fileStat.mtime?.getTime() ?? null;
517
+ }
518
+ catch (error) {
519
+ // A file that no longer exists cannot be newer than the build
520
+ if (error instanceof crossRuntime.NotFoundError) {
521
+ return null;
522
+ }
523
+ throw error;
524
+ }
525
+ }
526
+ /**
527
+ * Load existing build result from manifest files
528
+ * @param context - Build context
529
+ * @returns Build result from previous successful build
530
+ */
531
+ async function loadExistingBuild(context) {
532
+ const { chunkManifestFile, distDir } = context;
533
+ const clientOutputDir = crossRuntime.runtime.path.resolve(distDir, CLIENT_DIR);
534
+ const manifestContent = await crossRuntime.runtime.fs.readTextFile(chunkManifestFile);
535
+ const manifest = JSON.parse(manifestContent);
536
+ // A framework plugin without saveModuleMap writes no module map
537
+ const moduleMapPath = crossRuntime.runtime.path.resolve(clientOutputDir, MODULE_MAP_FILENAME);
538
+ const moduleMap = (await crossRuntime.runtime.fs.exists(moduleMapPath))
539
+ ? JSON.parse(await crossRuntime.runtime.fs.readTextFile(moduleMapPath))
540
+ : {};
541
+ return {
542
+ success: true,
543
+ buildId: manifest.buildId,
544
+ clientBundle: crossRuntime.runtime.path.resolve(clientOutputDir, manifest.entrypoint),
545
+ moduleMap,
546
+ clientComponents: Object.keys(moduleMap).length,
547
+ duration: 0,
548
+ timestamp: manifest.timestamp,
549
+ };
550
+ }
551
+ /**
552
+ * Watch mode for Hot Module Replacement (HMR)
553
+ * Monitors source files and rebuilds on changes
554
+ * @param context - Build context
555
+ * @param onChange - Callback invoked after each rebuild, including a failed
556
+ * one; check result.success before serving or announcing the result. The
557
+ * next rebuild waits for the promise it returns, so it can load the
558
+ * rebuilt output before dist/ changes again.
559
+ * @returns File system watcher
560
+ */
561
+ export function watch(context, onChange) {
562
+ const { srcDir, distDir, projectRoot } = context;
563
+ buildLogger.debug("👁️ Watch mode enabled, monitoring for changes...");
564
+ // The cache lives as long as this watcher, unless the caller passed one
565
+ const cache = context.cache ?? new buildCache.BuildCache();
566
+ const contextWithCache = { ...context, cache };
567
+ // Compute relative dist directory path for filtering
568
+ const relativeDistDir = crossRuntime.runtime.path.relative(projectRoot, distDir);
569
+ // Build list of paths to watch
570
+ const watchPaths = [srcDir];
571
+ const watcher = crossRuntime.runtime.fs.watch(watchPaths);
572
+ let building = false;
573
+ let pendingRebuild = false;
574
+ const changedFiles = new Set();
575
+ // Debounce timer to batch rapid file changes
576
+ let debounceTimer = null;
577
+ const DEBOUNCE_MS = 50;
578
+ /**
579
+ * Trigger a build with proper handling of pending rebuilds
580
+ * Uses do-while loop to ensure pending rebuilds are processed immediately
581
+ */
582
+ async function triggerBuild() {
583
+ if (building) {
584
+ pendingRebuild = true;
585
+ return;
586
+ }
587
+ building = true;
588
+ // Keep rebuilding while there are pending changes
589
+ do {
590
+ pendingRebuild = false;
591
+ try {
592
+ // Check what types of files changed
593
+ const changedFilesList = Array.from(changedFiles);
594
+ // Invalidate cache entries for changed files
595
+ cache.invalidateFiles(changedFilesList.map((f) => crossRuntime.runtime.path.resolve(projectRoot, f)));
596
+ const hasCssChanges = changedFilesList.some((file) => file.endsWith(".css"));
597
+ const hasJsChanges = changedFilesList.some((file) => file.match(/\.(tsx?|jsx?)$/));
598
+ // Determine build mode:
599
+ // - cssOnly: only CSS changed, use fast path (no JS rebuild)
600
+ // - skipCss: only JS changed, skip CSS processing
601
+ // - full build: both changed
602
+ const cssOnly = hasCssChanges && !hasJsChanges;
603
+ const skipCss = !hasCssChanges && hasJsChanges;
604
+ // Convert changed files to absolute paths for incremental virtual source
605
+ const changedFilesAbsolute = new Set(changedFilesList.map((f) => crossRuntime.runtime.path.resolve(projectRoot, f)));
606
+ // Builds write to the same dist directory, so they run one after
607
+ // another; changes that arrive during a build wait for the next pass.
608
+ // oxlint-disable-next-line no-await-in-loop
609
+ const result = await build(contextWithCache, {
610
+ skipCss,
611
+ cssOnly,
612
+ changedFiles: changedFilesAbsolute,
613
+ });
614
+ // Attach the files this build covered to the build result
615
+ result.changedFiles = changedFilesList;
616
+ // A failed build keeps its changed files, so the next change
617
+ // rebuilds them too: a CSS change in a failed build is not skipped
618
+ // by a later JS-only build. build() has logged the failure. Files
619
+ // that changed during this build stay for the pending rebuild.
620
+ if (result.success) {
621
+ buildLogger.debug(`✅ Rebuild complete (${result.duration.toFixed(0)}ms)`);
622
+ for (const builtFile of changedFilesList) {
623
+ changedFiles.delete(builtFile);
624
+ }
625
+ }
626
+ // Sequential like the build above: the callback reads dist/, which
627
+ // the next build rewrites.
628
+ // oxlint-disable-next-line no-await-in-loop
629
+ await onChange(result);
630
+ }
631
+ catch (error) {
632
+ // build() reports its own failures in the result, so this is an
633
+ // error thrown by onChange; the next change calls it again.
634
+ buildLogger.with({ error }).error("❌ Rebuild callback failed");
635
+ }
636
+ } while (pendingRebuild);
637
+ building = false;
638
+ }
639
+ (async () => {
640
+ for await (const event of watcher) {
641
+ if (event.kind === "modify" ||
642
+ event.kind === "create" ||
643
+ event.kind === "remove") {
644
+ const eventPath = event.paths[0];
645
+ if (!eventPath)
646
+ continue;
647
+ const changedFile = crossRuntime.runtime.path.relative(projectRoot, eventPath);
648
+ // Skip non-source files (tsx/jsx/css)
649
+ if (!changedFile.match(/\.(tsx?|jsx?|css)$/))
650
+ continue;
651
+ // Skip dist directory (build outputs shouldn't trigger rebuilds)
652
+ // Convert to POSIX format for cross-platform path comparison
653
+ const normalizedChangedFile = crossRuntime.toPosix(changedFile);
654
+ const normalizedDistDir = crossRuntime.toPosix(relativeDistDir);
655
+ if (normalizedChangedFile.startsWith(`${normalizedDistDir}/`)) {
656
+ continue;
657
+ }
658
+ // Skip temporary files (e.g., .temp.css from CSS module processing)
659
+ if (changedFile.includes(".temp."))
660
+ continue;
661
+ buildLogger.debug(`🔄 File changed: ${changedFile}`);
662
+ // Collect changed files for this rebuild
663
+ changedFiles.add(changedFile);
664
+ // Debounce: clear existing timer and set a new one
665
+ // This batches rapid file changes (e.g., editor save operations)
666
+ if (debounceTimer !== null) {
667
+ clearTimeout(debounceTimer);
668
+ }
669
+ debounceTimer = setTimeout(() => {
670
+ debounceTimer = null;
671
+ triggerBuild();
672
+ }, DEBOUNCE_MS);
673
+ }
674
+ }
675
+ })();
676
+ return watcher;
677
+ }
678
+ /**
679
+ * Bundle client code with code splitting. Client bundles always use
680
+ * rolldown (bundler.CLIENT_BUNDLER_BACKEND), whatever context.bundlerBackend
681
+ * says: the import map resolver plugin, which applies config.browserShims, is
682
+ * what keeps server-only modules such as @eserstack/logging out of the browser.
683
+ * @param context - Build context
684
+ * @param clientComponents - Array of client components to bundle
685
+ * @param buildId - Unique build identifier
686
+ * @param timestamp - Build timestamp
687
+ * @returns The bundle's entry file and its chunk manifest, not yet written
688
+ */
689
+ async function bundleClient(context, clientComponents, buildId, timestamp) {
690
+ const { config, projectRoot, distDir } = context;
691
+ // Generate entry file that includes all client components + bootstrap
692
+ const { plugin } = context;
693
+ if (!plugin.createClientEntry) {
694
+ throw new Error("Framework plugin must implement createClientEntry");
695
+ }
696
+ const generatedEntry = await plugin.createClientEntry(clientComponents, projectRoot, distDir);
697
+ try {
698
+ // Bundle with code splitting, bundling the packages too
699
+ // Pass ALL component files as entrypoints for proper code splitting
700
+ // Rolldown creates separate chunks for each and extracts shared deps (React) into common chunks
701
+ const componentEntrypoints = clientComponents.map((c) => c.filePath);
702
+ const clientOutputDir = crossRuntime.runtime.path.resolve(distDir, CLIENT_DIR);
703
+ // Create import map resolver plugin to handle all bare imports
704
+ // Bare imports resolve from the importing files through node_modules
705
+ // autoMarkExternal: false ensures npm packages are bundled inline for browsers
706
+ // (browsers can't resolve bare specifiers without an import map)
707
+ const importMapPlugin = importMapResolverPlugin.createImportMapResolverPlugin({
708
+ projectRoot,
709
+ browserShims: config.browserShims,
710
+ autoMarkExternal: false,
711
+ });
712
+ const define = {
713
+ ...settings.PRODUCTION_SETTINGS.define,
714
+ };
715
+ const bundleResult = await bundler.bundle({
716
+ entrypoints: [generatedEntry, ...componentEntrypoints],
717
+ outputDir: clientOutputDir,
718
+ projectRoot,
719
+ minify: settings.PRODUCTION_SETTINGS.minify,
720
+ splitting: settings.PRODUCTION_SETTINGS.codeSplitting,
721
+ platform: "browser",
722
+ sourcemap: settings.PRODUCTION_SETTINGS.sourceMaps,
723
+ plugins: [importMapPlugin],
724
+ define,
725
+ }, clientComponents, bundler.CLIENT_BUNDLER_BACKEND);
726
+ // Generate chunk manifest (HMR disabled for non-runtime builds)
727
+ const manifest = chunkManifest.generateChunkManifest(buildId, timestamp, bundleResult, clientComponents, config.logLevel, false);
728
+ // Clean up generated entry file
729
+ try {
730
+ await crossRuntime.runtime.fs.remove(generatedEntry);
731
+ }
732
+ catch {
733
+ // Ignore if file doesn't exist
734
+ }
735
+ bundler.logBundleStats(bundleResult);
736
+ chunkManifest.logManifest(manifest);
737
+ return { entrypoint: bundleResult.entrypoint, manifest };
738
+ }
739
+ catch (error) {
740
+ // Clean up on error
741
+ try {
742
+ await crossRuntime.runtime.fs.remove(generatedEntry);
743
+ }
744
+ catch {
745
+ // Ignore cleanup errors
746
+ }
747
+ throw error;
748
+ }
749
+ }
750
+ /**
751
+ * Copy public assets to dist
752
+ * @param projectRoot - Project root directory
753
+ * @param distDir - Destination directory
754
+ */
755
+ async function copyPublicAssets(projectRoot, distDir) {
756
+ const publicDir = crossRuntime.runtime.path.resolve(projectRoot, "public");
757
+ if (!(await crossRuntime.runtime.fs.exists(publicDir))) {
758
+ return;
759
+ }
760
+ // Copy all files and directories recursively
761
+ for await (const entry of crossRuntime.runtime.fs.readDir(publicDir)) {
762
+ const sourcePath = crossRuntime.runtime.path.resolve(publicDir, entry.name);
763
+ const destPath = crossRuntime.runtime.path.resolve(distDir, entry.name);
764
+ await copyPath.copyPath(sourcePath, destPath);
765
+ }
766
+ }
767
+ /**
768
+ * Copy translation JSON files to server directory
769
+ * Copies {srcDir}/app/messages/*.json to dist/server/{srcDirName}/app/messages/
770
+ * Also copies {srcDir}/lib/i18n/messages/*.json to dist/server/{srcDirName}/lib/i18n/messages/
771
+ * @param srcDir - Source directory (absolute path)
772
+ * @param serverDistDir - Server distribution directory (dist/server)
773
+ * @param projectRoot - Project root directory for computing srcDirName
774
+ */
775
+ async function copyTranslationFiles(srcDir, serverDistDir, projectRoot) {
776
+ let totalCopied = 0;
777
+ // Get srcDir name relative to project root (e.g., "src")
778
+ const srcDirName = crossRuntime.runtime.path.relative(projectRoot, srcDir);
779
+ // Copy from {srcDir}/app/messages/ (legacy location)
780
+ const appMessagesSourceDir = crossRuntime.runtime.path.resolve(srcDir, "app/messages");
781
+ const appMessagesDestDir = crossRuntime.runtime.path.resolve(serverDistDir, srcDirName, "app/messages");
782
+ if (await crossRuntime.runtime.fs.exists(appMessagesSourceDir)) {
783
+ await crossRuntime.runtime.fs.ensureDir(appMessagesDestDir);
784
+ for await (const entry of crossRuntime.runtime.fs.readDir(appMessagesSourceDir)) {
785
+ if (entry.isFile && entry.name.endsWith(".json")) {
786
+ const sourcePath = crossRuntime.runtime.path.resolve(appMessagesSourceDir, entry.name);
787
+ const destPath = crossRuntime.runtime.path.resolve(appMessagesDestDir, entry.name);
788
+ await copyPath.copyPath(sourcePath, destPath);
789
+ totalCopied++;
790
+ }
791
+ }
792
+ }
793
+ // Copy from {srcDir}/lib/i18n/messages/ (loader.ts location)
794
+ const i18nMessagesSourceDir = crossRuntime.runtime.path.resolve(srcDir, "lib/i18n/messages");
795
+ const i18nMessagesDestDir = crossRuntime.runtime.path.resolve(serverDistDir, srcDirName, "lib/i18n/messages");
796
+ if (await crossRuntime.runtime.fs.exists(i18nMessagesSourceDir)) {
797
+ await crossRuntime.runtime.fs.ensureDir(i18nMessagesDestDir);
798
+ for await (const entry of crossRuntime.runtime.fs.readDir(i18nMessagesSourceDir)) {
799
+ if (entry.isFile && entry.name.endsWith(".json")) {
800
+ const sourcePath = crossRuntime.runtime.path.resolve(i18nMessagesSourceDir, entry.name);
801
+ const destPath = crossRuntime.runtime.path.resolve(i18nMessagesDestDir, entry.name);
802
+ await copyPath.copyPath(sourcePath, destPath);
803
+ totalCopied++;
804
+ }
805
+ }
806
+ }
807
+ if (totalCopied > 0) {
808
+ buildLogger.debug(`✓ Copied ${totalCopied} translation file(s)`);
809
+ }
810
+ else {
811
+ buildLogger.debug("No messages directories found, skipping translation files");
812
+ }
813
+ }
814
+ /**
815
+ * Compile the global stylesheet, {srcDir}/app/styles/global.css, into
816
+ * styles.css: the CSS plugin compiles it when it claims it, otherwise the CSS
817
+ * processor transforms it.
818
+ * @param options - Plugin, processor and directories
819
+ * @returns Whether styles.css was written; false when there is no global
820
+ * stylesheet
821
+ */
822
+ async function processCssFiles(options) {
823
+ const { plugin, processor, srcDir, projectRoot, outputDir } = options;
824
+ const cssInput = crossRuntime.runtime.path.resolve(srcDir, "app/styles/global.css");
825
+ const cssOutput = crossRuntime.runtime.path.resolve(outputDir, "styles.css");
826
+ // Check if CSS source file exists
827
+ if (!(await crossRuntime.runtime.fs.exists(cssInput))) {
828
+ buildLogger.debug("No CSS source file found, skipping CSS processing");
829
+ return false;
830
+ }
831
+ const source = await crossRuntime.runtime.fs.readTextFile(cssInput);
832
+ let compiled;
833
+ try {
834
+ compiled = await cssProcessor.compileStylesheet(source, {
835
+ plugin,
836
+ processor,
837
+ context: { projectRoot, cssPath: cssInput, isModule: false },
838
+ minify: true,
839
+ });
840
+ }
841
+ catch (error) {
842
+ // Not logged here: build() logs the error once, with its cause chain
843
+ const message = error instanceof Error ? error.message : String(error);
844
+ throw types.buildErrors.cssError(`${cssInput}: ${message}`, {
845
+ cause: error,
846
+ });
847
+ }
848
+ await crossRuntime.runtime.fs.ensureDir(outputDir);
849
+ await crossRuntime.runtime.fs.writeTextFile(cssOutput, compiled);
850
+ buildLogger.debug(`✓ CSS processed with ${processor.name}`);
851
+ return true;
852
+ }
853
+ /**
854
+ * Rebuild only the stylesheets, for a change that touched nothing but CSS.
855
+ * styles.css comes out as a full build writes it, the compiled global
856
+ * stylesheet followed by the CSS module styles, and the critical, deferred
857
+ * and universal CSS are derived from it again, since the pages load those.
858
+ * The JavaScript in dist/ stays, and so does its build id.
859
+ * @param context - Build context
860
+ * @param newBuildId - Id reported when dist/ holds no finished build yet
861
+ * @param startTime - When the build started, from performance.now()
862
+ * @returns Build result with the build id of the code in dist/
863
+ */
864
+ async function rebuildStylesheets(context, newBuildId, startTime) {
865
+ const { srcDir, projectRoot, distDir, cssPlugin } = context;
866
+ buildLogger.debug("⚡ CSS-only rebuild (fast path)");
867
+ const timestamp = Date.now();
868
+ const clientOutputDir = crossRuntime.runtime.path.resolve(distDir, CLIENT_DIR);
869
+ const codeManifest = await readChunkManifest(context.chunkManifestFile);
870
+ // The CSS modules are compiled before styles.css is touched, so a module
871
+ // that fails to compile leaves the previous styles.css in place.
872
+ const cssModulePaths = await scanCssModuleFiles(srcDir);
873
+ const cssModuleResults = cssModulePaths.length > 0
874
+ ? await processCssModulesFiles(projectRoot, clientOutputDir, context.config, {
875
+ skipCss: true,
876
+ cssModulePaths,
877
+ cache: context.cache,
878
+ plugin: cssPlugin,
879
+ })
880
+ : new Map();
881
+ const wroteGlobalStyles = cssPlugin !== undefined &&
882
+ (await processCssFiles({
883
+ plugin: cssPlugin,
884
+ processor: context.cssProcessor,
885
+ srcDir,
886
+ projectRoot,
887
+ outputDir: clientOutputDir,
888
+ }));
889
+ if (!wroteGlobalStyles) {
890
+ // As in a full build, the CSS module styles then make up styles.css on
891
+ // their own; appending them to the previous file would repeat them.
892
+ await removeFileIfExists(crossRuntime.runtime.path.resolve(clientOutputDir, "styles.css"));
893
+ }
894
+ await appendCssModulesToStyles(cssModuleResults, clientOutputDir);
895
+ if (cssPlugin !== undefined) {
896
+ await writeDerivedStylesheets(cssPlugin, clientOutputDir);
897
+ }
898
+ const duration = performance.now() - startTime;
899
+ buildLogger.info(`⚡ CSS rebuild completed (${duration.toFixed(0)}ms)`);
900
+ return {
901
+ success: true,
902
+ buildId: codeManifest?.buildId ?? newBuildId,
903
+ clientBundle: "", // Preserved from previous build
904
+ moduleMap: {}, // Preserved from previous build
905
+ clientComponents: 0,
906
+ duration,
907
+ timestamp,
908
+ };
909
+ }
910
+ /**
911
+ * Remove a file; a file that does not exist is already removed.
912
+ */
913
+ async function removeFileIfExists(filePath) {
914
+ try {
915
+ await crossRuntime.runtime.fs.remove(filePath);
916
+ }
917
+ catch (error) {
918
+ if (!(error instanceof crossRuntime.NotFoundError)) {
919
+ throw error;
920
+ }
921
+ }
922
+ }
923
+ /**
924
+ * Derive the critical, deferred and universal CSS from styles.css with the
925
+ * CSS plugin (build steps 16 and 17). Each is optional: when the plugin
926
+ * cannot derive one, pages load the full styles.css instead.
927
+ * @param cssPlugin - CSS plugin that extracts the critical and universal CSS
928
+ * @param clientOutputDir - Client output directory containing styles.css
929
+ */
930
+ async function writeDerivedStylesheets(cssPlugin, clientOutputDir) {
931
+ // Step 16: Extract critical CSS for faster initial render
932
+ buildLogger.debug("✨ Step 16: Extracting critical CSS...");
933
+ const criticalCssResult = await extractCriticalPageCssFiles(cssPlugin, clientOutputDir);
934
+ if (criticalCssResult) {
935
+ buildLogger.debug(` Critical: ${criticalCssResult.criticalPath}, Deferred: ${criticalCssResult.deferredPath}`);
936
+ }
937
+ // Step 17: Generate universal CSS (base/theme styles)
938
+ buildLogger.debug("🎨 Step 17: Generating universal CSS...");
939
+ const universalCssPath = await generateCriticalUniversalCssFile(cssPlugin, clientOutputDir);
940
+ if (universalCssPath) {
941
+ buildLogger.debug(` Universal: ${universalCssPath}`);
942
+ }
943
+ }
944
+ /**
945
+ * Extract critical CSS from processed styles
946
+ * Splits CSS into critical (inlined) and deferred (async loaded)
947
+ *
948
+ * Uses the CSS plugin's extractCriticalCss method if available.
949
+ * The extraction is framework-aware (e.g., Tailwind v4 layer handling).
950
+ *
951
+ * @param plugin - CSS plugin to use for extraction
952
+ * @param distDir - Distribution directory containing styles.css
953
+ */
954
+ async function extractCriticalPageCssFiles(plugin, distDir) {
955
+ // Check if plugin supports critical CSS extraction
956
+ if (!plugin.extractCriticalCss) {
957
+ buildLogger.debug("CSS plugin doesn't support critical CSS extraction, skipping");
958
+ return null;
959
+ }
960
+ const stylesPath = crossRuntime.runtime.path.resolve(distDir, "styles.css");
961
+ // Check if styles.css exists
962
+ if (!(await crossRuntime.runtime.fs.exists(stylesPath))) {
963
+ buildLogger.debug("No styles.css found, skipping critical CSS extraction");
964
+ return null;
965
+ }
966
+ try {
967
+ const fullCss = await crossRuntime.runtime.fs.readTextFile(stylesPath);
968
+ // Representative HTML template covering common layout patterns
969
+ // This ensures all layout-critical utilities are included
970
+ const representativeHtml = `
971
+ <!DOCTYPE html>
972
+ <html lang="en">
973
+ <head></head>
974
+ <body>
975
+ <div id="root" class="flex flex-col lg:flex-row min-h-screen bg-neutral-50">
976
+ <aside class="w-full lg:w-64 bg-surface border-b lg:border-b-0 lg:border-r border-neutral-200 flex-shrink-0">
977
+ <div class="lg:sticky lg:top-0 p-4 lg:p-6">
978
+ <nav class="space-y-4">
979
+ <a href="#" class="flex items-center gap-2 text-neutral-600 hover:text-primary-600">Link</a>
980
+ </nav>
981
+ </div>
982
+ </aside>
983
+ <div class="flex-1 flex flex-col">
984
+ <main class="flex-1">
985
+ <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12 lg:py-20">
986
+ <h1 class="text-3xl sm:text-4xl lg:text-5xl font-bold text-neutral-900 mb-4">Title</h1>
987
+ <h2 class="text-lg font-bold text-neutral-900 mb-2">Subtitle</h2>
988
+ <p class="text-neutral-600 text-lg mb-6">Description</p>
989
+ <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
990
+ <div class="bg-surface rounded-lg border border-neutral-200 p-4 shadow-sm">Card</div>
991
+ </div>
992
+ <div class="flex flex-wrap gap-4 items-center justify-center">
993
+ <button class="btn" data-variant="primary">Primary</button>
994
+ <button class="btn" data-variant="secondary">Secondary</button>
995
+ </div>
996
+ </div>
997
+ </main>
998
+ <footer class="flex flex-wrap items-center justify-center gap-6 p-8 text-sm border-t border-neutral-200 bg-surface min-h-[5.5rem]">
999
+ <a href="#" class="flex items-center gap-2 text-neutral-600 hover:text-primary-600">Footer Link</a>
1000
+ </footer>
1001
+ </div>
1002
+ </div>
1003
+ </body>
1004
+ </html>
1005
+ `;
1006
+ // Use plugin's extractCriticalCss method with comprehensive force-include patterns
1007
+ const result = plugin.extractCriticalCss(fullCss, representativeHtml, {
1008
+ forceInclude: [
1009
+ // Layout utilities - MUST be in critical CSS
1010
+ /^\.flex/,
1011
+ /^\.grid/,
1012
+ /^\.block/,
1013
+ /^\.inline/,
1014
+ /^\.items-/,
1015
+ /^\.justify-/,
1016
+ /^\.gap-/,
1017
+ /^\.space-/,
1018
+ /^\.min-h-/,
1019
+ /^\.max-w-/,
1020
+ /^\.w-/,
1021
+ /^\.h-/,
1022
+ /^\.mx-/,
1023
+ /^\.my-/,
1024
+ /^\.px-/,
1025
+ /^\.py-/,
1026
+ /^\.p-/,
1027
+ /^\.m-/,
1028
+ /^\.mt-/,
1029
+ /^\.mb-/,
1030
+ /^\.ml-/,
1031
+ /^\.mr-/,
1032
+ /^\.pt-/,
1033
+ /^\.pb-/,
1034
+ /^\.pl-/,
1035
+ /^\.pr-/,
1036
+ // Responsive variants
1037
+ /^\.sm:/,
1038
+ /^\.md:/,
1039
+ /^\.lg:/,
1040
+ /^\.xl:/,
1041
+ /^\.2xl:/,
1042
+ // Background and text colors for initial render
1043
+ /^\.bg-neutral-/,
1044
+ /^\.bg-surface/,
1045
+ /^\.bg-primary-/,
1046
+ /^\.text-neutral-/,
1047
+ /^\.text-primary-/,
1048
+ /^\.text-white/,
1049
+ // Border utilities
1050
+ /^\.border/,
1051
+ /^\.rounded/,
1052
+ // Typography
1053
+ /^\.text-sm/,
1054
+ /^\.text-lg/,
1055
+ /^\.text-xl/,
1056
+ /^\.text-2xl/,
1057
+ /^\.text-3xl/,
1058
+ /^\.text-4xl/,
1059
+ /^\.text-5xl/,
1060
+ /^\.font-/,
1061
+ /^\.leading-/,
1062
+ // Visibility and overflow
1063
+ /^\.overflow-/,
1064
+ /^\.visible/,
1065
+ /^\.invisible/,
1066
+ /^\.hidden/,
1067
+ // Position
1068
+ /^\.relative/,
1069
+ /^\.absolute/,
1070
+ /^\.fixed/,
1071
+ /^\.sticky/,
1072
+ // Shadows
1073
+ /^\.shadow/,
1074
+ // Base selectors
1075
+ /^html/,
1076
+ /^body/,
1077
+ /^#root/,
1078
+ /^\*/,
1079
+ ],
1080
+ });
1081
+ // Save critical and deferred CSS
1082
+ const criticalPath = crossRuntime.runtime.path.resolve(distDir, "styles.critical.css");
1083
+ const deferredPath = crossRuntime.runtime.path.resolve(distDir, "styles.deferred.css");
1084
+ await crossRuntime.runtime.fs.writeTextFile(criticalPath, result.critical);
1085
+ await crossRuntime.runtime.fs.writeTextFile(deferredPath, result.deferred);
1086
+ const stats = result.stats;
1087
+ if (stats) {
1088
+ buildLogger.debug(`✓ Critical CSS extracted: ${stats.criticalSize} bytes critical, ${stats.deferredSize} bytes deferred`);
1089
+ }
1090
+ else {
1091
+ buildLogger.debug("✓ Critical CSS extracted");
1092
+ }
1093
+ return { criticalPath, deferredPath };
1094
+ }
1095
+ catch (error) {
1096
+ // Non-fatal: pages fall back to loading the full stylesheet
1097
+ buildLogger
1098
+ .with({ error })
1099
+ .warn("Critical CSS extraction failed, loading full CSS instead");
1100
+ return null;
1101
+ }
1102
+ }
1103
+ /**
1104
+ * Generate universal CSS (base/theme styles) from compiled CSS output
1105
+ * This CSS contains reset styles and theme variables.
1106
+ *
1107
+ * Uses the CSS plugin's extractUniversalCss method if available.
1108
+ *
1109
+ * @param plugin - CSS plugin to use for extraction
1110
+ * @param distDir - Distribution directory containing styles.css
1111
+ * @returns Path to the generated universal CSS file, or null if generation failed
1112
+ */
1113
+ async function generateCriticalUniversalCssFile(plugin, distDir) {
1114
+ // Check if plugin supports universal CSS extraction
1115
+ if (!plugin.extractUniversalCss) {
1116
+ buildLogger.debug("CSS plugin doesn't support universal CSS extraction, skipping");
1117
+ return null;
1118
+ }
1119
+ const stylesPath = crossRuntime.runtime.path.resolve(distDir, "styles.css");
1120
+ // Check if styles.css exists
1121
+ if (!(await crossRuntime.runtime.fs.exists(stylesPath))) {
1122
+ buildLogger.debug("No styles.css found, skipping universal CSS generation");
1123
+ return null;
1124
+ }
1125
+ try {
1126
+ const compiledCss = await crossRuntime.runtime.fs.readTextFile(stylesPath);
1127
+ // Use plugin's extractUniversalCss method
1128
+ const result = plugin.extractUniversalCss(compiledCss);
1129
+ // Save universal CSS
1130
+ const universalPath = crossRuntime.runtime.path.resolve(distDir, "styles.universal.css");
1131
+ await crossRuntime.runtime.fs.writeTextFile(universalPath, result.css);
1132
+ buildLogger.debug(`✓ Universal CSS generated: ${result.css.length} bytes`);
1133
+ return universalPath;
1134
+ }
1135
+ catch (error) {
1136
+ // Non-fatal: the server falls back to its default universal CSS
1137
+ buildLogger
1138
+ .with({ error })
1139
+ .warn("Universal CSS generation failed, using the default instead");
1140
+ return null;
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Clean build directory
1145
+ * @param distDir - Distribution directory to clean
1146
+ */
1147
+ async function cleanBuildDir(distDir, preserveCss) {
1148
+ if (!(await crossRuntime.runtime.fs.exists(distDir))) {
1149
+ return;
1150
+ }
1151
+ if (preserveCss) {
1152
+ // Selective cleanup: preserve CSS files in client directory
1153
+ buildLogger.debug("🧹 Cleaning build directory (preserving CSS)");
1154
+ // Remove server directory completely
1155
+ const serverDir = crossRuntime.runtime.path.resolve(distDir, SERVER_DIR);
1156
+ if (await crossRuntime.runtime.fs.exists(serverDir)) {
1157
+ await crossRuntime.runtime.fs.remove(serverDir, { recursive: true });
1158
+ }
1159
+ // Clean client directory but preserve CSS files
1160
+ const clientDir = crossRuntime.runtime.path.resolve(distDir, CLIENT_DIR);
1161
+ if (await crossRuntime.runtime.fs.exists(clientDir)) {
1162
+ for await (const entry of crossRuntime.runtime.fs.readDir(clientDir)) {
1163
+ // Preserve CSS files and font directories
1164
+ if (entry.name.endsWith(".css") ||
1165
+ entry.name === "fonts" ||
1166
+ entry.name === "fonts.css" ||
1167
+ entry.name === "font-preloads.json") {
1168
+ continue;
1169
+ }
1170
+ const entryPath = crossRuntime.runtime.path.resolve(clientDir, entry.name);
1171
+ await crossRuntime.runtime.fs.remove(entryPath, { recursive: true });
1172
+ }
1173
+ }
1174
+ }
1175
+ else {
1176
+ // Full cleanup
1177
+ await crossRuntime.runtime.fs.remove(distDir, { recursive: true });
1178
+ buildLogger.debug("🧹 Cleaned build directory");
1179
+ }
1180
+ }
1181
+ /**
1182
+ * Self-host the configured fonts with the font optimizer, and write the
1183
+ * @font-face rules to fonts.css and the preload hints to font-preloads.json
1184
+ * @param optimizer - Font optimizer from the build plugins
1185
+ * @param distDir - Client output directory
1186
+ * @param fontDefinitions - Font configuration
1187
+ */
1188
+ async function optimizeFonts(optimizer, distDir, fontDefinitions) {
1189
+ if (fontDefinitions.length === 0) {
1190
+ buildLogger.debug("✓ No fonts configured, skipping font optimization");
1191
+ return;
1192
+ }
1193
+ const fontsDir = crossRuntime.runtime.path.resolve(distDir, "fonts");
1194
+ const publicPath = "/fonts";
1195
+ try {
1196
+ const result = await optimizer.optimize(fontDefinitions, {
1197
+ outputDir: fontsDir,
1198
+ publicPath,
1199
+ });
1200
+ if (result === null) {
1201
+ buildLogger.debug(`✓ Font optimizer ${optimizer.name} handles none of the configured fonts, skipping`);
1202
+ return;
1203
+ }
1204
+ // Save font CSS to a file that can be inlined in HTML
1205
+ const fontCssPath = crossRuntime.runtime.path.resolve(distDir, "fonts.css");
1206
+ await crossRuntime.runtime.fs.writeTextFile(fontCssPath, result.fontFaceCss);
1207
+ // Save preload hints to a file for HTML shell integration
1208
+ const preloadHintsPath = crossRuntime.runtime.path.resolve(distDir, "font-preloads.json");
1209
+ await crossRuntime.runtime.fs.writeTextFile(preloadHintsPath, JSON.stringify(result.preloadHints, null, 2));
1210
+ buildLogger.debug(`✓ Fonts optimized: ${result.fileCount} file(s), ${(result.totalSize / 1024).toFixed(2)} KB`);
1211
+ }
1212
+ catch (error) {
1213
+ // Font optimization is optional, so the build continues without it
1214
+ buildLogger
1215
+ .with({ error })
1216
+ .warn("Font optimization failed, continuing without it");
1217
+ }
1218
+ }
1219
+ /**
1220
+ * Scan for all CSS module files in a directory
1221
+ * @param srcDir - Source directory to scan
1222
+ * @returns Array of absolute paths to .module.css files
1223
+ */
1224
+ async function scanCssModuleFiles(srcDir) {
1225
+ const cssModuleFiles = [];
1226
+ async function scanDirectory(dir) {
1227
+ for await (const entry of crossRuntime.runtime.fs.readDir(dir)) {
1228
+ const fullPath = crossRuntime.runtime.path.resolve(dir, entry.name);
1229
+ if (entry.isDirectory) {
1230
+ await scanDirectory(fullPath);
1231
+ }
1232
+ else if (entry.isFile && entry.name.endsWith(".module.css")) {
1233
+ cssModuleFiles.push(fullPath);
1234
+ }
1235
+ }
1236
+ }
1237
+ await scanDirectory(srcDir);
1238
+ return cssModuleFiles;
1239
+ }
1240
+ /**
1241
+ * Process CSS Modules files
1242
+ * Finds and processes all .module.css files with Lightning CSS
1243
+ * @param projectRoot - Project root directory
1244
+ * @param distDir - Distribution directory
1245
+ * @param config - Build configuration
1246
+ * @param options - Processing options including plugin
1247
+ */
1248
+ async function processCssModulesFiles(projectRoot, distDir, config, options) {
1249
+ // Use pre-scanned paths if provided, otherwise scan using config.srcDir
1250
+ const cssModuleFiles = options?.cssModulePaths ?? (await scanCssModuleFiles(config.srcDir));
1251
+ if (cssModuleFiles.length === 0) {
1252
+ buildLogger.debug("No CSS modules found, skipping CSS module processing");
1253
+ return new Map();
1254
+ }
1255
+ buildLogger.debug(`Found ${cssModuleFiles.length} CSS module(s)`);
1256
+ try {
1257
+ // Process all CSS modules
1258
+ const results = await cssModules.processCSSModules(cssModuleFiles, {
1259
+ generateDTS: config.cssModuleTypes,
1260
+ projectRoot,
1261
+ cache: options?.cache,
1262
+ plugin: options?.plugin,
1263
+ injectReference: !config.noCssModuleAutoReference,
1264
+ });
1265
+ // Save outputs to output directory (JSON files for bundler resolution)
1266
+ // When skipCss is true, only save JSON files (not processed CSS)
1267
+ for (const [cssPath, result] of results) {
1268
+ // One module's files at a time keeps open file handles bounded; a
1269
+ // project can have more CSS modules than the open-file limit.
1270
+ // oxlint-disable-next-line no-await-in-loop
1271
+ await cssModules.saveCSSModuleOutputs(cssPath, result, distDir, {
1272
+ skipCss: options?.skipCss,
1273
+ projectRoot, // Pass projectRoot for correct relative path calculation
1274
+ });
1275
+ }
1276
+ buildLogger.debug(`✓ Processed ${cssModuleFiles.length} CSS module(s)${config.cssModuleTypes ? " with TypeScript definitions" : ""}`);
1277
+ return results;
1278
+ }
1279
+ catch (error) {
1280
+ const message = error instanceof Error ? error.message : String(error);
1281
+ throw types.buildErrors.cssError(`${cssModuleFiles.length} CSS module(s): ${message}`, { cause: error });
1282
+ }
1283
+ }
1284
+ /**
1285
+ * Copy CSS Module JSON files from src/ to a target directory
1286
+ * @param cssModulePaths - Array of source CSS module paths
1287
+ * @param projectRoot - Project root directory
1288
+ * @param targetDir - Target directory to copy JSON files to
1289
+ */
1290
+ async function copyCssModuleJsonFilesFromSrc(cssModulePaths, projectRoot, targetDir) {
1291
+ let copiedCount = 0;
1292
+ for (const cssPath of cssModulePaths) {
1293
+ // One copy at a time keeps open file handles bounded; a project can have
1294
+ // more CSS modules than the open-file limit.
1295
+ // oxlint-disable-next-line no-await-in-loop
1296
+ const copied = await copyCssModuleJsonFile(cssPath, projectRoot, targetDir);
1297
+ if (copied) {
1298
+ copiedCount++;
1299
+ }
1300
+ }
1301
+ if (copiedCount > 0) {
1302
+ buildLogger.debug(`✓ Copied ${copiedCount} CSS module JSON file(s)`);
1303
+ }
1304
+ }
1305
+ /**
1306
+ * Copy the JSON file of one CSS module from src/ to a target directory
1307
+ * @param cssPath - Source CSS module path
1308
+ * @param projectRoot - Project root directory
1309
+ * @param targetDir - Target directory to copy the JSON file to
1310
+ * @returns Whether the file was copied; a failed copy is logged as a warning
1311
+ */
1312
+ async function copyCssModuleJsonFile(cssPath, projectRoot, targetDir) {
1313
+ // Get relative path from project root
1314
+ const relativePath = crossRuntime.runtime.path.relative(projectRoot, cssPath);
1315
+ // Construct JSON file paths
1316
+ const jsonFilename = crossRuntime.runtime.path.basename(cssPath) + ".json";
1317
+ const sourceJsonPath = crossRuntime.runtime.path.join(projectRoot, crossRuntime.runtime.path.dirname(relativePath), jsonFilename);
1318
+ const targetJsonPath = crossRuntime.runtime.path.join(targetDir, crossRuntime.runtime.path.dirname(relativePath), jsonFilename);
1319
+ // Ensure target directory exists
1320
+ await crossRuntime.runtime.fs.ensureDir(crossRuntime.runtime.path.dirname(targetJsonPath));
1321
+ // Copy JSON file
1322
+ try {
1323
+ await copyPath.copyPath(sourceJsonPath, targetJsonPath);
1324
+ return true;
1325
+ }
1326
+ catch (error) {
1327
+ buildLogger
1328
+ .with({ error })
1329
+ .warn(`copy the CSS module class map of ${relativePath}; skipping it`);
1330
+ return false;
1331
+ }
1332
+ }
1333
+ /**
1334
+ * Append CSS module styles to the main styles.css bundle
1335
+ * @param results - The CSS modules processed earlier in the build, so none is
1336
+ * processed twice
1337
+ * @param clientOutputDir - Client output directory containing styles.css
1338
+ */
1339
+ async function appendCssModulesToStyles(results, clientOutputDir) {
1340
+ // Collect processed CSS content
1341
+ const cssModuleContents = [];
1342
+ for (const [, result] of results) {
1343
+ cssModuleContents.push(result.code);
1344
+ }
1345
+ // Append CSS module styles to main styles.css bundle
1346
+ if (cssModuleContents.length > 0) {
1347
+ const stylesPath = crossRuntime.runtime.path.resolve(clientOutputDir, "styles.css");
1348
+ let existingStyles = "";
1349
+ try {
1350
+ existingStyles = await crossRuntime.runtime.fs.readTextFile(stylesPath);
1351
+ }
1352
+ catch {
1353
+ // styles.css doesn't exist yet, that's fine
1354
+ }
1355
+ // Strip ANSI color codes from both existing styles and CSS module contents
1356
+ // oxlint-disable-next-line no-control-regex
1357
+ existingStyles = existingStyles.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "");
1358
+ const cleanedContents = cssModuleContents.map((content) =>
1359
+ // oxlint-disable-next-line no-control-regex
1360
+ content.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, ""));
1361
+ const combinedStyles = existingStyles + "\n" + cleanedContents.join("\n");
1362
+ await crossRuntime.runtime.fs.writeTextFile(stylesPath, combinedStyles);
1363
+ buildLogger.debug(`✓ Appended ${cssModuleContents.length} CSS module(s) to styles.css`);
1364
+ }
1365
+ }
1366
+ /**
1367
+ * Optimize images for production with the image optimizer: the images under
1368
+ * public/images become responsive variants in the configured formats
1369
+ * @param optimizer - Image optimizer from the build plugins
1370
+ * @param projectRoot - Project root directory
1371
+ * @param distDir - Client output directory
1372
+ * @param config - Build configuration
1373
+ */
1374
+ async function optimizeImagesStep(optimizer, projectRoot, distDir, config) {
1375
+ const imagesInputDir = crossRuntime.runtime.path.resolve(projectRoot, PUBLIC_DIR, "images");
1376
+ // Check if images directory exists
1377
+ if (!(await crossRuntime.runtime.fs.exists(imagesInputDir))) {
1378
+ buildLogger.debug("✓ No images directory found, skipping image optimization");
1379
+ return;
1380
+ }
1381
+ try {
1382
+ const manifest = await optimizer.optimize({
1383
+ inputDir: imagesInputDir,
1384
+ outputDir: crossRuntime.runtime.path.resolve(distDir, "images"),
1385
+ publicPath: "/images",
1386
+ config: config.images,
1387
+ });
1388
+ if (manifest === null) {
1389
+ buildLogger.debug(`✓ Image optimizer ${optimizer.name} optimizes no images, skipping`);
1390
+ return;
1391
+ }
1392
+ const imageCount = Object.keys(manifest.images).length;
1393
+ buildLogger.debug(`✓ Optimized ${imageCount} image(s)`);
1394
+ }
1395
+ catch (error) {
1396
+ // Image optimization is optional, so the build continues without it
1397
+ buildLogger
1398
+ .with({ error })
1399
+ .warn("Image optimization failed, continuing without it");
1400
+ }
1401
+ }