@eserstack/laroux-bundler 0.0.0-bootstrap.0 → 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.
- package/LICENSE +13 -0
- package/README.md +432 -0
- package/dist/adapters/fonts/font-optimizer.d.ts +28 -0
- package/dist/adapters/fonts/font-optimizer.js +74 -0
- package/dist/adapters/fonts/index.d.ts +18 -0
- package/dist/adapters/fonts/index.js +78 -0
- package/dist/adapters/fonts/mod.d.ts +6 -0
- package/dist/adapters/fonts/mod.js +7 -0
- package/dist/adapters/lightningcss/css-processor.d.ts +39 -0
- package/dist/adapters/lightningcss/css-processor.js +103 -0
- package/dist/adapters/lightningcss/mod.d.ts +5 -0
- package/dist/adapters/lightningcss/mod.js +6 -0
- package/dist/adapters/mod.d.ts +13 -0
- package/dist/adapters/mod.js +21 -0
- package/dist/adapters/prebuilt-bundler/mod.d.ts +5 -0
- package/dist/adapters/prebuilt-bundler/mod.js +6 -0
- package/dist/adapters/prebuilt-bundler/prebuilt-bundler.d.ts +22 -0
- package/dist/adapters/prebuilt-bundler/prebuilt-bundler.js +60 -0
- package/dist/adapters/react/mod.d.ts +10 -0
- package/dist/adapters/react/mod.js +16 -0
- package/dist/adapters/react/plugin.d.ts +17 -0
- package/dist/adapters/react/plugin.js +62 -0
- package/dist/adapters/react/rsc-analyze.d.ts +29 -0
- package/dist/adapters/react/rsc-analyze.js +116 -0
- package/dist/adapters/react/rsc-client-entry.d.ts +26 -0
- package/dist/adapters/react/rsc-client-entry.js +145 -0
- package/dist/adapters/react/rsc-module-map.d.ts +41 -0
- package/dist/adapters/react/rsc-module-map.js +81 -0
- package/dist/adapters/react/rsc-rewrite-imports.d.ts +38 -0
- package/dist/adapters/react/rsc-rewrite-imports.js +409 -0
- package/dist/adapters/react/rsc-transform.d.ts +26 -0
- package/dist/adapters/react/rsc-transform.js +101 -0
- package/dist/adapters/runtime-bundler/mod.d.ts +6 -0
- package/dist/adapters/runtime-bundler/mod.js +6 -0
- package/dist/adapters/runtime-bundler/runtime-bundler.d.ts +85 -0
- package/dist/adapters/runtime-bundler/runtime-bundler.js +244 -0
- package/dist/adapters/sharp/image-optimizer.d.ts +52 -0
- package/dist/adapters/sharp/image-optimizer.js +261 -0
- package/dist/adapters/sharp/mod.d.ts +6 -0
- package/dist/adapters/sharp/mod.js +6 -0
- package/dist/adapters/tailwindcss/compile.d.ts +22 -0
- package/dist/adapters/tailwindcss/compile.js +29 -0
- package/dist/adapters/tailwindcss/critical-css-config.d.ts +46 -0
- package/dist/adapters/tailwindcss/critical-css-config.js +78 -0
- package/dist/adapters/tailwindcss/critical-page-css.d.ts +61 -0
- package/dist/adapters/tailwindcss/critical-page-css.js +431 -0
- package/dist/adapters/tailwindcss/critical-universal-css.d.ts +68 -0
- package/dist/adapters/tailwindcss/critical-universal-css.js +250 -0
- package/dist/adapters/tailwindcss/mod.d.ts +10 -0
- package/dist/adapters/tailwindcss/mod.js +11 -0
- package/dist/adapters/tailwindcss/plugin.d.ts +16 -0
- package/dist/adapters/tailwindcss/plugin.js +107 -0
- package/dist/adapters/tailwindcss/stylesheet-loader.d.ts +15 -0
- package/dist/adapters/tailwindcss/stylesheet-loader.js +83 -0
- package/dist/config.d.ts +27 -0
- package/dist/config.js +31 -0
- package/dist/css-modules.d.ts +49 -0
- package/dist/css-modules.js +146 -0
- package/dist/domain/build-cache.d.ts +107 -0
- package/dist/domain/build-cache.js +128 -0
- package/dist/domain/build-validator.d.ts +68 -0
- package/dist/domain/build-validator.js +207 -0
- package/dist/domain/bundler.d.ts +136 -0
- package/dist/domain/bundler.js +225 -0
- package/dist/domain/chunk-manifest.d.ts +40 -0
- package/dist/domain/chunk-manifest.js +188 -0
- package/dist/domain/client-action-stub.d.ts +30 -0
- package/dist/domain/client-action-stub.js +167 -0
- package/dist/domain/copy-path.d.ts +15 -0
- package/dist/domain/copy-path.js +29 -0
- package/dist/domain/css-plugin.d.ts +91 -0
- package/dist/domain/css-plugin.js +6 -0
- package/dist/domain/css-processor.d.ts +57 -0
- package/dist/domain/css-processor.js +33 -0
- package/dist/domain/font-optimizer.d.ts +46 -0
- package/dist/domain/font-optimizer.js +17 -0
- package/dist/domain/framework-plugin.d.ts +106 -0
- package/dist/domain/framework-plugin.js +20 -0
- package/dist/domain/image-optimizer.d.ts +74 -0
- package/dist/domain/image-optimizer.js +16 -0
- package/dist/domain/import-map.d.ts +90 -0
- package/dist/domain/import-map.js +187 -0
- package/dist/domain/mod.d.ts +32 -0
- package/dist/domain/mod.js +20 -0
- package/dist/domain/route-generator.d.ts +34 -0
- package/dist/domain/route-generator.js +305 -0
- package/dist/domain/route-scanner.d.ts +72 -0
- package/dist/domain/route-scanner.js +282 -0
- package/dist/domain/server-action-transform.d.ts +28 -0
- package/dist/domain/server-action-transform.js +147 -0
- package/dist/domain/virtual-source.d.ts +63 -0
- package/dist/domain/virtual-source.js +238 -0
- package/dist/import-map-resolver-plugin.d.ts +47 -0
- package/dist/import-map-resolver-plugin.js +109 -0
- package/dist/mod.d.ts +57 -0
- package/dist/mod.js +56 -0
- package/dist/server-externals-plugin.d.ts +29 -0
- package/dist/server-externals-plugin.js +63 -0
- package/dist/system.d.ts +157 -0
- package/dist/system.js +1401 -0
- package/dist/types.d.ts +60 -0
- package/dist/types.js +38 -0
- package/package.json +86 -1
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Import Rewriting for Server Components
|
|
4
|
+
* Automatically rewrites imports in server components to point to transformed client components
|
|
5
|
+
*/
|
|
6
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
7
|
+
import * as patterns from "@eserstack/standards/patterns";
|
|
8
|
+
import * as collector from "@eserstack/collector";
|
|
9
|
+
import * as logging from "@eserstack/logging";
|
|
10
|
+
const rewriteLogger = logging.logger.getLogger([
|
|
11
|
+
"laroux-bundler",
|
|
12
|
+
"rsc-rewrite-imports",
|
|
13
|
+
]);
|
|
14
|
+
/**
|
|
15
|
+
* Check if a position in the content is inside a string literal
|
|
16
|
+
*/
|
|
17
|
+
function isInsideStringLiteral(content, position) {
|
|
18
|
+
let inSingleQuote = false;
|
|
19
|
+
let inDoubleQuote = false;
|
|
20
|
+
let inTemplateString = false;
|
|
21
|
+
let prevChar = "";
|
|
22
|
+
for (let i = 0; i < position; i++) {
|
|
23
|
+
const char = content[i];
|
|
24
|
+
// Safety check (shouldn't happen since i < position <= content.length)
|
|
25
|
+
if (char === undefined) {
|
|
26
|
+
break;
|
|
27
|
+
}
|
|
28
|
+
// Skip escaped quotes
|
|
29
|
+
if (prevChar === "\\") {
|
|
30
|
+
prevChar = char;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (char === "'" && !inDoubleQuote && !inTemplateString) {
|
|
34
|
+
inSingleQuote = !inSingleQuote;
|
|
35
|
+
}
|
|
36
|
+
else if (char === '"' && !inSingleQuote && !inTemplateString) {
|
|
37
|
+
inDoubleQuote = !inDoubleQuote;
|
|
38
|
+
}
|
|
39
|
+
else if (char === "`" && !inSingleQuote && !inDoubleQuote) {
|
|
40
|
+
inTemplateString = !inTemplateString;
|
|
41
|
+
}
|
|
42
|
+
prevChar = char;
|
|
43
|
+
}
|
|
44
|
+
return inSingleQuote || inDoubleQuote || inTemplateString;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Parse imports from TypeScript/JSX file
|
|
48
|
+
* Matches: import Foo from "./Foo.tsx"
|
|
49
|
+
* import { Bar } from "../Bar.tsx"
|
|
50
|
+
* import type { X } from "./types.ts"
|
|
51
|
+
*/
|
|
52
|
+
function parseImports(content) {
|
|
53
|
+
const imports = [];
|
|
54
|
+
// Match import statements with various patterns
|
|
55
|
+
// Handles: import X from "y", import { X } from "y", import type { X } from "y", import * as X from "y"
|
|
56
|
+
const importRegex = /import\s+(?:type\s+)?(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+))*\s+from\s+)?["']([^"']+)["'];?/g;
|
|
57
|
+
let match;
|
|
58
|
+
while ((match = importRegex.exec(content)) !== null) {
|
|
59
|
+
const importPath = match[1];
|
|
60
|
+
// Skip if no import path captured
|
|
61
|
+
if (!importPath) {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
// Skip if this import is inside a string literal (e.g., code samples)
|
|
65
|
+
if (isInsideStringLiteral(content, match.index)) {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
// Process relative imports AND @/ path alias imports
|
|
69
|
+
if (importPath.startsWith("./") ||
|
|
70
|
+
importPath.startsWith("../") ||
|
|
71
|
+
importPath.startsWith("@/")) {
|
|
72
|
+
imports.push({
|
|
73
|
+
original: match[0],
|
|
74
|
+
path: importPath,
|
|
75
|
+
startIndex: match.index,
|
|
76
|
+
endIndex: match.index + match[0].length,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return imports;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Resolve an import path relative to the importing file
|
|
84
|
+
* Handles both relative imports (./,../) and @/ path alias
|
|
85
|
+
*/
|
|
86
|
+
function resolveImportPath(importerPath, importPath, projectRoot) {
|
|
87
|
+
// Handle @/ path alias (resolves to src/)
|
|
88
|
+
if (importPath.startsWith("@/")) {
|
|
89
|
+
const pathWithoutAlias = importPath.slice(2); // Remove "@/"
|
|
90
|
+
return runtime.path.join(projectRoot, "src", pathWithoutAlias);
|
|
91
|
+
}
|
|
92
|
+
// Handle relative imports
|
|
93
|
+
const importerDir = runtime.path.dirname(importerPath);
|
|
94
|
+
const resolved = runtime.path.resolve(importerDir, importPath);
|
|
95
|
+
return resolved;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Check if a resolved path matches a client component
|
|
99
|
+
*/
|
|
100
|
+
function findClientComponentMatch(resolvedPath, clientComponentMap) {
|
|
101
|
+
// Try exact match first
|
|
102
|
+
if (clientComponentMap.has(resolvedPath)) {
|
|
103
|
+
return clientComponentMap.get(resolvedPath);
|
|
104
|
+
}
|
|
105
|
+
// Try with JS/TS extensions
|
|
106
|
+
const extensions = patterns.JS_FILE_EXTENSIONS.map((ext) => `.${ext}`);
|
|
107
|
+
for (const ext of extensions) {
|
|
108
|
+
const withExt = resolvedPath.endsWith(ext)
|
|
109
|
+
? resolvedPath
|
|
110
|
+
: resolvedPath + ext;
|
|
111
|
+
if (clientComponentMap.has(withExt)) {
|
|
112
|
+
return clientComponentMap.get(withExt);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Check if a resolved path matches a CSS module
|
|
119
|
+
*/
|
|
120
|
+
function findCSSModuleMatch(resolvedPath, cssModuleMap) {
|
|
121
|
+
// CSS modules must have exact .module.css extension
|
|
122
|
+
if (cssModuleMap.has(resolvedPath)) {
|
|
123
|
+
return cssModuleMap.get(resolvedPath);
|
|
124
|
+
}
|
|
125
|
+
// Try adding .module.css if not present
|
|
126
|
+
if (!resolvedPath.endsWith(".module.css")) {
|
|
127
|
+
const withExt = resolvedPath + ".module.css";
|
|
128
|
+
if (cssModuleMap.has(withExt)) {
|
|
129
|
+
return cssModuleMap.get(withExt);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Rewrite imports in a server component file
|
|
136
|
+
*/
|
|
137
|
+
export async function rewriteServerComponentImports(serverComponentPath, clientComponentMap, cssModuleMap, outputDir, projectRoot) {
|
|
138
|
+
const content = await runtime.fs.readTextFile(serverComponentPath);
|
|
139
|
+
const imports = parseImports(content);
|
|
140
|
+
let rewrittenContent = content;
|
|
141
|
+
let importsRewritten = 0;
|
|
142
|
+
let offset = 0; // Track content length changes
|
|
143
|
+
for (const importInfo of imports) {
|
|
144
|
+
// Resolve the import path
|
|
145
|
+
const resolvedPath = resolveImportPath(serverComponentPath, importInfo.path, projectRoot);
|
|
146
|
+
// Check if this import references a CSS module
|
|
147
|
+
const cssModulePath = findCSSModuleMatch(resolvedPath, cssModuleMap);
|
|
148
|
+
if (cssModulePath) {
|
|
149
|
+
// Rewrite CSS module import to JSON import with type assertion
|
|
150
|
+
// e.g., import "./file.module.css" -> import styles from "./file.module.css.json" with { type: "json" }
|
|
151
|
+
const newImportPath = importInfo.path.endsWith(".module.css")
|
|
152
|
+
? `${importInfo.path}.json`
|
|
153
|
+
: `${importInfo.path}.module.css.json`;
|
|
154
|
+
// Detect if this is a side-effect import (no bindings)
|
|
155
|
+
const isSideEffectImport = importInfo.original.match(/^import\s+["']/);
|
|
156
|
+
let newImport;
|
|
157
|
+
if (isSideEffectImport) {
|
|
158
|
+
// Side-effect import: import "./file.module.css"
|
|
159
|
+
// Convert to: import styles from "./file.module.css.json" with { type: "json" }
|
|
160
|
+
// We need a binding to use the assertion syntax
|
|
161
|
+
newImport = importInfo.original.replace(/^import\s+["']([^"']+)["'];?/, `import styles from "${newImportPath}" with { type: "json" };`);
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
// Named or default import: import styles from "./file.module.css"
|
|
165
|
+
// Add assertion: import styles from "./file.module.css.json" with { type: "json" }
|
|
166
|
+
newImport = importInfo.original
|
|
167
|
+
.replace(`"${importInfo.path}"`, `"${newImportPath}" with { type: "json" }`)
|
|
168
|
+
.replace(`'${importInfo.path}'`, `'${newImportPath}' with { type: "json" }`);
|
|
169
|
+
}
|
|
170
|
+
const startIndex = importInfo.startIndex + offset;
|
|
171
|
+
const endIndex = importInfo.endIndex + offset;
|
|
172
|
+
rewrittenContent =
|
|
173
|
+
rewrittenContent.slice(0, startIndex) +
|
|
174
|
+
newImport +
|
|
175
|
+
rewrittenContent.slice(endIndex);
|
|
176
|
+
offset += newImport.length - importInfo.original.length;
|
|
177
|
+
importsRewritten++;
|
|
178
|
+
continue; // Skip client component check for this import
|
|
179
|
+
}
|
|
180
|
+
// Check if this import references a client component
|
|
181
|
+
const transformedPath = findClientComponentMatch(resolvedPath, clientComponentMap);
|
|
182
|
+
if (transformedPath) {
|
|
183
|
+
// Calculate output path for this server component
|
|
184
|
+
const relativeToRoot = runtime.path.relative(projectRoot, serverComponentPath);
|
|
185
|
+
const outputPath = runtime.path.join(outputDir, relativeToRoot);
|
|
186
|
+
// Calculate relative path from the OUTPUT location to transformed component
|
|
187
|
+
const relativePath = runtime.path.relative(runtime.path.dirname(outputPath), transformedPath);
|
|
188
|
+
// Ensure it starts with ./ or ../
|
|
189
|
+
const normalizedPath = relativePath.startsWith(".")
|
|
190
|
+
? relativePath
|
|
191
|
+
: `./${relativePath}`;
|
|
192
|
+
// Replace the import path in the content
|
|
193
|
+
const newImport = importInfo.original
|
|
194
|
+
.replace(`"${importInfo.path}"`, `"${normalizedPath}"`)
|
|
195
|
+
.replace(`'${importInfo.path}'`, `'${normalizedPath}'`);
|
|
196
|
+
const startIndex = importInfo.startIndex + offset;
|
|
197
|
+
const endIndex = importInfo.endIndex + offset;
|
|
198
|
+
rewrittenContent =
|
|
199
|
+
rewrittenContent.slice(0, startIndex) +
|
|
200
|
+
newImport +
|
|
201
|
+
rewrittenContent.slice(endIndex);
|
|
202
|
+
offset += newImport.length - importInfo.original.length;
|
|
203
|
+
importsRewritten++;
|
|
204
|
+
}
|
|
205
|
+
else if (importInfo.path.startsWith("@/")) {
|
|
206
|
+
// Rewrite @/ path alias to relative path (for non-client-component imports)
|
|
207
|
+
// e.g., @/lib/backend/backend.ts -> ../../../lib/backend/backend.ts
|
|
208
|
+
const relativeToRoot = runtime.path.relative(projectRoot, serverComponentPath);
|
|
209
|
+
const outputPath = runtime.path.join(outputDir, relativeToRoot);
|
|
210
|
+
// Convert @/ to src/ and resolve the target path
|
|
211
|
+
const targetPath = runtime.path.join(projectRoot, "dist", "server", "src", importInfo.path.slice(2));
|
|
212
|
+
// Calculate relative path from current file to target
|
|
213
|
+
const relativePath = runtime.path.relative(runtime.path.dirname(outputPath), targetPath);
|
|
214
|
+
// Ensure it starts with ./ or ../
|
|
215
|
+
const normalizedPath = relativePath.startsWith(".")
|
|
216
|
+
? relativePath
|
|
217
|
+
: `./${relativePath}`;
|
|
218
|
+
// Replace the import path
|
|
219
|
+
const newImport = importInfo.original
|
|
220
|
+
.replace(`"${importInfo.path}"`, `"${normalizedPath}"`)
|
|
221
|
+
.replace(`'${importInfo.path}'`, `'${normalizedPath}'`);
|
|
222
|
+
const startIndex = importInfo.startIndex + offset;
|
|
223
|
+
const endIndex = importInfo.endIndex + offset;
|
|
224
|
+
rewrittenContent =
|
|
225
|
+
rewrittenContent.slice(0, startIndex) +
|
|
226
|
+
newImport +
|
|
227
|
+
rewrittenContent.slice(endIndex);
|
|
228
|
+
offset += newImport.length - importInfo.original.length;
|
|
229
|
+
importsRewritten++;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
// Write the rewritten file to dist/server
|
|
233
|
+
const relativeToRoot = runtime.path.relative(projectRoot, serverComponentPath);
|
|
234
|
+
const outputPath = runtime.path.join(outputDir, relativeToRoot);
|
|
235
|
+
await runtime.fs.ensureDir(runtime.path.dirname(outputPath));
|
|
236
|
+
await runtime.fs.writeTextFile(outputPath, rewrittenContent);
|
|
237
|
+
return {
|
|
238
|
+
originalPath: serverComponentPath,
|
|
239
|
+
rewrittenPath: outputPath,
|
|
240
|
+
importsRewritten,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Create a map of client component paths to their transformed paths
|
|
245
|
+
*/
|
|
246
|
+
export function createClientComponentMap(transformResults) {
|
|
247
|
+
const map = new Map();
|
|
248
|
+
for (const result of transformResults) {
|
|
249
|
+
// Map absolute path
|
|
250
|
+
map.set(result.originalPath, result.transformedPath);
|
|
251
|
+
// Also map without extension for convenience
|
|
252
|
+
const withoutExt = result.originalPath.replace(/\.(tsx|ts|jsx|js)$/, "");
|
|
253
|
+
map.set(withoutExt, result.transformedPath);
|
|
254
|
+
}
|
|
255
|
+
return map;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Create a map of CSS module paths to their JSON output paths
|
|
259
|
+
*/
|
|
260
|
+
export function createCSSModuleMap(cssModulePaths) {
|
|
261
|
+
const map = new Map();
|
|
262
|
+
for (const cssPath of cssModulePaths) {
|
|
263
|
+
// Map absolute path to JSON output path
|
|
264
|
+
const jsonPath = cssPath.replace(/\.module\.css$/, ".module.css.json");
|
|
265
|
+
map.set(cssPath, jsonPath);
|
|
266
|
+
// Also map without extension for convenience
|
|
267
|
+
const withoutExt = cssPath.replace(/\.module\.css$/, "");
|
|
268
|
+
map.set(withoutExt, jsonPath);
|
|
269
|
+
}
|
|
270
|
+
return map;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Process all server components
|
|
274
|
+
*/
|
|
275
|
+
export async function rewriteAllServerComponents(serverComponentPaths, transformResults, cssModulePaths, outputDir, projectRoot) {
|
|
276
|
+
rewriteLogger.debug(`🔄 Rewriting imports in ${serverComponentPaths.length} server component(s)...`);
|
|
277
|
+
const clientComponentMap = createClientComponentMap(transformResults);
|
|
278
|
+
const cssModuleMap = createCSSModuleMap(cssModulePaths);
|
|
279
|
+
rewriteLogger.debug(` Found ${cssModulePaths.length} CSS module(s) to track`);
|
|
280
|
+
const results = [];
|
|
281
|
+
for (const componentPath of serverComponentPaths) {
|
|
282
|
+
// One file at a time keeps open file handles bounded; a project can have
|
|
283
|
+
// more server components than the open-file limit.
|
|
284
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
285
|
+
const result = await rewriteServerComponentImports(componentPath, clientComponentMap, cssModuleMap, outputDir, projectRoot);
|
|
286
|
+
if (result.importsRewritten > 0) {
|
|
287
|
+
rewriteLogger.debug(` ✓ ${runtime.path.relative(projectRoot, componentPath)} (${result.importsRewritten} import(s) rewritten)`);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
rewriteLogger.debug(` ✓ ${runtime.path.relative(projectRoot, componentPath)} (no client imports)`);
|
|
291
|
+
}
|
|
292
|
+
results.push(result);
|
|
293
|
+
}
|
|
294
|
+
rewriteLogger.debug(`✅ Import rewriting complete`);
|
|
295
|
+
return results;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Rewrite CSS module imports in a single client component
|
|
299
|
+
*/
|
|
300
|
+
async function rewriteClientComponentCSSImports(clientComponentPath, cssModuleMap, projectRoot) {
|
|
301
|
+
const content = await runtime.fs.readTextFile(clientComponentPath);
|
|
302
|
+
const imports = parseImports(content);
|
|
303
|
+
let rewrittenContent = content;
|
|
304
|
+
let importsRewritten = 0;
|
|
305
|
+
let offset = 0;
|
|
306
|
+
for (const importInfo of imports) {
|
|
307
|
+
// Resolve the import path
|
|
308
|
+
const resolvedPath = resolveImportPath(clientComponentPath, importInfo.path, projectRoot);
|
|
309
|
+
// Check if this import references a CSS module
|
|
310
|
+
const cssModulePath = findCSSModuleMatch(resolvedPath, cssModuleMap);
|
|
311
|
+
if (cssModulePath) {
|
|
312
|
+
// Rewrite CSS module import to JSON import with type assertion
|
|
313
|
+
const newImportPath = importInfo.path.endsWith(".module.css")
|
|
314
|
+
? `${importInfo.path}.json`
|
|
315
|
+
: `${importInfo.path}.module.css.json`;
|
|
316
|
+
// Detect if this is a side-effect import (no bindings)
|
|
317
|
+
const isSideEffectImport = importInfo.original.match(/^import\s+["']/);
|
|
318
|
+
let newImport;
|
|
319
|
+
if (isSideEffectImport) {
|
|
320
|
+
// Side-effect import: import "./file.module.css"
|
|
321
|
+
// Convert to: import styles from "./file.module.css.json" with { type: "json" }
|
|
322
|
+
newImport = importInfo.original.replace(/^import\s+["']([^"']+)["'];?/, `import styles from "${newImportPath}" with { type: "json" };`);
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
// Named or default import: import styles from "./file.module.css"
|
|
326
|
+
// Add assertion: import styles from "./file.module.css.json" with { type: "json" }
|
|
327
|
+
newImport = importInfo.original
|
|
328
|
+
.replace(`"${importInfo.path}"`, `"${newImportPath}" with { type: "json" }`)
|
|
329
|
+
.replace(`'${importInfo.path}'`, `'${newImportPath}' with { type: "json" }`);
|
|
330
|
+
}
|
|
331
|
+
const startIndex = importInfo.startIndex + offset;
|
|
332
|
+
const endIndex = importInfo.endIndex + offset;
|
|
333
|
+
rewrittenContent =
|
|
334
|
+
rewrittenContent.slice(0, startIndex) +
|
|
335
|
+
newImport +
|
|
336
|
+
rewrittenContent.slice(endIndex);
|
|
337
|
+
offset += newImport.length - importInfo.original.length;
|
|
338
|
+
importsRewritten++;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
// Write back the rewritten content if changes were made
|
|
342
|
+
if (importsRewritten > 0) {
|
|
343
|
+
await runtime.fs.writeTextFile(clientComponentPath, rewrittenContent);
|
|
344
|
+
}
|
|
345
|
+
return { importsRewritten };
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Process all client components to rewrite CSS module imports
|
|
349
|
+
*/
|
|
350
|
+
export async function rewriteAllClientComponentCSSImports(clientComponents, cssModulePaths, _outputDir, projectRoot) {
|
|
351
|
+
rewriteLogger.debug(`🔄 Rewriting CSS module imports in ${clientComponents.length} client component(s)...`);
|
|
352
|
+
const cssModuleMap = createCSSModuleMap(cssModulePaths);
|
|
353
|
+
rewriteLogger.debug(` Found ${cssModulePaths.length} CSS module(s) to track`);
|
|
354
|
+
let totalRewritten = 0;
|
|
355
|
+
for (const component of clientComponents) {
|
|
356
|
+
// One file at a time keeps open file handles bounded; a project can have
|
|
357
|
+
// more client components than the open-file limit.
|
|
358
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
359
|
+
const result = await rewriteClientComponentCSSImports(component.filePath, cssModuleMap, projectRoot);
|
|
360
|
+
if (result.importsRewritten > 0) {
|
|
361
|
+
rewriteLogger.debug(` ✓ ${runtime.path.relative(projectRoot, component.filePath)} (${result.importsRewritten} CSS import(s) rewritten)`);
|
|
362
|
+
totalRewritten += result.importsRewritten;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if (totalRewritten > 0) {
|
|
366
|
+
rewriteLogger.debug(`✅ Rewrote ${totalRewritten} CSS module import(s) in ${clientComponents.length} client component(s)`);
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
rewriteLogger.debug(`✅ No CSS module imports found in client components`);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/** Extensions of the source files whose CSS module imports are rewritten. */
|
|
373
|
+
const CSS_IMPORTER_EXTENSIONS = ["tsx", "ts"];
|
|
374
|
+
/**
|
|
375
|
+
* Rewrite CSS module imports in ALL source files that might be bundled
|
|
376
|
+
* This is necessary because client components may import server components
|
|
377
|
+
* that have CSS module imports, which the bundler cannot load as CSS
|
|
378
|
+
*/
|
|
379
|
+
export async function rewriteAllSrcCSSModuleImports(srcDir, cssModulePaths, projectRoot) {
|
|
380
|
+
rewriteLogger.debug(`🔄 Rewriting CSS module imports in all src files...`);
|
|
381
|
+
const cssModuleMap = createCSSModuleMap(cssModulePaths);
|
|
382
|
+
// Find all .tsx and .ts files in src directory. The extension check is done
|
|
383
|
+
// here: the glob filter of walkFiles supports only * and **, so a
|
|
384
|
+
// "*.{tsx,ts}" list would match no file.
|
|
385
|
+
const srcFiles = [];
|
|
386
|
+
for await (const relPath of collector.walkFiles(srcDir, undefined, /node_modules/)) {
|
|
387
|
+
if (patterns.hasExtension(relPath, CSS_IMPORTER_EXTENSIONS)) {
|
|
388
|
+
srcFiles.push(runtime.path.join(srcDir, relPath));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
rewriteLogger.debug(` Found ${srcFiles.length} source file(s) to check`);
|
|
392
|
+
let totalRewritten = 0;
|
|
393
|
+
for (const filePath of srcFiles) {
|
|
394
|
+
// One file at a time keeps open file handles bounded; a project can have
|
|
395
|
+
// more source files than the open-file limit.
|
|
396
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
397
|
+
const result = await rewriteClientComponentCSSImports(filePath, cssModuleMap, projectRoot);
|
|
398
|
+
if (result.importsRewritten > 0) {
|
|
399
|
+
rewriteLogger.debug(` ✓ ${runtime.path.relative(projectRoot, filePath)} (${result.importsRewritten} CSS import(s) rewritten)`);
|
|
400
|
+
totalRewritten += result.importsRewritten;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (totalRewritten > 0) {
|
|
404
|
+
rewriteLogger.debug(`✅ Rewrote ${totalRewritten} CSS module import(s) in ${srcFiles.length} source file(s)`);
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
rewriteLogger.debug(`✅ No CSS module imports needed rewriting`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client Component Transformation
|
|
3
|
+
* Transforms "use client" components into createClientReference() wrappers at build time
|
|
4
|
+
*/
|
|
5
|
+
import type { ClientComponent } from "./rsc-analyze.ts";
|
|
6
|
+
export type TransformResult = {
|
|
7
|
+
originalPath: string;
|
|
8
|
+
transformedPath: string;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Transform a single client component file
|
|
12
|
+
*/
|
|
13
|
+
export declare function transformClientComponent(component: ClientComponent, outputDir: string): Promise<TransformResult>;
|
|
14
|
+
/**
|
|
15
|
+
* Transform all client components
|
|
16
|
+
*/
|
|
17
|
+
export declare function transformAllClientComponents(components: ClientComponent[], outputDir: string, projectRoot: string): Promise<TransformResult[]>;
|
|
18
|
+
/**
|
|
19
|
+
* Create import mapping for server code
|
|
20
|
+
* Maps original ES Module paths to transformed versions
|
|
21
|
+
*/
|
|
22
|
+
export declare function createImportMapping(transformResults: TransformResult[]): Map<string, string>;
|
|
23
|
+
/**
|
|
24
|
+
* Generate a manifest of transformed components for debugging
|
|
25
|
+
*/
|
|
26
|
+
export declare function generateTransformManifest(transformResults: TransformResult[], outputPath: string, projectRoot: string): Promise<void>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Client Component Transformation
|
|
4
|
+
* Transforms "use client" components into createClientReference() wrappers at build time
|
|
5
|
+
*/
|
|
6
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
7
|
+
import * as logging from "@eserstack/logging";
|
|
8
|
+
const transformLogger = logging.logger.getLogger([
|
|
9
|
+
"laroux-bundler",
|
|
10
|
+
"rsc-transform",
|
|
11
|
+
]);
|
|
12
|
+
/**
|
|
13
|
+
* Transform a single client component file
|
|
14
|
+
*/
|
|
15
|
+
export async function transformClientComponent(component, outputDir) {
|
|
16
|
+
// Create output directory structure
|
|
17
|
+
const relativeDirPath = runtime.path.dirname(component.relativePath);
|
|
18
|
+
const outputSubDir = runtime.path.join(outputDir, relativeDirPath);
|
|
19
|
+
await runtime.fs.ensureDir(outputSubDir);
|
|
20
|
+
// Generate transformed content
|
|
21
|
+
const transformed = generateTransformedContent(component);
|
|
22
|
+
// Write transformed file
|
|
23
|
+
const outputFileName = component.relativePath.split("/").pop();
|
|
24
|
+
const transformedPath = runtime.path.join(outputSubDir, outputFileName);
|
|
25
|
+
await runtime.fs.writeTextFile(transformedPath, transformed);
|
|
26
|
+
return {
|
|
27
|
+
originalPath: component.filePath,
|
|
28
|
+
transformedPath,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Generate the transformed content that wraps the component in createClientReference
|
|
33
|
+
*/
|
|
34
|
+
function generateTransformedContent(component) {
|
|
35
|
+
// Generate export statements for all exports
|
|
36
|
+
const exportStatements = component.exportNames.map((exportName) => {
|
|
37
|
+
const isDefaultExport = exportName === "default";
|
|
38
|
+
return isDefaultExport
|
|
39
|
+
? `export default createClientReference(\n "./${component.relativePath}",\n "default"\n);`
|
|
40
|
+
: `export const ${exportName} = createClientReference(\n "./${component.relativePath}",\n "${exportName}"\n);`;
|
|
41
|
+
});
|
|
42
|
+
return `/**
|
|
43
|
+
* Auto-generated client component reference
|
|
44
|
+
* Original: ${component.relativePath}
|
|
45
|
+
* Exports: ${component.exportNames.join(", ")}
|
|
46
|
+
* This file is generated at build time - do not edit!
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
import { createClientReference } from "@eserstack/laroux-react/protocol";
|
|
50
|
+
|
|
51
|
+
// Export client components as references
|
|
52
|
+
// The actual component code runs in the browser
|
|
53
|
+
${exportStatements.join("\n\n")}
|
|
54
|
+
`;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Transform all client components
|
|
58
|
+
*/
|
|
59
|
+
export async function transformAllClientComponents(components, outputDir, projectRoot) {
|
|
60
|
+
transformLogger.debug(`🔄 Transforming ${components.length} client component(s)...`);
|
|
61
|
+
const results = [];
|
|
62
|
+
for (const component of components) {
|
|
63
|
+
// One file at a time keeps open file handles bounded; a project can have
|
|
64
|
+
// more client components than the open-file limit.
|
|
65
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
66
|
+
const result = await transformClientComponent(component, outputDir);
|
|
67
|
+
transformLogger.debug(` ✓ ${component.relativePath} → ${runtime.path.relative(projectRoot, result.transformedPath)}`);
|
|
68
|
+
results.push(result);
|
|
69
|
+
}
|
|
70
|
+
transformLogger.debug(`✅ Transformation complete`);
|
|
71
|
+
return results;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Create import mapping for server code
|
|
75
|
+
* Maps original ES Module paths to transformed versions
|
|
76
|
+
*/
|
|
77
|
+
export function createImportMapping(transformResults) {
|
|
78
|
+
const mapping = new Map();
|
|
79
|
+
for (const result of transformResults) {
|
|
80
|
+
// Map full paths with ./ prefix
|
|
81
|
+
mapping.set(`./${result.originalPath}`, result.transformedPath);
|
|
82
|
+
// Also handle different path variations (filename only)
|
|
83
|
+
const fileName = result.originalPath.split("/").pop();
|
|
84
|
+
mapping.set(`./${fileName}`, result.transformedPath);
|
|
85
|
+
}
|
|
86
|
+
return mapping;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Generate a manifest of transformed components for debugging
|
|
90
|
+
*/
|
|
91
|
+
export async function generateTransformManifest(transformResults, outputPath, projectRoot) {
|
|
92
|
+
const manifest = {
|
|
93
|
+
generated: new Date().toISOString(),
|
|
94
|
+
components: transformResults.map((r) => ({
|
|
95
|
+
original: r.originalPath,
|
|
96
|
+
transformed: runtime.path.relative(projectRoot, r.transformedPath),
|
|
97
|
+
})),
|
|
98
|
+
};
|
|
99
|
+
await runtime.fs.writeTextFile(outputPath, JSON.stringify(manifest, null, 2));
|
|
100
|
+
transformLogger.debug(`📝 Transform manifest saved to: ${runtime.path.relative(projectRoot, outputPath)}`);
|
|
101
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime Bundler Adapter
|
|
3
|
+
* In-memory bundling for development mode
|
|
4
|
+
*/
|
|
5
|
+
export { createRuntimeCache, type RuntimeBundle, RuntimeBundler, type RuntimeBundlerConfig, } from "./runtime-bundler.ts";
|
|
6
|
+
export type { ResolvedBrowserShimsConfig } from "@eserstack/laroux/config";
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime Bundler for Dev Mode
|
|
3
|
+
* Performs in-memory transformations without requiring dist/ directory
|
|
4
|
+
*
|
|
5
|
+
* NOTE: This bundler requires a React plugin to function.
|
|
6
|
+
* The RSC functionality is provided by @eserstack/laroux-bundler/adapters/react.
|
|
7
|
+
*/
|
|
8
|
+
import type { ClientComponent, FrameworkPlugin, ModuleMap } from "../../domain/framework-plugin.ts";
|
|
9
|
+
import type { ChunkManifest } from "../../domain/chunk-manifest.ts";
|
|
10
|
+
import type { ResolvedBrowserShimsConfig } from "@eserstack/laroux/config";
|
|
11
|
+
import * as bundler from "../../domain/bundler.ts";
|
|
12
|
+
/**
|
|
13
|
+
* Configuration required by runtime bundler
|
|
14
|
+
* Injected as dependency to avoid importing from parent
|
|
15
|
+
*/
|
|
16
|
+
export type RuntimeBundlerConfig = {
|
|
17
|
+
/** Source directory path */
|
|
18
|
+
srcDir: string;
|
|
19
|
+
/** Project root: bare imports resolve from its import map and node_modules */
|
|
20
|
+
projectRoot: string;
|
|
21
|
+
/** Enable debug logging */
|
|
22
|
+
debug?: boolean;
|
|
23
|
+
/** Framework plugin for RSC functionality */
|
|
24
|
+
plugin: FrameworkPlugin;
|
|
25
|
+
/**
|
|
26
|
+
* Browser replacements for server-only modules, the same setting a
|
|
27
|
+
* production build takes (`BuildConfig.browserShims`). Defaults to
|
|
28
|
+
* `DEFAULT_BROWSER_SHIMS` from `@eserstack/laroux/config`, which replaces
|
|
29
|
+
* `@eserstack/logging` with laroux's browser logger.
|
|
30
|
+
*/
|
|
31
|
+
browserShims?: ResolvedBrowserShimsConfig;
|
|
32
|
+
};
|
|
33
|
+
export type RuntimeBundle = {
|
|
34
|
+
clientCode: string;
|
|
35
|
+
moduleMap: ModuleMap;
|
|
36
|
+
clientComponents: Map<string, ClientComponent>;
|
|
37
|
+
chunkManifest: ChunkManifest;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* In-memory cache for dev mode
|
|
41
|
+
*/
|
|
42
|
+
declare class RuntimeCache {
|
|
43
|
+
private clientComponents;
|
|
44
|
+
private moduleMap;
|
|
45
|
+
private bundleCode;
|
|
46
|
+
private chunkManifest;
|
|
47
|
+
private lastScan;
|
|
48
|
+
private readonly scanInterval;
|
|
49
|
+
private config;
|
|
50
|
+
getOrCreateBundle(): Promise<RuntimeBundle>;
|
|
51
|
+
constructor(config: RuntimeBundlerConfig);
|
|
52
|
+
rebuild(): Promise<void>;
|
|
53
|
+
private bundleClientCode;
|
|
54
|
+
clear(): void;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Create a runtime cache instance with injected config
|
|
58
|
+
* Factory function to enable dependency injection
|
|
59
|
+
*/
|
|
60
|
+
export declare function createRuntimeCache(config: RuntimeBundlerConfig): RuntimeCache;
|
|
61
|
+
/**
|
|
62
|
+
* Runtime bundler facade with dependency injection
|
|
63
|
+
*/
|
|
64
|
+
export declare class RuntimeBundler implements bundler.Bundler {
|
|
65
|
+
private cache;
|
|
66
|
+
constructor(config: RuntimeBundlerConfig);
|
|
67
|
+
/**
|
|
68
|
+
* Get runtime bundle (cached, in-memory)
|
|
69
|
+
* Implements Bundler interface
|
|
70
|
+
*/
|
|
71
|
+
getBundle(): Promise<bundler.BundleData>;
|
|
72
|
+
/**
|
|
73
|
+
* Get the full runtime bundle data (legacy method for internal use)
|
|
74
|
+
*/
|
|
75
|
+
getRuntimeBundle(): Promise<RuntimeBundle>;
|
|
76
|
+
/**
|
|
77
|
+
* Force rebuild of runtime bundle
|
|
78
|
+
*/
|
|
79
|
+
rebuild(): Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* Clear runtime cache
|
|
82
|
+
*/
|
|
83
|
+
clear(): void;
|
|
84
|
+
}
|
|
85
|
+
export {};
|