@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.
- package/LICENSE +13 -0
- package/README.md +431 -2
- 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 +83 -3
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Critical CSS Configuration for Tailwind CSS v4
|
|
4
|
+
*
|
|
5
|
+
* This configuration defines which CSS rules should be included in critical CSS
|
|
6
|
+
* for optimal initial page render. Since this is Tailwind-specific, it's bundled
|
|
7
|
+
* with the Tailwind plugin.
|
|
8
|
+
*
|
|
9
|
+
* Key concepts:
|
|
10
|
+
* - @layer theme: Contains CSS variables (--spacing, --color-*, etc.)
|
|
11
|
+
* - @layer base: Contains reset/preflight styles
|
|
12
|
+
* - @layer utilities: Contains utility classes (split based on usage)
|
|
13
|
+
* - @property: CSS Houdini properties (needed for gradients, transforms)
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* CSS layers that MUST always be in critical CSS
|
|
17
|
+
* These contain foundational styles that all utilities depend on
|
|
18
|
+
*/
|
|
19
|
+
export const CRITICAL_LAYERS = [
|
|
20
|
+
"theme",
|
|
21
|
+
"base",
|
|
22
|
+
"properties",
|
|
23
|
+
];
|
|
24
|
+
/**
|
|
25
|
+
* Heuristics for above-the-fold utility classes
|
|
26
|
+
* These patterns match classes that are likely needed for initial render
|
|
27
|
+
* to prevent Cumulative Layout Shift (CLS)
|
|
28
|
+
*/
|
|
29
|
+
export const ABOVE_FOLD_PATTERNS = [
|
|
30
|
+
// Layout utilities - critical for preventing CLS
|
|
31
|
+
/^\.(flex|grid|block|inline|hidden)/,
|
|
32
|
+
/^\.(items-|justify-|gap-|space-)/,
|
|
33
|
+
/^\.(w-|h-|min-h-|max-w-)/,
|
|
34
|
+
/^\.(p-|px-|py-|pt-|pb-|pl-|pr-)/,
|
|
35
|
+
/^\.(m-|mx-|my-|mt-|mb-|ml-|mr-)/,
|
|
36
|
+
// Typography
|
|
37
|
+
/^\.(text-|font-|leading-)/,
|
|
38
|
+
// Colors and backgrounds
|
|
39
|
+
/^\.(bg-|border-)/,
|
|
40
|
+
// Gradients (needed for gradient text which uses text-transparent)
|
|
41
|
+
/^\.(from-|via-|to-)/,
|
|
42
|
+
// Structural
|
|
43
|
+
/^\.(container|wrapper)/,
|
|
44
|
+
/^\.(rounded|shadow)/,
|
|
45
|
+
/^\.(overflow-)/,
|
|
46
|
+
// Responsive - sm/md/lg variants (critical for layout)
|
|
47
|
+
/^\.(sm:|md:|lg:|xl:)/,
|
|
48
|
+
];
|
|
49
|
+
/**
|
|
50
|
+
* CSS features that require @property declarations
|
|
51
|
+
* These must be in critical CSS for the features to work on initial render
|
|
52
|
+
*/
|
|
53
|
+
export const CRITICAL_PROPERTY_PATTERNS = [
|
|
54
|
+
// Gradients
|
|
55
|
+
/--tw-gradient/,
|
|
56
|
+
// Transforms
|
|
57
|
+
/--tw-rotate/,
|
|
58
|
+
/--tw-scale/,
|
|
59
|
+
/--tw-skew/,
|
|
60
|
+
/--tw-translate/,
|
|
61
|
+
// Shadows
|
|
62
|
+
/--tw-shadow/,
|
|
63
|
+
/--tw-ring/,
|
|
64
|
+
// Filters
|
|
65
|
+
/--tw-blur/,
|
|
66
|
+
/--tw-brightness/,
|
|
67
|
+
];
|
|
68
|
+
/**
|
|
69
|
+
* Get the default critical CSS configuration for Tailwind v4
|
|
70
|
+
*/
|
|
71
|
+
export function getDefaultCriticalCssConfig() {
|
|
72
|
+
return {
|
|
73
|
+
criticalLayers: CRITICAL_LAYERS,
|
|
74
|
+
aboveFoldPatterns: ABOVE_FOLD_PATTERNS,
|
|
75
|
+
forceInclude: [],
|
|
76
|
+
forceExclude: [],
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Critical Page CSS Extraction for Tailwind CSS v4
|
|
3
|
+
*
|
|
4
|
+
* Extracts page-specific above-the-fold CSS while properly handling Tailwind's @layer system:
|
|
5
|
+
* - @layer theme: ALWAYS critical (contains CSS variables)
|
|
6
|
+
* - @layer base: ALWAYS critical (reset/preflight styles)
|
|
7
|
+
* - @layer utilities: Split based on selector usage in HTML
|
|
8
|
+
*
|
|
9
|
+
* @see https://tailwindcss.com/docs/functions-and-directives#layer
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Critical page CSS extraction options
|
|
13
|
+
*/
|
|
14
|
+
export type CriticalPageCssOptions = {
|
|
15
|
+
/** HTML content to analyze */
|
|
16
|
+
html: string;
|
|
17
|
+
/** CSS content to split */
|
|
18
|
+
css: string;
|
|
19
|
+
/** Whether to minify output (disabled for Tailwind v4 due to CSS nesting) */
|
|
20
|
+
minify?: boolean;
|
|
21
|
+
/** Selectors to always include in critical CSS */
|
|
22
|
+
forceInclude?: (string | RegExp)[];
|
|
23
|
+
/** Selectors to always exclude from critical CSS */
|
|
24
|
+
forceExclude?: (string | RegExp)[];
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Result of critical page CSS extraction
|
|
28
|
+
*/
|
|
29
|
+
export type CriticalPageCssResult = {
|
|
30
|
+
/** Critical CSS to inline in <head> */
|
|
31
|
+
critical: string;
|
|
32
|
+
/** Deferred CSS to load asynchronously */
|
|
33
|
+
deferred: string;
|
|
34
|
+
/** Statistics about extraction */
|
|
35
|
+
stats: {
|
|
36
|
+
/** Original CSS size in bytes */
|
|
37
|
+
originalSize: number;
|
|
38
|
+
/** Critical CSS size in bytes */
|
|
39
|
+
criticalSize: number;
|
|
40
|
+
/** Deferred CSS size in bytes */
|
|
41
|
+
deferredSize: number;
|
|
42
|
+
/** Number of critical rules */
|
|
43
|
+
criticalRules: number;
|
|
44
|
+
/** Number of deferred rules */
|
|
45
|
+
deferredRules: number;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Extract critical page CSS from full CSS based on HTML content
|
|
50
|
+
*
|
|
51
|
+
* Strategy:
|
|
52
|
+
* 1. Always include @layer theme (CSS variables)
|
|
53
|
+
* 2. Always include @layer base (reset/preflight)
|
|
54
|
+
* 3. Split @layer utilities based on selector usage and above-fold heuristics
|
|
55
|
+
* 4. Include @font-face and used @keyframes
|
|
56
|
+
*/
|
|
57
|
+
export declare function extractCriticalPageCss(options: CriticalPageCssOptions): CriticalPageCssResult;
|
|
58
|
+
/**
|
|
59
|
+
* Generate inline critical CSS script for async loading
|
|
60
|
+
*/
|
|
61
|
+
export declare function generateAsyncCssLoader(deferredCssPath: string): string;
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Critical Page CSS Extraction for Tailwind CSS v4
|
|
4
|
+
*
|
|
5
|
+
* Extracts page-specific above-the-fold CSS while properly handling Tailwind's @layer system:
|
|
6
|
+
* - @layer theme: ALWAYS critical (contains CSS variables)
|
|
7
|
+
* - @layer base: ALWAYS critical (reset/preflight styles)
|
|
8
|
+
* - @layer utilities: Split based on selector usage in HTML
|
|
9
|
+
*
|
|
10
|
+
* @see https://tailwindcss.com/docs/functions-and-directives#layer
|
|
11
|
+
*/
|
|
12
|
+
import * as logging from "@eserstack/logging";
|
|
13
|
+
import * as criticalCssConfig from "./critical-css-config.js";
|
|
14
|
+
const criticalPageCssLogger = logging.logger.getLogger([
|
|
15
|
+
"laroux-bundler",
|
|
16
|
+
"critical-page-css",
|
|
17
|
+
]);
|
|
18
|
+
/**
|
|
19
|
+
* Extract a @layer block starting from a specific position
|
|
20
|
+
*/
|
|
21
|
+
function extractLayerBlockAt(css, startIndex) {
|
|
22
|
+
// Find opening brace
|
|
23
|
+
let pos = startIndex;
|
|
24
|
+
while (pos < css.length && css[pos] !== "{")
|
|
25
|
+
pos++;
|
|
26
|
+
if (pos >= css.length)
|
|
27
|
+
return null;
|
|
28
|
+
const contentStart = pos + 1;
|
|
29
|
+
let braceCount = 1;
|
|
30
|
+
pos++; // Skip opening brace
|
|
31
|
+
// Find matching closing brace
|
|
32
|
+
while (pos < css.length && braceCount > 0) {
|
|
33
|
+
if (css[pos] === "{")
|
|
34
|
+
braceCount++;
|
|
35
|
+
else if (css[pos] === "}")
|
|
36
|
+
braceCount--;
|
|
37
|
+
pos++;
|
|
38
|
+
}
|
|
39
|
+
// Extract inner content (without the @layer wrapper)
|
|
40
|
+
const innerContent = css.slice(contentStart, pos - 1).trim();
|
|
41
|
+
return { innerContent, end: pos };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Extract @keyframes blocks from CSS safely without ReDoS-prone regex
|
|
45
|
+
* Uses character-by-character parsing to handle nested braces
|
|
46
|
+
*/
|
|
47
|
+
function extractKeyframes(css) {
|
|
48
|
+
const results = [];
|
|
49
|
+
const keyframesMarker = "@keyframes";
|
|
50
|
+
let searchPos = 0;
|
|
51
|
+
while (searchPos < css.length) {
|
|
52
|
+
const keyframesStart = css.indexOf(keyframesMarker, searchPos);
|
|
53
|
+
if (keyframesStart === -1)
|
|
54
|
+
break;
|
|
55
|
+
// Extract animation name (after @keyframes and before {)
|
|
56
|
+
let nameStart = keyframesStart + keyframesMarker.length;
|
|
57
|
+
while (nameStart < css.length && /\s/.test(css[nameStart] ?? "")) {
|
|
58
|
+
nameStart++;
|
|
59
|
+
}
|
|
60
|
+
let nameEnd = nameStart;
|
|
61
|
+
while (nameEnd < css.length &&
|
|
62
|
+
css[nameEnd] !== "{" &&
|
|
63
|
+
!/\s/.test(css[nameEnd] ?? "")) {
|
|
64
|
+
nameEnd++;
|
|
65
|
+
}
|
|
66
|
+
const name = css.slice(nameStart, nameEnd);
|
|
67
|
+
// Find opening brace
|
|
68
|
+
let braceStart = nameEnd;
|
|
69
|
+
while (braceStart < css.length && css[braceStart] !== "{") {
|
|
70
|
+
braceStart++;
|
|
71
|
+
}
|
|
72
|
+
if (braceStart >= css.length) {
|
|
73
|
+
searchPos = css.length;
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
// Find matching closing brace using brace counting
|
|
77
|
+
let braceCount = 1;
|
|
78
|
+
let pos = braceStart + 1;
|
|
79
|
+
while (pos < css.length && braceCount > 0) {
|
|
80
|
+
if (css[pos] === "{")
|
|
81
|
+
braceCount++;
|
|
82
|
+
else if (css[pos] === "}")
|
|
83
|
+
braceCount--;
|
|
84
|
+
pos++;
|
|
85
|
+
}
|
|
86
|
+
const block = css.slice(keyframesStart, pos);
|
|
87
|
+
results.push({ name, block });
|
|
88
|
+
searchPos = pos;
|
|
89
|
+
}
|
|
90
|
+
return results;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Extract all @layer blocks from CSS
|
|
94
|
+
* Handles multiple blocks with the same layer name by combining their content
|
|
95
|
+
*/
|
|
96
|
+
function extractAllLayers(css) {
|
|
97
|
+
const layers = new Map();
|
|
98
|
+
// Track all inner contents for each layer name (to handle duplicates)
|
|
99
|
+
const layerContents = new Map();
|
|
100
|
+
const layerPositions = new Map();
|
|
101
|
+
// Match @layer declarations (both @layer name; and @layer name { ... })
|
|
102
|
+
const layerPattern = /@layer\s+([a-zA-Z_-][a-zA-Z0-9_-]*)\s*[{;]/g;
|
|
103
|
+
let match;
|
|
104
|
+
while ((match = layerPattern.exec(css)) !== null) {
|
|
105
|
+
const layerName = match[1];
|
|
106
|
+
if (layerName === undefined)
|
|
107
|
+
continue;
|
|
108
|
+
// Check if it's a declaration (@layer name;) or block (@layer name { ... })
|
|
109
|
+
if (match[0].endsWith(";")) {
|
|
110
|
+
// Layer declaration only - not a block
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const extracted = extractLayerBlockAt(css, match.index + match[0].length - 1);
|
|
114
|
+
if (extracted) {
|
|
115
|
+
// Accumulate content for this layer
|
|
116
|
+
if (!layerContents.has(layerName)) {
|
|
117
|
+
layerContents.set(layerName, []);
|
|
118
|
+
layerPositions.set(layerName, {
|
|
119
|
+
start: match.index,
|
|
120
|
+
end: extracted.end,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
layerContents.get(layerName).push(extracted.innerContent);
|
|
124
|
+
// Update end position to the last block
|
|
125
|
+
layerPositions.get(layerName).end = extracted.end;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
// Build combined blocks
|
|
129
|
+
for (const [layerName, contents] of layerContents) {
|
|
130
|
+
const combinedContent = contents.join("\n");
|
|
131
|
+
const positions = layerPositions.get(layerName);
|
|
132
|
+
layers.set(layerName, {
|
|
133
|
+
block: `@layer ${layerName} {\n${combinedContent}\n}`,
|
|
134
|
+
start: positions.start,
|
|
135
|
+
end: positions.end,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
return layers;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Parse CSS rules from a string (for utility layer splitting)
|
|
142
|
+
* Handles Tailwind v4's nested @media syntax inside selectors
|
|
143
|
+
*/
|
|
144
|
+
function parseUtilityRules(css) {
|
|
145
|
+
const rules = [];
|
|
146
|
+
// Use brace-matching to extract complete rules with nested content
|
|
147
|
+
let pos = 0;
|
|
148
|
+
while (pos < css.length) {
|
|
149
|
+
// Skip whitespace
|
|
150
|
+
while (pos < css.length && /\s/.test(css[pos]))
|
|
151
|
+
pos++;
|
|
152
|
+
if (pos >= css.length)
|
|
153
|
+
break;
|
|
154
|
+
// Find selector start
|
|
155
|
+
const selectorStart = pos;
|
|
156
|
+
// Find opening brace
|
|
157
|
+
while (pos < css.length && css[pos] !== "{")
|
|
158
|
+
pos++;
|
|
159
|
+
if (pos >= css.length)
|
|
160
|
+
break;
|
|
161
|
+
const selector = css.slice(selectorStart, pos).trim();
|
|
162
|
+
if (!selector) {
|
|
163
|
+
pos++;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
// Match braces to find complete block (handles nested @media)
|
|
167
|
+
let braceCount = 1;
|
|
168
|
+
pos++; // Skip opening brace
|
|
169
|
+
while (pos < css.length && braceCount > 0) {
|
|
170
|
+
if (css[pos] === "{")
|
|
171
|
+
braceCount++;
|
|
172
|
+
else if (css[pos] === "}")
|
|
173
|
+
braceCount--;
|
|
174
|
+
pos++;
|
|
175
|
+
}
|
|
176
|
+
const fullRule = css.slice(selectorStart, pos);
|
|
177
|
+
// Top-level @media blocks (not nested in selectors)
|
|
178
|
+
if (selector.startsWith("@media") || selector.startsWith("@supports")) {
|
|
179
|
+
rules.push({ selector: "@media", full: fullRule });
|
|
180
|
+
}
|
|
181
|
+
else if (selector && !selector.startsWith("@")) {
|
|
182
|
+
rules.push({
|
|
183
|
+
selector,
|
|
184
|
+
full: fullRule,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return rules;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Check if a selector is used in HTML
|
|
192
|
+
*/
|
|
193
|
+
function selectorMatchesHtml(selector, html) {
|
|
194
|
+
// Extract class names from selector
|
|
195
|
+
const classMatches = selector.match(/\.([a-zA-Z_-][a-zA-Z0-9_\-\\:/.[\]]*)/g);
|
|
196
|
+
if (classMatches) {
|
|
197
|
+
for (const classMatch of classMatches) {
|
|
198
|
+
// Clean up escaped characters and get class name
|
|
199
|
+
let className = classMatch.substring(1); // Remove leading dot
|
|
200
|
+
className = className.replace(/\\/g, ""); // Remove escapes
|
|
201
|
+
className = className.split(":")[0] ?? ""; // Remove pseudo-classes
|
|
202
|
+
// Check if class is in HTML
|
|
203
|
+
if (className &&
|
|
204
|
+
new RegExp(`class=["'][^"']*\\b${escapeRegex(className)}\\b`, "i").test(html)) {
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
// Extract element selectors
|
|
210
|
+
const elementMatch = selector.match(/^([a-zA-Z][a-zA-Z0-9-]*)/);
|
|
211
|
+
if (elementMatch && elementMatch[1]) {
|
|
212
|
+
const element = elementMatch[1].toLowerCase();
|
|
213
|
+
if (new RegExp(`<${element}[\\s>]`, "i").test(html)) {
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
// Extract ID selectors
|
|
218
|
+
const idMatches = selector.match(/#([a-zA-Z_-][a-zA-Z0-9_-]*)/g);
|
|
219
|
+
if (idMatches) {
|
|
220
|
+
for (const idMatch of idMatches) {
|
|
221
|
+
const id = idMatch.substring(1);
|
|
222
|
+
if (new RegExp(`id=["']${id}["']`, "i").test(html)) {
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Escape special regex characters
|
|
231
|
+
*/
|
|
232
|
+
function escapeRegex(str) {
|
|
233
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Check if selector matches force patterns
|
|
237
|
+
*/
|
|
238
|
+
function matchesForcePatterns(selector, patterns) {
|
|
239
|
+
return patterns.some((pattern) => {
|
|
240
|
+
if (typeof pattern === "string") {
|
|
241
|
+
return selector.includes(pattern);
|
|
242
|
+
}
|
|
243
|
+
return pattern.test(selector);
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Check if a utility selector is likely above-the-fold
|
|
248
|
+
*/
|
|
249
|
+
function isLikelyAboveFold(selector) {
|
|
250
|
+
return criticalCssConfig.ABOVE_FOLD_PATTERNS.some((pattern) => pattern.test(selector));
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Extract critical page CSS from full CSS based on HTML content
|
|
254
|
+
*
|
|
255
|
+
* Strategy:
|
|
256
|
+
* 1. Always include @layer theme (CSS variables)
|
|
257
|
+
* 2. Always include @layer base (reset/preflight)
|
|
258
|
+
* 3. Split @layer utilities based on selector usage and above-fold heuristics
|
|
259
|
+
* 4. Include @font-face and used @keyframes
|
|
260
|
+
*/
|
|
261
|
+
export function extractCriticalPageCss(options) {
|
|
262
|
+
const { html, css, forceInclude = [], forceExclude = [] } = options;
|
|
263
|
+
criticalPageCssLogger.debug("Extracting critical page CSS (Tailwind v4 aware)...");
|
|
264
|
+
const criticalParts = [];
|
|
265
|
+
const deferredParts = [];
|
|
266
|
+
let criticalRuleCount = 0;
|
|
267
|
+
let deferredRuleCount = 0;
|
|
268
|
+
// Preserve the Tailwind comment header
|
|
269
|
+
const headerMatch = css.match(/^\/\*![\s\S]*?\*\//);
|
|
270
|
+
if (headerMatch) {
|
|
271
|
+
criticalParts.push(headerMatch[0]);
|
|
272
|
+
}
|
|
273
|
+
// Extract @layer order declaration (must be first)
|
|
274
|
+
// Use bounded pattern to prevent ReDoS - layer names are limited to 200 chars
|
|
275
|
+
const layerOrderMatch = css.match(/@layer\s+[\w,-]{1,200}(?:\s+[\w,-]{1,50})*\s*;/);
|
|
276
|
+
if (layerOrderMatch) {
|
|
277
|
+
criticalParts.push(layerOrderMatch[0]);
|
|
278
|
+
}
|
|
279
|
+
// Extract @property rules (CSS Houdini - needed for gradients, transforms, etc.)
|
|
280
|
+
// These MUST be in critical CSS for gradient text and other effects to work
|
|
281
|
+
// Use bounded pattern [^}]{0,5000} to prevent ReDoS
|
|
282
|
+
const propertyRegex = /@property\s+--[\w-]+\s*\{[^}]{0,5000}\}/g;
|
|
283
|
+
const propertyRules = css.match(propertyRegex) ?? [];
|
|
284
|
+
if (propertyRules.length > 0) {
|
|
285
|
+
criticalParts.push(propertyRules.join("\n"));
|
|
286
|
+
criticalRuleCount += propertyRules.length;
|
|
287
|
+
criticalPageCssLogger.debug(` @property rules: ${propertyRules.length} (CRITICAL)`);
|
|
288
|
+
}
|
|
289
|
+
// Extract all layer blocks
|
|
290
|
+
const layers = extractAllLayers(css);
|
|
291
|
+
// Process each layer
|
|
292
|
+
for (const [layerName, layerData] of layers) {
|
|
293
|
+
if (criticalCssConfig.CRITICAL_LAYERS.includes(layerName)) {
|
|
294
|
+
// Theme, base, properties - ALWAYS critical
|
|
295
|
+
criticalParts.push(layerData.block);
|
|
296
|
+
criticalRuleCount++;
|
|
297
|
+
criticalPageCssLogger.debug(` @layer ${layerName}: CRITICAL (required)`);
|
|
298
|
+
}
|
|
299
|
+
else if (layerName === "utilities") {
|
|
300
|
+
// Split utilities based on usage
|
|
301
|
+
const { critical: criticalUtils, deferred: deferredUtils } = splitUtilityLayer(layerData.block, html, forceInclude, forceExclude);
|
|
302
|
+
if (criticalUtils.trim()) {
|
|
303
|
+
criticalParts.push(`@layer utilities {\n${criticalUtils}\n}`);
|
|
304
|
+
criticalRuleCount += criticalUtils.split("}").length - 1;
|
|
305
|
+
}
|
|
306
|
+
if (deferredUtils.trim()) {
|
|
307
|
+
deferredParts.push(`@layer utilities {\n${deferredUtils}\n}`);
|
|
308
|
+
deferredRuleCount += deferredUtils.split("}").length - 1;
|
|
309
|
+
}
|
|
310
|
+
criticalPageCssLogger.debug(` @layer utilities: split`);
|
|
311
|
+
}
|
|
312
|
+
else if (layerName === "components") {
|
|
313
|
+
// Components - include if selectors match HTML
|
|
314
|
+
const { critical: criticalComps, deferred: deferredComps } = splitUtilityLayer(layerData.block, html, forceInclude, forceExclude);
|
|
315
|
+
if (criticalComps.trim()) {
|
|
316
|
+
criticalParts.push(`@layer components {\n${criticalComps}\n}`);
|
|
317
|
+
criticalRuleCount++;
|
|
318
|
+
}
|
|
319
|
+
if (deferredComps.trim()) {
|
|
320
|
+
deferredParts.push(`@layer components {\n${deferredComps}\n}`);
|
|
321
|
+
deferredRuleCount++;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
// Unknown layers - defer
|
|
326
|
+
deferredParts.push(layerData.block);
|
|
327
|
+
deferredRuleCount++;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
// Handle @font-face (always critical)
|
|
331
|
+
// Use bounded pattern [^}]{0,10000} to prevent ReDoS
|
|
332
|
+
const fontFaceRegex = /@font-face\s*\{[^}]{0,10000}\}/gi;
|
|
333
|
+
const fontFaces = css.match(fontFaceRegex) ?? [];
|
|
334
|
+
for (const fontFace of fontFaces) {
|
|
335
|
+
criticalParts.push(fontFace);
|
|
336
|
+
criticalRuleCount++;
|
|
337
|
+
}
|
|
338
|
+
// Handle @keyframes (critical if animation name is used in HTML)
|
|
339
|
+
// Use a safer extraction approach to prevent ReDoS
|
|
340
|
+
const keyframes = extractKeyframes(css);
|
|
341
|
+
for (const keyframe of keyframes) {
|
|
342
|
+
if (keyframe.name && html.includes(keyframe.name)) {
|
|
343
|
+
criticalParts.push(keyframe.block);
|
|
344
|
+
criticalRuleCount++;
|
|
345
|
+
}
|
|
346
|
+
else {
|
|
347
|
+
deferredParts.push(keyframe.block);
|
|
348
|
+
deferredRuleCount++;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// Build output
|
|
352
|
+
const critical = criticalParts.join("\n\n");
|
|
353
|
+
const deferred = deferredParts.join("\n\n");
|
|
354
|
+
const stats = {
|
|
355
|
+
originalSize: new TextEncoder().encode(css).length,
|
|
356
|
+
criticalSize: new TextEncoder().encode(critical).length,
|
|
357
|
+
deferredSize: new TextEncoder().encode(deferred).length,
|
|
358
|
+
criticalRules: criticalRuleCount,
|
|
359
|
+
deferredRules: deferredRuleCount,
|
|
360
|
+
};
|
|
361
|
+
criticalPageCssLogger.debug(`Critical: ${stats.criticalSize} bytes (${criticalRuleCount} parts), ` +
|
|
362
|
+
`Deferred: ${stats.deferredSize} bytes (${deferredRuleCount} parts)`);
|
|
363
|
+
return { critical, deferred, stats };
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Split utility layer content into critical and deferred
|
|
367
|
+
*/
|
|
368
|
+
function splitUtilityLayer(layerContent, html, forceInclude, forceExclude) {
|
|
369
|
+
// Remove @layer wrapper to get inner content
|
|
370
|
+
const innerContent = layerContent
|
|
371
|
+
.replace(/^@layer\s+\w+\s*\{/, "")
|
|
372
|
+
.replace(/\}$/, "")
|
|
373
|
+
.trim();
|
|
374
|
+
const rules = parseUtilityRules(innerContent);
|
|
375
|
+
const criticalRules = [];
|
|
376
|
+
const deferredRules = [];
|
|
377
|
+
for (const rule of rules) {
|
|
378
|
+
// Media queries - check if inner selectors are critical
|
|
379
|
+
if (rule.selector === "@media") {
|
|
380
|
+
// For now, include all responsive utilities in critical
|
|
381
|
+
// (they affect layout and prevent CLS)
|
|
382
|
+
if (rule.full.includes("@media") &&
|
|
383
|
+
(rule.full.includes("min-width") || rule.full.includes("max-width"))) {
|
|
384
|
+
criticalRules.push(rule.full);
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
deferredRules.push(rule.full);
|
|
388
|
+
}
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
// Force exclude check
|
|
392
|
+
if (matchesForcePatterns(rule.selector, forceExclude)) {
|
|
393
|
+
deferredRules.push(rule.full);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
// Force include check
|
|
397
|
+
if (matchesForcePatterns(rule.selector, forceInclude)) {
|
|
398
|
+
criticalRules.push(rule.full);
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
// Check if selector is in HTML and likely above-fold
|
|
402
|
+
const inHtml = selectorMatchesHtml(rule.selector, html);
|
|
403
|
+
const aboveFold = isLikelyAboveFold(rule.selector);
|
|
404
|
+
if (inHtml || aboveFold) {
|
|
405
|
+
criticalRules.push(rule.full);
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
deferredRules.push(rule.full);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return {
|
|
412
|
+
critical: criticalRules.join("\n"),
|
|
413
|
+
deferred: deferredRules.join("\n"),
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Generate inline critical CSS script for async loading
|
|
418
|
+
*/
|
|
419
|
+
export function generateAsyncCssLoader(deferredCssPath) {
|
|
420
|
+
return `<script>
|
|
421
|
+
(function(){
|
|
422
|
+
var l=document.createElement('link');
|
|
423
|
+
l.rel='stylesheet';
|
|
424
|
+
l.href='${deferredCssPath}';
|
|
425
|
+
l.media='print';
|
|
426
|
+
l.onload=function(){this.media='all'};
|
|
427
|
+
document.head.appendChild(l);
|
|
428
|
+
})();
|
|
429
|
+
</script>
|
|
430
|
+
<noscript><link rel="stylesheet" href="${deferredCssPath}"></noscript>`;
|
|
431
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Critical Universal CSS Extraction
|
|
3
|
+
*
|
|
4
|
+
* Dynamically extracts essential base CSS from the compiled Tailwind CSS.
|
|
5
|
+
* This ensures critical CSS uses actual values from the app's global.css
|
|
6
|
+
* and theme configuration, not hardcoded values.
|
|
7
|
+
*
|
|
8
|
+
* Architecture:
|
|
9
|
+
* 1. Parse compiled CSS to find @layer base and @layer theme blocks
|
|
10
|
+
* 2. Extract specific selectors needed for initial render (html, body, #root)
|
|
11
|
+
* 3. Extract CSS variables from theme for fallbacks
|
|
12
|
+
* 4. Output as minimal CSS for fast initial paint
|
|
13
|
+
*
|
|
14
|
+
* IMPORTANT: Does NOT extract element resets (a, button, h1-h6) because
|
|
15
|
+
* unlayered CSS overrides Tailwind's @layer utilities, breaking classes
|
|
16
|
+
* like .text-white, .bg-primary-600, etc.
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* Result of critical universal CSS extraction
|
|
20
|
+
*/
|
|
21
|
+
export type CriticalUniversalCssResult = {
|
|
22
|
+
/** The generated critical universal CSS */
|
|
23
|
+
css: string;
|
|
24
|
+
/** CSS variables extracted from theme */
|
|
25
|
+
themeVariables: Record<string, string>;
|
|
26
|
+
/** Statistics about extraction */
|
|
27
|
+
stats: {
|
|
28
|
+
/** Number of CSS variables extracted */
|
|
29
|
+
variableCount: number;
|
|
30
|
+
/** Number of rules extracted */
|
|
31
|
+
rulesExtracted: number;
|
|
32
|
+
/** Total size in bytes */
|
|
33
|
+
size: number;
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Extract critical universal CSS from compiled Tailwind CSS output.
|
|
38
|
+
*
|
|
39
|
+
* This function:
|
|
40
|
+
* 1. Extracts @layer theme to get CSS variables
|
|
41
|
+
* 2. Extracts @layer base rules for critical selectors (html, body, #root, etc.)
|
|
42
|
+
* 3. Combines them into minimal critical CSS
|
|
43
|
+
*
|
|
44
|
+
* @param compiledCss - The full compiled CSS (styles.css)
|
|
45
|
+
* @returns Critical universal CSS result with extracted values
|
|
46
|
+
*/
|
|
47
|
+
export declare function extractCriticalUniversalCss(compiledCss: string): CriticalUniversalCssResult;
|
|
48
|
+
/**
|
|
49
|
+
* Generate the critical universal CSS from compiled CSS.
|
|
50
|
+
*
|
|
51
|
+
* @param compiledCss - The full compiled CSS
|
|
52
|
+
* @returns Minified CSS string ready for inline embedding
|
|
53
|
+
*/
|
|
54
|
+
export declare function generateCriticalUniversalCss(compiledCss: string): string;
|
|
55
|
+
/**
|
|
56
|
+
* Extract only the @layer theme block from compiled CSS.
|
|
57
|
+
*
|
|
58
|
+
* @param compiledCss - The full compiled CSS
|
|
59
|
+
* @returns The @layer theme block content or null if not found
|
|
60
|
+
*/
|
|
61
|
+
export declare function extractThemeLayer(compiledCss: string): string | null;
|
|
62
|
+
/**
|
|
63
|
+
* Default critical universal CSS for when no compiled CSS is available yet.
|
|
64
|
+
* Used during initial page loads before the build completes.
|
|
65
|
+
* This is minimal and safe - scrollbar-gutter prevents layout shift,
|
|
66
|
+
* box-sizing is universal best practice.
|
|
67
|
+
*/
|
|
68
|
+
export declare const DEFAULT_CRITICAL_UNIVERSAL_CSS = "html{scrollbar-gutter:stable}*,*::before,*::after{box-sizing:border-box}";
|