@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,250 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Critical Universal CSS Extraction
4
+ *
5
+ * Dynamically extracts essential base CSS from the compiled Tailwind CSS.
6
+ * This ensures critical CSS uses actual values from the app's global.css
7
+ * and theme configuration, not hardcoded values.
8
+ *
9
+ * Architecture:
10
+ * 1. Parse compiled CSS to find @layer base and @layer theme blocks
11
+ * 2. Extract specific selectors needed for initial render (html, body, #root)
12
+ * 3. Extract CSS variables from theme for fallbacks
13
+ * 4. Output as minimal CSS for fast initial paint
14
+ *
15
+ * IMPORTANT: Does NOT extract element resets (a, button, h1-h6) because
16
+ * unlayered CSS overrides Tailwind's @layer utilities, breaking classes
17
+ * like .text-white, .bg-primary-600, etc.
18
+ */
19
+ import * as logging from "@eserstack/logging";
20
+ const criticalUniversalCssLogger = logging.logger.getLogger([
21
+ "laroux-bundler",
22
+ "critical-universal-css",
23
+ ]);
24
+ /**
25
+ * Selectors to extract from @layer base for critical CSS.
26
+ * These are essential for initial render and don't conflict with utilities.
27
+ */
28
+ const CRITICAL_SELECTORS = [
29
+ "html",
30
+ ":host",
31
+ "html, :host",
32
+ "body",
33
+ "#root",
34
+ ".initial-loading",
35
+ "[data-client-component]",
36
+ ];
37
+ /**
38
+ * Selectors to EXCLUDE - these conflict with Tailwind utilities when unlayered
39
+ */
40
+ const EXCLUDED_SELECTORS = [
41
+ "*",
42
+ "*, ::after, ::before",
43
+ "*, ::after, ::before, ::backdrop, ::file-selector-button",
44
+ "a",
45
+ "button",
46
+ "h1",
47
+ "h2",
48
+ "h3",
49
+ "h4",
50
+ "h5",
51
+ "h6",
52
+ "h1, h2, h3, h4, h5, h6",
53
+ ];
54
+ /**
55
+ * Extract a @layer block from CSS
56
+ */
57
+ function extractLayerBlock(css, layerName) {
58
+ const pattern = new RegExp(`@layer\\s+${layerName}\\s*\\{`, "g");
59
+ const match = pattern.exec(css);
60
+ if (!match) {
61
+ return null;
62
+ }
63
+ const startIndex = match.index + match[0].length;
64
+ let braceCount = 1;
65
+ let pos = startIndex;
66
+ while (pos < css.length && braceCount > 0) {
67
+ if (css[pos] === "{")
68
+ braceCount++;
69
+ else if (css[pos] === "}")
70
+ braceCount--;
71
+ pos++;
72
+ }
73
+ return css.slice(startIndex, pos - 1).trim();
74
+ }
75
+ /**
76
+ * Parse CSS rules from a block of CSS text.
77
+ * Returns array of { selector, declarations } objects.
78
+ */
79
+ function parseCssRules(cssBlock) {
80
+ const rules = [];
81
+ // Match selector { declarations }
82
+ // This is a simplified parser that handles most cases
83
+ const rulePattern = /([^{}]+)\{([^{}]*)\}/g;
84
+ let match;
85
+ while ((match = rulePattern.exec(cssBlock)) !== null) {
86
+ const selectorRaw = match[1];
87
+ const declarationsRaw = match[2];
88
+ if (selectorRaw === undefined || declarationsRaw === undefined)
89
+ continue;
90
+ const selector = selectorRaw.trim();
91
+ const declarations = declarationsRaw.trim();
92
+ if (selector && declarations) {
93
+ rules.push({ selector, declarations });
94
+ }
95
+ }
96
+ return rules;
97
+ }
98
+ /**
99
+ * Check if a selector should be included in critical CSS
100
+ */
101
+ function shouldIncludeSelector(selector) {
102
+ // Check if selector is in the excluded list
103
+ const normalizedSelector = selector.trim().toLowerCase();
104
+ for (const excluded of EXCLUDED_SELECTORS) {
105
+ if (normalizedSelector === excluded.toLowerCase()) {
106
+ return false;
107
+ }
108
+ // Also check if selector starts with excluded element selectors
109
+ if (normalizedSelector.startsWith("a ") ||
110
+ normalizedSelector.startsWith("a,") ||
111
+ normalizedSelector.startsWith("button ") ||
112
+ normalizedSelector.startsWith("button,")) {
113
+ return false;
114
+ }
115
+ }
116
+ // Check if selector is in the critical list
117
+ for (const critical of CRITICAL_SELECTORS) {
118
+ if (normalizedSelector === critical.toLowerCase()) {
119
+ return true;
120
+ }
121
+ // Handle comma-separated selectors like "html, :host"
122
+ const selectorParts = normalizedSelector.split(",").map((s) => s.trim());
123
+ const criticalParts = critical
124
+ .toLowerCase()
125
+ .split(",")
126
+ .map((s) => s.trim());
127
+ if (selectorParts.some((sp) => criticalParts.includes(sp)) ||
128
+ criticalParts.some((cp) => selectorParts.includes(cp))) {
129
+ return true;
130
+ }
131
+ }
132
+ return false;
133
+ }
134
+ /**
135
+ * Extract CSS variables from theme layer
136
+ */
137
+ function extractThemeVariables(themeBlock) {
138
+ const variables = {};
139
+ // Match CSS variable declarations
140
+ const varPattern = /(--[\w-]+):\s*([^;]+);/g;
141
+ let match;
142
+ while ((match = varPattern.exec(themeBlock)) !== null) {
143
+ const [, name, value] = match;
144
+ if (name && value) {
145
+ variables[name] = value.trim();
146
+ }
147
+ }
148
+ return variables;
149
+ }
150
+ /**
151
+ * Extract critical universal CSS from compiled Tailwind CSS output.
152
+ *
153
+ * This function:
154
+ * 1. Extracts @layer theme to get CSS variables
155
+ * 2. Extracts @layer base rules for critical selectors (html, body, #root, etc.)
156
+ * 3. Combines them into minimal critical CSS
157
+ *
158
+ * @param compiledCss - The full compiled CSS (styles.css)
159
+ * @returns Critical universal CSS result with extracted values
160
+ */
161
+ export function extractCriticalUniversalCss(compiledCss) {
162
+ criticalUniversalCssLogger.debug("Extracting critical universal CSS from compiled output...");
163
+ const cssLines = [];
164
+ let rulesExtracted = 0;
165
+ // Extract theme layer for CSS variables
166
+ const themeBlock = extractLayerBlock(compiledCss, "theme");
167
+ const themeVariables = themeBlock ? extractThemeVariables(themeBlock) : {};
168
+ // Add minimal universal reset that doesn't conflict with utilities
169
+ // Only box-sizing is safe - padding/margin/border conflict with utility classes
170
+ cssLines.push("*,*::before,*::after{box-sizing:border-box}");
171
+ rulesExtracted++;
172
+ // Extract base layer
173
+ const baseBlock = extractLayerBlock(compiledCss, "base");
174
+ if (baseBlock) {
175
+ // There may be multiple @layer base blocks, find all of them
176
+ const allBaseBlocks = [baseBlock];
177
+ // Look for additional @layer base blocks (app-specific ones come later)
178
+ let searchStart = compiledCss.indexOf(baseBlock) + baseBlock.length;
179
+ while (searchStart < compiledCss.length) {
180
+ const nextBase = extractLayerBlock(compiledCss.slice(searchStart), "base");
181
+ if (nextBase) {
182
+ allBaseBlocks.push(nextBase);
183
+ searchStart +=
184
+ compiledCss.slice(searchStart).indexOf(nextBase) + nextBase.length;
185
+ }
186
+ else {
187
+ break;
188
+ }
189
+ }
190
+ // Parse and filter rules from all base blocks
191
+ for (const block of allBaseBlocks) {
192
+ const rules = parseCssRules(block);
193
+ for (const rule of rules) {
194
+ if (shouldIncludeSelector(rule.selector)) {
195
+ // Clean up the declarations (remove extra whitespace)
196
+ const cleanDeclarations = rule.declarations
197
+ .replace(/\s+/g, " ")
198
+ .replace(/;\s*/g, ";")
199
+ .replace(/:\s*/g, ":")
200
+ .trim();
201
+ if (cleanDeclarations) {
202
+ cssLines.push(`${rule.selector}{${cleanDeclarations}}`);
203
+ rulesExtracted++;
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ const css = cssLines.join("\n");
210
+ const stats = {
211
+ variableCount: Object.keys(themeVariables).length,
212
+ rulesExtracted,
213
+ size: new TextEncoder().encode(css).length,
214
+ };
215
+ criticalUniversalCssLogger.debug(`Extracted critical universal CSS: ${stats.size} bytes, ${stats.rulesExtracted} rules, ${stats.variableCount} theme variables`);
216
+ return { css, themeVariables, stats };
217
+ }
218
+ /**
219
+ * Generate the critical universal CSS from compiled CSS.
220
+ *
221
+ * @param compiledCss - The full compiled CSS
222
+ * @returns Minified CSS string ready for inline embedding
223
+ */
224
+ export function generateCriticalUniversalCss(compiledCss) {
225
+ const result = extractCriticalUniversalCss(compiledCss);
226
+ // Minify by removing unnecessary whitespace
227
+ return result.css
228
+ .replace(/\n+/g, "")
229
+ .replace(/\s*{\s*/g, "{")
230
+ .replace(/\s*}\s*/g, "}")
231
+ .replace(/\s*;\s*/g, ";")
232
+ .replace(/\s*:\s*/g, ":")
233
+ .replace(/;\}/g, "}");
234
+ }
235
+ /**
236
+ * Extract only the @layer theme block from compiled CSS.
237
+ *
238
+ * @param compiledCss - The full compiled CSS
239
+ * @returns The @layer theme block content or null if not found
240
+ */
241
+ export function extractThemeLayer(compiledCss) {
242
+ return extractLayerBlock(compiledCss, "theme");
243
+ }
244
+ /**
245
+ * Default critical universal CSS for when no compiled CSS is available yet.
246
+ * Used during initial page loads before the build completes.
247
+ * This is minimal and safe - scrollbar-gutter prevents layout shift,
248
+ * box-sizing is universal best practice.
249
+ */
250
+ export const DEFAULT_CRITICAL_UNIVERSAL_CSS = "html{scrollbar-gutter:stable}*,*::before,*::after{box-sizing:border-box}";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Tailwind CSS Adapter
3
+ * Tailwind CSS v4 support for Laroux bundler
4
+ */
5
+ export { createTailwindPlugin, type TailwindPluginOptions } from "./plugin.ts";
6
+ export { compileTailwind, expandApplyDirectives, type TailwindCompileOptions, } from "./compile.ts";
7
+ export { loadStylesheet, type StylesheetLoadResult, } from "./stylesheet-loader.ts";
8
+ export { ABOVE_FOLD_PATTERNS, CRITICAL_LAYERS, CRITICAL_PROPERTY_PATTERNS, type CriticalCssConfig, getDefaultCriticalCssConfig, } from "./critical-css-config.ts";
9
+ export { type CriticalPageCssOptions, type CriticalPageCssResult, extractCriticalPageCss, generateAsyncCssLoader, } from "./critical-page-css.ts";
10
+ export { type CriticalUniversalCssResult, DEFAULT_CRITICAL_UNIVERSAL_CSS, extractCriticalUniversalCss, extractThemeLayer, generateCriticalUniversalCss, } from "./critical-universal-css.ts";
@@ -0,0 +1,11 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Tailwind CSS Adapter
4
+ * Tailwind CSS v4 support for Laroux bundler
5
+ */
6
+ export { createTailwindPlugin } from "./plugin.js";
7
+ export { compileTailwind, expandApplyDirectives, } from "./compile.js";
8
+ export { loadStylesheet, } from "./stylesheet-loader.js";
9
+ export { ABOVE_FOLD_PATTERNS, CRITICAL_LAYERS, CRITICAL_PROPERTY_PATTERNS, getDefaultCriticalCssConfig, } from "./critical-css-config.js";
10
+ export { extractCriticalPageCss, generateAsyncCssLoader, } from "./critical-page-css.js";
11
+ export { DEFAULT_CRITICAL_UNIVERSAL_CSS, extractCriticalUniversalCss, extractThemeLayer, generateCriticalUniversalCss, } from "./critical-universal-css.js";
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Tailwind CSS Plugin for Laroux Bundler
3
+ * Uses @tailwindcss/node programmatic API + @tailwindcss/oxide for scanning
4
+ */
5
+ import type { CssPlugin, CssPluginOptions } from "../../domain/css-plugin.ts";
6
+ export type TailwindPluginOptions = CssPluginOptions & {
7
+ /** Custom patterns to detect Tailwind usage */
8
+ detectPatterns?: RegExp[];
9
+ };
10
+ /**
11
+ * Create a Tailwind CSS plugin
12
+ * Uses @tailwindcss/node programmatic API + @tailwindcss/oxide for scanning
13
+ * @param options - Plugin options
14
+ * @returns CssPlugin instance
15
+ */
16
+ export declare function createTailwindPlugin(options?: TailwindPluginOptions): CssPlugin;
@@ -0,0 +1,107 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Tailwind CSS Plugin for Laroux Bundler
4
+ * Uses @tailwindcss/node programmatic API + @tailwindcss/oxide for scanning
5
+ */
6
+ import { runtime } from "@eserstack/standards/cross-runtime";
7
+ import * as logging from "@eserstack/logging";
8
+ import * as collector from "@eserstack/collector";
9
+ import * as patterns from "@eserstack/standards/patterns";
10
+ import * as oxide from "@tailwindcss/oxide";
11
+ import * as compile from "./compile.js";
12
+ import * as criticalPageCss from "./critical-page-css.js";
13
+ import * as criticalUniversalCss from "./critical-universal-css.js";
14
+ const logger = logging.logger.getLogger(["laroux-bundler", "tailwindcss"]);
15
+ /** Extensions of the source files scanned for utility class candidates. */
16
+ const SCANNED_EXTENSIONS = ["tsx", "ts", "jsx", "js"];
17
+ /**
18
+ * Create a Tailwind CSS plugin
19
+ * Uses @tailwindcss/node programmatic API + @tailwindcss/oxide for scanning
20
+ * @param options - Plugin options
21
+ * @returns CssPlugin instance
22
+ */
23
+ export function createTailwindPlugin(options = {}) {
24
+ const { globalCssPath = "src/app/styles/global.css", autoInjectReference = true, detectPatterns = [/@tailwind\b/, /@apply\b/, /@import\s+["']tailwindcss/], } = options;
25
+ return {
26
+ name: "tailwindcss",
27
+ shouldProcess(css, _context) {
28
+ // Check if CSS contains Tailwind-specific directives
29
+ return detectPatterns.some((pattern) => pattern.test(css));
30
+ },
31
+ preprocess(css, context) {
32
+ // For CSS modules, handle @apply expansion
33
+ if (context.isModule && css.includes("@apply")) {
34
+ let processedContent = css;
35
+ // Auto-inject @reference directive if enabled and not present; the
36
+ // build turns it off for an app that sets noCssModuleAutoReference
37
+ const hasReferenceDirective = /^@reference\s+/m.test(css);
38
+ if (autoInjectReference &&
39
+ context.injectReference !== false &&
40
+ !hasReferenceDirective) {
41
+ // Calculate relative path from CSS module to global.css
42
+ const cssDir = runtime.path.dirname(context.cssPath);
43
+ const globalCssAbsPath = runtime.path.resolve(context.projectRoot, globalCssPath);
44
+ const relativePath = runtime.path.relative(cssDir, globalCssAbsPath);
45
+ processedContent = `@reference "${relativePath}";\n\n${css}`;
46
+ }
47
+ // Expand @apply directives
48
+ return compile.expandApplyDirectives(processedContent, runtime.path.dirname(context.cssPath));
49
+ }
50
+ return css;
51
+ },
52
+ async compile(css, context) {
53
+ const cssDir = runtime.path.dirname(context.cssPath);
54
+ const srcDir = runtime.path.resolve(context.projectRoot, "src");
55
+ // Collect source files for scanning
56
+ const filesToScan = [];
57
+ // Walk src directory using @eserstack/collector walkFiles. The
58
+ // extension check is done here: its glob filter supports only * and
59
+ // **, so a "*.{tsx,ts}" list would match no file.
60
+ for await (const relPath of collector.walkFiles(srcDir, undefined, /node_modules/)) {
61
+ if (!patterns.hasExtension(relPath, SCANNED_EXTENSIONS)) {
62
+ continue;
63
+ }
64
+ const fullPath = runtime.path.resolve(srcDir, relPath);
65
+ const ext = runtime.path.extname(relPath);
66
+ const content = await runtime.fs.readTextFile(fullPath);
67
+ filesToScan.push({
68
+ content,
69
+ extension: ext.slice(1), // Remove leading dot
70
+ });
71
+ }
72
+ // Scan all files for utility candidates using @tailwindcss/oxide
73
+ const scanner = new oxide.Scanner({});
74
+ const candidates = scanner.scanFiles(filesToScan);
75
+ logger.debug(`Scanned ${filesToScan.length} files, found ${Array.isArray(candidates) ? candidates.length : 0} candidates`);
76
+ // Compile with programmatic API
77
+ return compile.compileTailwind(css, {
78
+ base: cssDir,
79
+ candidates,
80
+ });
81
+ },
82
+ extractCriticalCss(compiledCss, html, options) {
83
+ const result = criticalPageCss.extractCriticalPageCss({
84
+ css: compiledCss,
85
+ html,
86
+ forceInclude: options?.forceInclude,
87
+ forceExclude: options?.forceExclude,
88
+ });
89
+ return {
90
+ critical: result.critical,
91
+ deferred: result.deferred,
92
+ stats: {
93
+ originalSize: result.stats.originalSize,
94
+ criticalSize: result.stats.criticalSize,
95
+ deferredSize: result.stats.deferredSize,
96
+ },
97
+ };
98
+ },
99
+ extractUniversalCss(compiledCss) {
100
+ const result = criticalUniversalCss.extractCriticalUniversalCss(compiledCss);
101
+ return {
102
+ css: result.css,
103
+ themeVariables: result.themeVariables,
104
+ };
105
+ },
106
+ };
107
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Stylesheet Loader for Tailwind CSS
3
+ * Handles @import and @reference directives with npm module resolution
4
+ */
5
+ export type StylesheetLoadResult = {
6
+ path: string;
7
+ content: string;
8
+ base: string;
9
+ };
10
+ /**
11
+ * Load a stylesheet for Tailwind's compile() API
12
+ * Handles @import and @reference directives
13
+ * Supports both relative paths and npm module imports
14
+ */
15
+ export declare function loadStylesheet(id: string, base: string): Promise<StylesheetLoadResult>;
@@ -0,0 +1,83 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Stylesheet Loader for Tailwind CSS
4
+ * Handles @import and @reference directives with npm module resolution
5
+ */
6
+ import { runtime } from "@eserstack/standards/cross-runtime";
7
+ /**
8
+ * Load a stylesheet for Tailwind's compile() API
9
+ * Handles @import and @reference directives
10
+ * Supports both relative paths and npm module imports
11
+ */
12
+ export async function loadStylesheet(id, base) {
13
+ // Check if it's a relative or absolute path
14
+ if (id.startsWith(".") || id.startsWith("/")) {
15
+ const resolvedPath = runtime.path.resolve(base, id);
16
+ const content = await runtime.fs.readTextFile(resolvedPath);
17
+ return {
18
+ path: resolvedPath,
19
+ content,
20
+ base: runtime.path.dirname(resolvedPath),
21
+ };
22
+ }
23
+ // Handle npm module imports (e.g., "tailwindcss", "tailwindcss/theme.css")
24
+ // Walk up directory tree to find node_modules
25
+ let searchBase = base;
26
+ while (searchBase !== "/" && searchBase !== "") {
27
+ for (const candidate of nodeModulesCandidates(searchBase, id)) {
28
+ // Candidates are tried in resolution order and the walk stops at the
29
+ // first readable one, so later candidates are never read.
30
+ // oxlint-disable-next-line no-await-in-loop
31
+ const loaded = await tryLoadStylesheet(candidate);
32
+ if (loaded !== null) {
33
+ return loaded;
34
+ }
35
+ }
36
+ // Move up one directory; dirname of a Windows drive root returns it
37
+ // unchanged, which ends the walk there
38
+ const parent = runtime.path.dirname(searchBase);
39
+ if (parent === searchBase) {
40
+ break;
41
+ }
42
+ searchBase = parent;
43
+ }
44
+ // Fallback to treating as a relative path
45
+ const resolvedPath = runtime.path.resolve(base, id);
46
+ const content = await runtime.fs.readTextFile(resolvedPath);
47
+ return {
48
+ path: resolvedPath,
49
+ content,
50
+ base: runtime.path.dirname(resolvedPath),
51
+ };
52
+ }
53
+ /**
54
+ * Paths to try under one node_modules directory, in resolution order:
55
+ * the id itself, the id with a .css extension, then the package's index.css
56
+ */
57
+ function nodeModulesCandidates(searchBase, id) {
58
+ const nodeModulesPath = runtime.path.resolve(searchBase, "node_modules", id);
59
+ const candidates = [nodeModulesPath];
60
+ if (!id.endsWith(".css")) {
61
+ candidates.push(`${nodeModulesPath}.css`);
62
+ }
63
+ candidates.push(runtime.path.resolve(nodeModulesPath, "index.css"));
64
+ return candidates;
65
+ }
66
+ /**
67
+ * Read a stylesheet, or return null when the path cannot be read. A bare
68
+ * package id usually names a directory, so a failed read here is expected
69
+ * and means "try the next candidate".
70
+ */
71
+ async function tryLoadStylesheet(filePath) {
72
+ try {
73
+ const content = await runtime.fs.readTextFile(filePath);
74
+ return {
75
+ path: filePath,
76
+ content,
77
+ base: runtime.path.dirname(filePath),
78
+ };
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Build Configuration
3
+ * Static presets for bundler settings
4
+ */
5
+ /**
6
+ * Bundler backend: Rolldown, for the client and the server bundles.
7
+ */
8
+ export type BundlerBackend = "rolldown";
9
+ /**
10
+ * Build settings type
11
+ */
12
+ export type BuildSettings = {
13
+ minify: boolean;
14
+ sourceMaps: boolean;
15
+ codeSplitting: boolean;
16
+ define: Record<string, string>;
17
+ };
18
+ /**
19
+ * Production settings - used by PrebuiltBundler
20
+ * Optimized for deployment: minified, no source maps
21
+ */
22
+ export declare const PRODUCTION_SETTINGS: BuildSettings;
23
+ /**
24
+ * Development settings - used by RuntimeBundler
25
+ * Optimized for debugging: no minification, source maps enabled
26
+ */
27
+ export declare const DEVELOPMENT_SETTINGS: BuildSettings;
package/dist/config.js ADDED
@@ -0,0 +1,31 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Build Configuration
4
+ * Static presets for bundler settings
5
+ */
6
+ /**
7
+ * Production settings - used by PrebuiltBundler
8
+ * Optimized for deployment: minified, no source maps
9
+ */
10
+ export const PRODUCTION_SETTINGS = {
11
+ minify: true,
12
+ sourceMaps: false,
13
+ codeSplitting: true,
14
+ define: {
15
+ "process.env.NODE_ENV": '"production"',
16
+ "process.env.DEBUG": '"false"',
17
+ },
18
+ };
19
+ /**
20
+ * Development settings - used by RuntimeBundler
21
+ * Optimized for debugging: no minification, source maps enabled
22
+ */
23
+ export const DEVELOPMENT_SETTINGS = {
24
+ minify: false,
25
+ sourceMaps: true,
26
+ codeSplitting: false,
27
+ define: {
28
+ "process.env.NODE_ENV": '"development"',
29
+ "process.env.DEBUG": '"false"',
30
+ },
31
+ };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * CSS Modules Handler
3
+ * Re-exports @eserstack/bundler/css CSS modules utilities with laroux-specific caching.
4
+ * The caller's CSS plugin preprocesses each module; the Tailwind plugin
5
+ * injects @reference and expands @apply.
6
+ */
7
+ import type { CssModuleResult as EserCssModuleResult } from "@eserstack/bundler/css";
8
+ import type { CssPlugin } from "./domain/css-plugin.ts";
9
+ import type { BuildCache } from "./domain/build-cache.ts";
10
+ export type CSSModuleResult = EserCssModuleResult;
11
+ export type ProcessCSSModuleOptions = {
12
+ /** Whether to generate TypeScript .d.ts file */
13
+ generateDTS?: boolean;
14
+ /** Project root directory */
15
+ projectRoot?: string;
16
+ /** Whether to minify */
17
+ minify?: boolean;
18
+ /**
19
+ * CSS plugin that preprocesses each module, such as the Tailwind plugin
20
+ * expanding @apply. Without one, modules are compiled as written.
21
+ */
22
+ plugin?: CssPlugin;
23
+ /**
24
+ * Let the plugin add an @reference to the global stylesheet to a module
25
+ * that has none (default: true)
26
+ */
27
+ injectReference?: boolean;
28
+ };
29
+ /**
30
+ * Process a single CSS module file
31
+ * Uses plugin for @reference injection and @apply expansion
32
+ */
33
+ export declare function processCSSModule(cssPath: string, options?: ProcessCSSModuleOptions): Promise<CSSModuleResult>;
34
+ export type ProcessCSSModulesOptions = ProcessCSSModuleOptions & {
35
+ /** Build cache for incremental builds */
36
+ cache?: BuildCache;
37
+ };
38
+ /**
39
+ * Process multiple CSS modules in parallel with one shared CSS plugin
40
+ */
41
+ export declare function processCSSModules(cssPaths: string[], options?: ProcessCSSModulesOptions): Promise<Map<string, CSSModuleResult>>;
42
+ /**
43
+ * Save CSS module outputs to disk
44
+ */
45
+ export declare function saveCSSModuleOutputs(cssPath: string, result: CSSModuleResult, outputDir: string, options?: {
46
+ skipCss?: boolean;
47
+ projectRoot?: string;
48
+ }): Promise<void>;
49
+ export { generateTypeScriptDefinition } from "@eserstack/bundler/css";