@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
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Common Bundler Interface and Methods
3
+ * Uses @eserstack/bundler directly for bundling operations, on its Rolldown
4
+ * backend.
5
+ */
6
+ import type { ChunkManifest } from "./chunk-manifest.ts";
7
+ import type { ClientComponent, ModuleMap } from "./framework-plugin.ts";
8
+ import type { BundlerPlugin } from "@eserstack/bundler/backends";
9
+ import type { BundlerBackend } from "../config.ts";
10
+ /**
11
+ * Backend for client bundles. Its import map resolver plugin applies
12
+ * config.browserShims and keeps server-only modules out of the browser.
13
+ */
14
+ export declare const CLIENT_BUNDLER_BACKEND: BundlerBackend;
15
+ export type BundleOutput = {
16
+ fileName: string;
17
+ size: number;
18
+ code?: string;
19
+ imports?: string[];
20
+ };
21
+ export type BundleResult = {
22
+ entrypoint: string;
23
+ outputs: Record<string, BundleOutput>;
24
+ manifest: Record<string, string[]>;
25
+ totalSize: number;
26
+ };
27
+ export type BundleOptions = {
28
+ entrypoints: string[];
29
+ outputDir: string;
30
+ /** Project root directory for module resolution */
31
+ projectRoot?: string;
32
+ minify?: boolean;
33
+ splitting?: boolean;
34
+ platform?: "browser" | "node";
35
+ sourcemap?: "external" | "inline" | "none" | boolean;
36
+ /** Bundler plugins for custom resolution and transformation */
37
+ plugins?: BundlerPlugin[];
38
+ /** Global replacements (e.g., process.env.NODE_ENV) */
39
+ define?: Record<string, string>;
40
+ };
41
+ /**
42
+ * Bundle data returned by bundlers
43
+ */
44
+ export type BundleData = {
45
+ /** Client-side JavaScript code */
46
+ clientCode: string | null;
47
+ /** Module map for RSC server rendering */
48
+ moduleMap: ModuleMap;
49
+ /** Chunk manifest for browser */
50
+ chunkManifest: ChunkManifest;
51
+ /** Entry point path */
52
+ entrypoint: string;
53
+ };
54
+ /**
55
+ * Common bundler interface
56
+ * Both RuntimeBundler and PrebuiltBundler implement this
57
+ */
58
+ export interface Bundler {
59
+ /**
60
+ * Get bundle data
61
+ * May trigger rebuild for RuntimeBundler, reads from disk for PrebuiltBundler
62
+ */
63
+ getBundle(): Promise<BundleData>;
64
+ }
65
+ /**
66
+ * Analyze bundle result for statistics
67
+ */
68
+ export declare function analyzeBundleResult(result: BundleResult): {
69
+ chunkCount: number;
70
+ largestChunk: {
71
+ name: string;
72
+ size: number;
73
+ };
74
+ smallestChunk: {
75
+ name: string;
76
+ size: number;
77
+ };
78
+ averageChunkSize: number;
79
+ };
80
+ /**
81
+ * Log bundle statistics using structured logging
82
+ */
83
+ export declare function logBundleStats(result: BundleResult): void;
84
+ /**
85
+ * Bundle with specified backend.
86
+ *
87
+ * @param options - Bundle options
88
+ * @param clientComponents - Client components to bundle
89
+ * @param backend - Bundler backend
90
+ */
91
+ export declare function bundle(options: BundleOptions, clientComponents: ClientComponent[], backend: BundlerBackend): Promise<BundleResult>;
92
+ /**
93
+ * Options for bundling server components
94
+ */
95
+ export type ServerBundleOptions = {
96
+ /** Server component entry points */
97
+ entrypoints: string[];
98
+ /** Output directory for bundled files */
99
+ outputDir: string;
100
+ /** Project root directory */
101
+ projectRoot: string;
102
+ /** External packages to exclude from bundle (loaded at runtime) */
103
+ externals?: string[];
104
+ /** Bundler plugins for custom resolution and transformation */
105
+ plugins?: BundlerPlugin[];
106
+ /** Enable source maps */
107
+ sourcemap?: boolean;
108
+ /** Enable minification (usually false for server code) */
109
+ minify?: boolean;
110
+ };
111
+ /**
112
+ * Result of server component bundling
113
+ */
114
+ export type ServerBundleResult = {
115
+ /** Map of entry point paths to output paths */
116
+ outputMap: Map<string, string>;
117
+ /** Total bundle size */
118
+ totalSize: number;
119
+ /** Number of files generated */
120
+ fileCount: number;
121
+ };
122
+ /**
123
+ * Bundle server components with externals.
124
+ *
125
+ * This function bundles server components for SSR/RSC runtime.
126
+ * Key differences from client bundling:
127
+ * - Platform: "node" (server-side)
128
+ * - The given external packages stay bare imports (not inlined)
129
+ * - No code splitting (each entry stays separate)
130
+ * - Resolves imports at build time for runtime compatibility
131
+ *
132
+ * @param options - Server bundle options
133
+ * @param backend - Bundler backend to use
134
+ * @returns Server bundle result
135
+ */
136
+ export declare function bundleServerComponents(options: ServerBundleOptions, backend: BundlerBackend): Promise<ServerBundleResult>;
@@ -0,0 +1,225 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Common Bundler Interface and Methods
4
+ * Uses @eserstack/bundler directly for bundling operations, on its Rolldown
5
+ * backend.
6
+ */
7
+ import * as logging from "@eserstack/logging";
8
+ import { runtime } from "@eserstack/standards/cross-runtime";
9
+ import * as patterns from "@eserstack/standards/patterns";
10
+ import * as backends from "@eserstack/bundler/backends";
11
+ const bundlerLogger = logging.logger.getLogger(["laroux-bundler", "bundler"]);
12
+ /**
13
+ * Backend for client bundles. Its import map resolver plugin applies
14
+ * config.browserShims and keeps server-only modules out of the browser.
15
+ */
16
+ export const CLIENT_BUNDLER_BACKEND = "rolldown";
17
+ /**
18
+ * Convert @eserstack/bundler result to laroux format.
19
+ */
20
+ function convertBundleResult(result, componentManifest) {
21
+ const outputs = {};
22
+ let totalSize = 0;
23
+ for (const [name, output] of result.outputs) {
24
+ outputs[name] = {
25
+ fileName: name,
26
+ size: output.size,
27
+ };
28
+ totalSize += output.size;
29
+ }
30
+ return {
31
+ entrypoint: result.entrypoint ?? "client.js",
32
+ outputs,
33
+ manifest: componentManifest,
34
+ totalSize: result.totalSize ?? totalSize,
35
+ };
36
+ }
37
+ /**
38
+ * Analyze bundle result for statistics
39
+ */
40
+ export function analyzeBundleResult(result) {
41
+ const chunks = Object.values(result.outputs);
42
+ if (chunks.length === 0) {
43
+ return {
44
+ chunkCount: 0,
45
+ largestChunk: { name: "", size: 0 },
46
+ smallestChunk: { name: "", size: 0 },
47
+ averageChunkSize: 0,
48
+ };
49
+ }
50
+ const sorted = chunks.sort((a, b) => b.size - a.size);
51
+ const largest = sorted[0];
52
+ const smallest = sorted[sorted.length - 1];
53
+ return {
54
+ chunkCount: chunks.length,
55
+ largestChunk: largest
56
+ ? { name: largest.fileName, size: largest.size }
57
+ : { name: "", size: 0 },
58
+ smallestChunk: smallest
59
+ ? { name: smallest.fileName, size: smallest.size }
60
+ : { name: "", size: 0 },
61
+ averageChunkSize: chunks.length > 0 ? result.totalSize / chunks.length : 0,
62
+ };
63
+ }
64
+ /**
65
+ * Log bundle statistics using structured logging
66
+ */
67
+ export function logBundleStats(result) {
68
+ const stats = analyzeBundleResult(result);
69
+ bundlerLogger.debug("📊 Bundle Statistics:", {
70
+ totalSizeKB: (result.totalSize / 1024).toFixed(2),
71
+ chunkCount: stats.chunkCount,
72
+ largestChunk: {
73
+ name: stats.largestChunk.name,
74
+ sizeKB: (stats.largestChunk.size / 1024).toFixed(2),
75
+ },
76
+ smallestChunk: {
77
+ name: stats.smallestChunk.name,
78
+ sizeKB: (stats.smallestChunk.size / 1024).toFixed(2),
79
+ },
80
+ averageChunkSizeKB: (stats.averageChunkSize / 1024).toFixed(2),
81
+ });
82
+ }
83
+ /**
84
+ * Bundle with specified backend.
85
+ *
86
+ * @param options - Bundle options
87
+ * @param clientComponents - Client components to bundle
88
+ * @param backend - Bundler backend
89
+ */
90
+ export async function bundle(options, clientComponents, backend) {
91
+ bundlerLogger.info(`📦 Using bundler backend: ${backend}`);
92
+ bundlerLogger.debug(`Bundling with @eserstack/bundler (${backend})...`);
93
+ bundlerLogger.debug(` Entrypoints: ${options.entrypoints.length}`);
94
+ bundlerLogger.debug(` Output: ${options.outputDir}`);
95
+ bundlerLogger.debug(`Creating bundler: ${backend}`);
96
+ const bundler = backends.createBundler(backend, { entryName: "client" });
97
+ // Build entrypoints map from array
98
+ const entrypoints = {};
99
+ for (let i = 0; i < options.entrypoints.length; i++) {
100
+ const filePath = options.entrypoints[i];
101
+ if (filePath === undefined)
102
+ continue;
103
+ if (i === 0) {
104
+ entrypoints["client"] = filePath;
105
+ }
106
+ else {
107
+ const component = clientComponents.find((c) => c.filePath === filePath);
108
+ if (component !== undefined) {
109
+ entrypoints[component.relativePath] = filePath;
110
+ }
111
+ else {
112
+ entrypoints[`entry-${i}`] = filePath;
113
+ }
114
+ }
115
+ }
116
+ // Convert sourcemap to boolean for @eserstack/bundler
117
+ const sourcemapEnabled = options.sourcemap === true ||
118
+ options.sourcemap === "external" ||
119
+ options.sourcemap === "inline";
120
+ const config = {
121
+ entrypoints,
122
+ outputDir: options.outputDir,
123
+ projectRoot: options.projectRoot,
124
+ format: "esm",
125
+ platform: options.platform ?? "browser",
126
+ codeSplitting: options.splitting !== false,
127
+ minify: options.minify ?? false,
128
+ sourcemap: sourcemapEnabled,
129
+ plugins: options.plugins,
130
+ define: options.define,
131
+ };
132
+ // Run bundle
133
+ const result = await bundler.bundle(config);
134
+ if (!result.success) {
135
+ const errors = result.errors?.map((e) => e.message).join("\n") ?? "Unknown error";
136
+ throw new Error(`Bundle failed: ${errors}`);
137
+ }
138
+ // Build component manifest from entrypointManifest. Rolldown keys it by
139
+ // real path, so a component under a symlinked directory (such as /var on
140
+ // macOS, a link to /private/var) is looked up under its real path as well.
141
+ const manifest = {};
142
+ const realPaths = await Promise.all(clientComponents.map((component) => runtime.fs.realPath(component.filePath)));
143
+ for (const [index, component] of clientComponents.entries()) {
144
+ const realPath = realPaths[index] ?? component.filePath;
145
+ const chunks = result.entrypointManifest?.[component.filePath] ??
146
+ result.entrypointManifest?.[realPath] ??
147
+ [];
148
+ if (chunks.length > 0) {
149
+ manifest[component.filePath] = [...chunks];
150
+ }
151
+ }
152
+ bundlerLogger.debug(` Outputs: ${result.outputs.size} files`);
153
+ bundlerLogger.debug(` Total size: ${((result.totalSize ?? 0) / 1024).toFixed(2)} KB`);
154
+ return convertBundleResult(result, manifest);
155
+ }
156
+ /**
157
+ * Bundle server components with externals.
158
+ *
159
+ * This function bundles server components for SSR/RSC runtime.
160
+ * Key differences from client bundling:
161
+ * - Platform: "node" (server-side)
162
+ * - The given external packages stay bare imports (not inlined)
163
+ * - No code splitting (each entry stays separate)
164
+ * - Resolves imports at build time for runtime compatibility
165
+ *
166
+ * @param options - Server bundle options
167
+ * @param backend - Bundler backend to use
168
+ * @returns Server bundle result
169
+ */
170
+ export async function bundleServerComponents(options, backend) {
171
+ bundlerLogger.info(`📦 Bundling server components with ${backend}`);
172
+ bundlerLogger.debug(` Entrypoints: ${options.entrypoints.length}`);
173
+ bundlerLogger.debug(` Output: ${options.outputDir}`);
174
+ bundlerLogger.debug(` Externals: ${options.externals?.length ?? 0}`);
175
+ const bundler = backends.createBundler(backend, { entryName: "server" });
176
+ // Build entrypoints map - each server component is a separate entry
177
+ // Output preserves the full path structure (e.g., src/app/layout.ts → src/app/layout.js)
178
+ const entrypoints = {};
179
+ for (const filePath of options.entrypoints) {
180
+ // Use relative path from project root as entry name
181
+ let relativePath = filePath
182
+ .replace(options.projectRoot, "")
183
+ .replace(/^\//, "");
184
+ // Strip file extension (src/app/layout.tsx → src/app/layout)
185
+ relativePath = patterns.replaceJsExtension(relativePath, "");
186
+ entrypoints[relativePath] = filePath;
187
+ }
188
+ const config = {
189
+ entrypoints,
190
+ outputDir: options.outputDir,
191
+ format: "esm",
192
+ platform: "node", // Server-side target
193
+ codeSplitting: false, // Each entry stays separate
194
+ minify: options.minify ?? false,
195
+ sourcemap: options.sourcemap ?? false,
196
+ external: options.externals, // Keep these packages as bare imports
197
+ plugins: options.plugins,
198
+ };
199
+ // Run bundle
200
+ const result = await bundler.bundle(config);
201
+ if (!result.success) {
202
+ const errors = result.errors?.map((e) => e.message).join("\n") ?? "Unknown error";
203
+ throw new Error(`Server bundle failed: ${errors}`);
204
+ }
205
+ // Build output map
206
+ const outputMap = new Map();
207
+ for (const [outputPath, output] of result.outputs) {
208
+ if (output.isEntry && result.entrypointManifest !== undefined) {
209
+ // Find the original entry point for this output
210
+ for (const [entryPath, chunks] of Object.entries(result.entrypointManifest)) {
211
+ if (chunks.includes(outputPath)) {
212
+ outputMap.set(entryPath, outputPath);
213
+ break;
214
+ }
215
+ }
216
+ }
217
+ }
218
+ bundlerLogger.debug(` Outputs: ${result.outputs.size} files`);
219
+ bundlerLogger.debug(` Total size: ${((result.totalSize ?? 0) / 1024).toFixed(2)} KB`);
220
+ return {
221
+ outputMap,
222
+ totalSize: result.totalSize ?? 0,
223
+ fileCount: result.outputs.size,
224
+ };
225
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Chunk Manifest Generator
3
+ * Maps client components to their bundle chunks
4
+ *
5
+ * Uses @eserstack/bundler for base chunk manifest types.
6
+ */
7
+ import type { ChunkInfo as BaseChunkInfo, ChunkManifest as BaseChunkManifest } from "@eserstack/bundler";
8
+ import type { BundleResult } from "./bundler.ts";
9
+ import type { ClientComponent } from "./framework-plugin.ts";
10
+ import type { ChunkManifest, ComponentChunkInfo, FileInfo } from "@eserstack/laroux";
11
+ import type { LogLevel } from "@eserstack/laroux/config";
12
+ export type { BaseChunkInfo, BaseChunkManifest };
13
+ /**
14
+ * The bundle outputs do not cover the client components: a component has no
15
+ * chunk mapping, or its mapping names a chunk the bundle did not emit.
16
+ */
17
+ export declare class ChunkManifestError extends Error {
18
+ /** One entry per component or chunk that could not be resolved */
19
+ readonly problems: readonly string[];
20
+ /** What the bundle did produce: output files or mapped entry points */
21
+ readonly available: readonly string[];
22
+ constructor(message: string, problems: readonly string[], available: readonly string[]);
23
+ }
24
+ export type { ChunkManifest, ComponentChunkInfo, FileInfo };
25
+ /**
26
+ * Generate chunk manifest from bundle result and component analysis
27
+ */
28
+ export declare function generateChunkManifest(buildId: string, timestamp: number, bundleResult: BundleResult, components: ClientComponent[], logLevel?: LogLevel, hmrEnabled?: boolean): ChunkManifest;
29
+ /**
30
+ * Save manifest to file
31
+ */
32
+ export declare function saveChunkManifest(manifest: ChunkManifest, outputPath: string): Promise<void>;
33
+ /**
34
+ * Load manifest from file
35
+ */
36
+ export declare function loadChunkManifest(filePath: string): Promise<ChunkManifest>;
37
+ /**
38
+ * Log manifest using structured logging
39
+ */
40
+ export declare function logManifest(manifest: ChunkManifest): void;
@@ -0,0 +1,188 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Chunk Manifest Generator
4
+ * Maps client components to their bundle chunks
5
+ *
6
+ * Uses @eserstack/bundler for base chunk manifest types.
7
+ */
8
+ import { runtime } from "@eserstack/standards/cross-runtime";
9
+ import * as virtualSource from "./virtual-source.js";
10
+ import * as logging from "@eserstack/logging";
11
+ const manifestLogger = logging.logger.getLogger([
12
+ "laroux-bundler",
13
+ "chunk-manifest",
14
+ ]);
15
+ // Constants
16
+ const MANIFEST_VERSION = "1.0";
17
+ /**
18
+ * The bundle outputs do not cover the client components: a component has no
19
+ * chunk mapping, or its mapping names a chunk the bundle did not emit.
20
+ */
21
+ export class ChunkManifestError extends Error {
22
+ /** One entry per component or chunk that could not be resolved */
23
+ problems;
24
+ /** What the bundle did produce: output files or mapped entry points */
25
+ available;
26
+ // Explicit assignment, not parameter properties: Node's erase-only type
27
+ // stripping cannot emit the assignment a parameter property implies.
28
+ constructor(message, problems, available) {
29
+ super(message);
30
+ this.name = "ChunkManifestError";
31
+ this.problems = problems;
32
+ this.available = available;
33
+ }
34
+ }
35
+ /**
36
+ * Generate chunk manifest from bundle result and component analysis
37
+ */
38
+ export function generateChunkManifest(buildId, timestamp, bundleResult, components, logLevel = "info", hmrEnabled = false) {
39
+ manifestLogger.debug(`📋 Generating chunk manifest...`);
40
+ const manifest = {
41
+ version: MANIFEST_VERSION,
42
+ buildId,
43
+ timestamp,
44
+ entrypoint: bundleResult.entrypoint,
45
+ logLevel,
46
+ hmrEnabled,
47
+ chunks: {},
48
+ files: {},
49
+ };
50
+ // Build file info from bundle outputs
51
+ for (const [_path, output] of Object.entries(bundleResult.outputs)) {
52
+ manifest.files[output.fileName] = {
53
+ name: output.fileName,
54
+ size: output.size,
55
+ hash: extractHash(output.fileName) ?? undefined,
56
+ };
57
+ }
58
+ // Map each component to its chunks using ES Module specifiers
59
+ const missingChunks = [];
60
+ for (const component of components) {
61
+ const chunks = findChunksForComponent(component, bundleResult);
62
+ // First chunk is the main chunk, rest are dependencies
63
+ const [mainChunk, ...depChunks] = chunks;
64
+ if (!mainChunk) {
65
+ manifestLogger.warn(`No chunks found for ${component.relativePath}`);
66
+ continue;
67
+ }
68
+ // Validate that all referenced chunks exist in the bundle outputs
69
+ const allChunks = [mainChunk, ...depChunks];
70
+ for (const chunkFile of allChunks) {
71
+ if (!manifest.files[chunkFile]) {
72
+ missingChunks.push(`${component.relativePath} references ${chunkFile}, but it's not in bundle outputs`);
73
+ }
74
+ }
75
+ // Normalize the key to match module-map format (strip _bundle_src/ prefix)
76
+ const manifestKey = normalizeManifestKey(component.relativePath);
77
+ manifest.chunks[manifestKey] = {
78
+ main: stripChunkDecorations(mainChunk),
79
+ deps: depChunks.map(stripChunkDecorations),
80
+ size: calculateTotalSize(chunks, manifest.files),
81
+ };
82
+ // Only include exportName if it's not "default" (byte optimization)
83
+ const exportName = component.exportNames[0] ?? "default";
84
+ if (exportName !== "default") {
85
+ manifest.chunks[manifestKey].exportName = exportName;
86
+ }
87
+ manifestLogger.debug(` ${manifestKey} → main: ${mainChunk}, deps: [${depChunks.join(", ")}]`);
88
+ }
89
+ // Fail the build if validation found issues; the build logs the error
90
+ if (missingChunks.length > 0) {
91
+ const availableFiles = Object.keys(manifest.files);
92
+ throw new ChunkManifestError(`chunk manifest: ${missingChunks.length} chunk(s) referenced but not found in bundle outputs: ${missingChunks.join("; ")}. Bundle outputs: ${availableFiles.join(", ")}`, missingChunks, availableFiles);
93
+ }
94
+ manifestLogger.debug(`✅ Manifest generated`);
95
+ manifestLogger.debug(` Components: ${Object.keys(manifest.chunks).length}`);
96
+ manifestLogger.debug(` Chunks: ${Object.keys(manifest.files).length}`);
97
+ manifestLogger.debug(` Validation: All referenced chunks exist`);
98
+ return manifest;
99
+ }
100
+ /**
101
+ * Find which chunks contain a specific component
102
+ *
103
+ * Strategy (Code Splitting Mode):
104
+ * 1. Use the bundleResult.manifest mapping (required)
105
+ * 2. This contains the actual chunk files the bundler generated
106
+ * 3. Throws error if manifest mapping is missing (fail-fast)
107
+ */
108
+ function findChunksForComponent(component, bundleResult) {
109
+ // Check if bundleResult has manifest mapping for this component
110
+ const manifestChunks = bundleResult.manifest[component.filePath];
111
+ if (manifestChunks === undefined || manifestChunks.length === 0) {
112
+ // The bundler did not map this component to any chunk, which a working
113
+ // bundler never does; the build logs the error
114
+ const availableMappings = Object.keys(bundleResult.manifest);
115
+ throw new ChunkManifestError(`chunk manifest: no chunks found for ${component.relativePath} (${component.filePath}); ` +
116
+ `the bundler did not analyze the component's dependencies. Mapped entry points: ${availableMappings.join(", ")}`, [component.filePath], availableMappings);
117
+ }
118
+ return manifestChunks;
119
+ }
120
+ /**
121
+ * Calculate total size of chunks
122
+ */
123
+ function calculateTotalSize(chunkNames, files) {
124
+ return chunkNames.reduce((total, chunkName) => {
125
+ const file = files[chunkName];
126
+ return total + (file?.size ?? 0);
127
+ }, 0);
128
+ }
129
+ /**
130
+ * Extract hash from filename
131
+ * e.g., "Counter-abc123.js" → "abc123"
132
+ */
133
+ function extractHash(fileName) {
134
+ const match = fileName.match(/-([a-f0-9]+)\./i);
135
+ return match?.[1] ?? null;
136
+ }
137
+ /**
138
+ * Strip chunk decorations from filename
139
+ * e.g., "chunk-MARX6EW4.js" → "MARX6EW4"
140
+ */
141
+ function stripChunkDecorations(filename) {
142
+ return filename.replace(/^chunk-/, "").replace(/\.js$/, "");
143
+ }
144
+ /**
145
+ * Normalize component path for manifest key
146
+ * Strips the _bundle_src/ prefix that's added during virtual source bundling
147
+ * e.g., "_bundle_src/src/app/icon.tsx" → "src/app/icon.tsx"
148
+ */
149
+ function normalizeManifestKey(relativePath) {
150
+ const prefix = `${virtualSource.VIRTUAL_SRC_DIR}/`;
151
+ if (relativePath.startsWith(prefix)) {
152
+ return relativePath.slice(prefix.length);
153
+ }
154
+ return relativePath;
155
+ }
156
+ /**
157
+ * Save manifest to file
158
+ */
159
+ export async function saveChunkManifest(manifest, outputPath) {
160
+ await runtime.fs.writeTextFile(outputPath, JSON.stringify(manifest, null, 2));
161
+ manifestLogger.debug(`📝 Chunk manifest saved: ${outputPath}`);
162
+ }
163
+ /**
164
+ * Load manifest from file
165
+ */
166
+ export async function loadChunkManifest(filePath) {
167
+ const content = await runtime.fs.readTextFile(filePath);
168
+ return JSON.parse(content);
169
+ }
170
+ /**
171
+ * Log manifest using structured logging
172
+ */
173
+ export function logManifest(manifest) {
174
+ manifestLogger.debug("📦 Chunk Manifest:", {
175
+ entrypoint: manifest.entrypoint,
176
+ components: Object.keys(manifest.chunks).length,
177
+ files: Object.keys(manifest.files).length,
178
+ chunks: Object.fromEntries(Object.entries(manifest.chunks).map(([id, info]) => [
179
+ id,
180
+ {
181
+ main: info.main,
182
+ deps: info.deps,
183
+ exportName: info.exportName,
184
+ sizeKB: (info.size / 1024).toFixed(2),
185
+ },
186
+ ])),
187
+ });
188
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Result of stub generation for a single file.
3
+ */
4
+ export interface ClientActionStubResult {
5
+ /** Original file path */
6
+ filePath: string;
7
+ /** Relative path from project root */
8
+ relativePath: string;
9
+ /** List of exported action names */
10
+ exportedActions: string[];
11
+ }
12
+ /**
13
+ * Transform a single "use server" file into client stubs.
14
+ *
15
+ * @param filePath - Absolute path to the file
16
+ * @param relativePath - Relative path for action ID generation
17
+ * @returns List of exported action names, or null if not a "use server" file
18
+ */
19
+ export declare function generateClientStub(filePath: string, relativePath: string): Promise<string[] | null>;
20
+ /**
21
+ * Transform all "use server" files in a directory into client stubs.
22
+ *
23
+ * This is used during client bundling to replace server action files
24
+ * with client-side stubs that call the server through __callServer.
25
+ *
26
+ * @param virtualSrcDir - Virtual source directory (e.g., dist/_bundle_src/src)
27
+ * @param projectRoot - Project root for relative path calculation
28
+ * @returns Array of stub generation results
29
+ */
30
+ export declare function generateClientActionStubs(virtualSrcDir: string, projectRoot: string): Promise<ClientActionStubResult[]>;