@flamingo-stack/openframe-frontend-core 0.0.831 → 0.0.832
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/dist/build/next-styles.cjs +93 -3
- package/dist/build/next-styles.d.ts +8 -0
- package/dist/build/route-styles-client.mjs +67 -0
- package/dist/build/route-styles-markers.cjs +18 -0
- package/dist/build/route-styles-server.mjs +102 -0
- package/dist/build/route-styles.cjs +415 -0
- package/dist/build/route-styles.d.ts +11 -0
- package/dist/build/style-sources.cjs +14 -1
- package/dist/build/style-sources.d.ts +3 -0
- package/package.json +6 -1
- package/src/styles/index.css +2 -0
|
@@ -32,12 +32,31 @@
|
|
|
32
32
|
* page's sheet is mostly its layout's. Inlining removes the wait; a smaller sheet only makes it cheap.
|
|
33
33
|
*/
|
|
34
34
|
const { execFile } = require('node:child_process');
|
|
35
|
+
const crypto = require('node:crypto');
|
|
35
36
|
const { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = require('node:fs');
|
|
36
37
|
const { tmpdir } = require('node:os');
|
|
37
38
|
const { dirname, isAbsolute, join, resolve } = require('node:path');
|
|
38
39
|
const { promisify } = require('node:util');
|
|
39
40
|
const { brotliCompressSync, constants } = require('node:zlib');
|
|
40
41
|
|
|
42
|
+
const { STYLES_DIR, BUILD_INFO } = require('./route-styles-markers.cjs');
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The complete sheet's address for a build (`{ buildId, assetPrefix, basePath }`). Named by the build, so the browser
|
|
46
|
+
* bundle knows it too: a page Next draws only in the browser (a 404 is served as an empty error shell, then rendered
|
|
47
|
+
* from its data) has no route sheet from the server and loads this one itself.
|
|
48
|
+
*/
|
|
49
|
+
const fullSheetUrl = ({ buildId, assetPrefix, basePath }) =>
|
|
50
|
+
`${(assetPrefix || basePath || '').replace(/\/$/, '')}/_next/static/next-styles/full-${buildId}.css`;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The route-sheet build (`./route-styles.cjs`), loaded only by the `build` command. The app's next.config imports
|
|
54
|
+
* this file and Turbopack traces what it imports (`join(__dirname, …)` included): reaching the build tool pulled
|
|
55
|
+
* Next's own server, sharp's native libraries and esbuild into the trace and failed the build (Next 16.3).
|
|
56
|
+
*/
|
|
57
|
+
const loadRouteStyles = () =>
|
|
58
|
+
require(/* turbopackIgnore: true */ /* webpackIgnore: true */ join(__dirname, 'route-styles.cjs'));
|
|
59
|
+
|
|
41
60
|
/** `nextConfig` with every route's stylesheets written into its HTML. Composes with a config function. */
|
|
42
61
|
function withInlineStyles(nextConfig) {
|
|
43
62
|
const apply = config => ({ ...config, experimental: { ...config.experimental, inlineCss: true } });
|
|
@@ -47,6 +66,39 @@ function withInlineStyles(nextConfig) {
|
|
|
47
66
|
return apply(nextConfig);
|
|
48
67
|
}
|
|
49
68
|
|
|
69
|
+
/**
|
|
70
|
+
* `withInlineStyles`, and per-route stylesheets when the build is `next-styles build` (`./route-styles.cjs`): the
|
|
71
|
+
* server bundle carries `.next-styles/` (filled after the build) and knows its build, and the build records the
|
|
72
|
+
* settings the route step reads. Any other build, and `next dev`, is `withInlineStyles` alone.
|
|
73
|
+
*/
|
|
74
|
+
function withRouteStyles(nextConfig) {
|
|
75
|
+
return async (phase, ...rest) => {
|
|
76
|
+
const config = typeof nextConfig === 'function' ? await nextConfig(phase, ...rest) : nextConfig;
|
|
77
|
+
const inline = withInlineStyles(config);
|
|
78
|
+
if (process.env.NEXT_STYLES !== 'routes' || phase !== 'phase-production-build') return inline;
|
|
79
|
+
const root = process.cwd();
|
|
80
|
+
const infoFile = join(root, STYLES_DIR, BUILD_INFO);
|
|
81
|
+
// One id per build: the server checks the sheets it reads were written for it.
|
|
82
|
+
const buildId = existsSync(infoFile) ? JSON.parse(readFileSync(infoFile, 'utf8')).buildId : crypto.randomUUID();
|
|
83
|
+
const info = {
|
|
84
|
+
buildId,
|
|
85
|
+
distDir: inline.distDir ?? '.next',
|
|
86
|
+
output: inline.output ?? null,
|
|
87
|
+
assetPrefix: inline.assetPrefix ?? '',
|
|
88
|
+
basePath: inline.basePath ?? '',
|
|
89
|
+
};
|
|
90
|
+
writeFileSync(infoFile, `${JSON.stringify(info, null, 2)}\n`);
|
|
91
|
+
// Every route: the files are read at run time by `RouteStyles`, which no static trace can follow.
|
|
92
|
+
const includes = { ...inline.outputFileTracingIncludes };
|
|
93
|
+
for (const route of ['/', '/*', '/*/**']) includes[route] = [...(includes[route] ?? []), `./${STYLES_DIR}/**/*`];
|
|
94
|
+
return {
|
|
95
|
+
...inline,
|
|
96
|
+
env: { ...inline.env, NEXT_STYLES_BUILD: buildId, NEXT_STYLES_FULL_URL: fullSheetUrl(info) },
|
|
97
|
+
outputFileTracingIncludes: includes,
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
50
102
|
/**
|
|
51
103
|
* The stylesheet `input` with each `@import` made an absolute path: the Tailwind CLI resolves an import
|
|
52
104
|
* by path only, never through a package's `exports` (`@import '<package>/styles'`), which a bundler does.
|
|
@@ -158,8 +210,9 @@ if (require.main === module) {
|
|
|
158
210
|
const [command, ...rest] = process.argv.slice(2);
|
|
159
211
|
Promise.resolve()
|
|
160
212
|
.then(() => {
|
|
161
|
-
if (command
|
|
162
|
-
return
|
|
213
|
+
if (command === 'budget') return budgetCommand(rest);
|
|
214
|
+
if (command === 'build') return buildCommand(rest);
|
|
215
|
+
throw new Error(`next-styles: unknown command ${command ?? '(none)'}; try "build" or "budget"`);
|
|
163
216
|
})
|
|
164
217
|
.catch(error => {
|
|
165
218
|
console.error(`[css-budget] ${error.message}`);
|
|
@@ -167,4 +220,41 @@ if (require.main === module) {
|
|
|
167
220
|
});
|
|
168
221
|
}
|
|
169
222
|
|
|
170
|
-
|
|
223
|
+
/**
|
|
224
|
+
* `build [--budget <brotli bytes>] [--input <css>] [--config <tailwind config>] [--full-config <tailwind config>]
|
|
225
|
+
* [-- <next build args>]`: `next build` with a stylesheet per route (`./route-styles.cjs`).
|
|
226
|
+
*/
|
|
227
|
+
async function buildCommand(argv) {
|
|
228
|
+
const root = process.cwd();
|
|
229
|
+
const split = argv.indexOf('--');
|
|
230
|
+
const args = parseArgs(split < 0 ? argv : argv.slice(0, split));
|
|
231
|
+
const nextArgs = split < 0 ? [] : argv.slice(split + 1);
|
|
232
|
+
const config =
|
|
233
|
+
args.config ??
|
|
234
|
+
firstExisting(
|
|
235
|
+
root,
|
|
236
|
+
['ts', 'js', 'cjs', 'mjs'].map(ext => `tailwind.config.${ext}`),
|
|
237
|
+
);
|
|
238
|
+
const input = args.input ?? firstExisting(root, ['src/app/globals.css', 'app/globals.css']);
|
|
239
|
+
if (!input || !config)
|
|
240
|
+
throw new Error('usage: next-styles build [--input <css>] [--config <tailwind config>] [-- <next build args>]');
|
|
241
|
+
const { buildWithRouteStyles, DEFAULT_BUDGET } = loadRouteStyles();
|
|
242
|
+
await buildWithRouteStyles({
|
|
243
|
+
root,
|
|
244
|
+
nextArgs,
|
|
245
|
+
input,
|
|
246
|
+
config,
|
|
247
|
+
fullConfig: args['full-config'] ?? config,
|
|
248
|
+
budget: args.budget ? Number(args.budget) : DEFAULT_BUDGET,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
module.exports = {
|
|
253
|
+
STYLES_DIR,
|
|
254
|
+
BUILD_INFO,
|
|
255
|
+
fullSheetUrl,
|
|
256
|
+
withInlineStyles,
|
|
257
|
+
withRouteStyles,
|
|
258
|
+
measureStylesheet,
|
|
259
|
+
resolveImports,
|
|
260
|
+
};
|
|
@@ -19,3 +19,11 @@ export function measureStylesheet(
|
|
|
19
19
|
|
|
20
20
|
/** The stylesheet at `input` with each `@import` resolved to an absolute path (packages through their `exports`). */
|
|
21
21
|
export function resolveImports(input: string, root: string): string;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* `withInlineStyles`, plus per-route stylesheets when the build runs as `next-styles build`: the server bundle
|
|
25
|
+
* carries `.next-styles/` and knows its build. Any other build and `next dev` get `withInlineStyles` alone.
|
|
26
|
+
*/
|
|
27
|
+
export function withRouteStyles<T extends object>(
|
|
28
|
+
nextConfig: T | ((...args: unknown[]) => T | Promise<T>),
|
|
29
|
+
): (phase: string, ...rest: unknown[]) => Promise<T & { experimental: { inlineCss: true } }>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
/**
|
|
3
|
+
* The client part of `RouteStyles` (`./route-styles-server.mjs`). In the server render it asks the resolver the
|
|
4
|
+
* server part put in the process for the rules of the page's path, and renders them. In the browser it renders the
|
|
5
|
+
* same `<style>` empty, under the same `href`: React finds the server's copy in the head by its `href` and keeps it,
|
|
6
|
+
* and after a client navigation the complete sheet holds every rule. The loader starts the complete sheet when the HTML reaches it,
|
|
7
|
+
* without blocking paint, and appends it after every other stylesheet so its rules are the last copy of each.
|
|
8
|
+
*
|
|
9
|
+
* A page the server did not render (Next answers a 404 with an empty error shell and draws it from its data in the
|
|
10
|
+
* browser) has neither the rules nor the loader: the effect then loads the complete sheet itself, from the address
|
|
11
|
+
* the build wrote into the bundle.
|
|
12
|
+
*/
|
|
13
|
+
import { usePathname } from 'next/navigation';
|
|
14
|
+
import { createElement, Fragment, useEffect } from 'react';
|
|
15
|
+
import markers from './route-styles-markers.cjs';
|
|
16
|
+
|
|
17
|
+
const REGISTRY = Symbol.for(markers.REGISTRY_KEY);
|
|
18
|
+
const FULL_URL = process.env.NEXT_STYLES_FULL_URL || '';
|
|
19
|
+
/** Appends the complete sheet named by its own `<script data-next-styles-full>` once, at low priority. */
|
|
20
|
+
const LOADER =
|
|
21
|
+
"(function(s){var h=s&&s.getAttribute('data-next-styles-full');" +
|
|
22
|
+
"if(!h||document.querySelector('link[data-next-styles-full]'))return;" +
|
|
23
|
+
"var l=document.createElement('link');l.rel='stylesheet';l.href=h;l.fetchPriority='low';" +
|
|
24
|
+
"l.setAttribute('data-next-styles-full','');document.head.appendChild(l)})(document.currentScript)";
|
|
25
|
+
|
|
26
|
+
/** The complete sheet, once, unless the server wrote this page's rules (its loader then started the sheet already). */
|
|
27
|
+
function loadCompleteSheet(build) {
|
|
28
|
+
if (!FULL_URL || document.querySelector('link[data-next-styles-full]')) return;
|
|
29
|
+
if (document.querySelector(`style[data-href="next-styles:${build}"]`)?.textContent) return;
|
|
30
|
+
const link = document.createElement('link');
|
|
31
|
+
link.rel = 'stylesheet';
|
|
32
|
+
link.href = FULL_URL;
|
|
33
|
+
link.setAttribute('data-next-styles-full', '');
|
|
34
|
+
document.head.appendChild(link);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function RouteStyle({ build, complete }) {
|
|
38
|
+
const pathname = usePathname();
|
|
39
|
+
useEffect(() => loadCompleteSheet(build), [build]);
|
|
40
|
+
let entry;
|
|
41
|
+
if (typeof window === 'undefined') {
|
|
42
|
+
const resolve = globalThis[REGISTRY]?.get(build);
|
|
43
|
+
if (!resolve) {
|
|
44
|
+
// The server part runs first in this process; without its resolver the page would have no utilities.
|
|
45
|
+
throw new Error('next-styles: RouteStyle rendered without RouteStyles in this process');
|
|
46
|
+
}
|
|
47
|
+
entry = resolve(pathname, complete);
|
|
48
|
+
}
|
|
49
|
+
return createElement(
|
|
50
|
+
Fragment,
|
|
51
|
+
null,
|
|
52
|
+
createElement(
|
|
53
|
+
'style',
|
|
54
|
+
// One href for every page of the build: the browser keeps the first page's copy, and a client
|
|
55
|
+
// navigation inserts no other (the complete sheet already holds every rule by then).
|
|
56
|
+
{ href: `next-styles:${build}`, precedence: 'next-styles' },
|
|
57
|
+
entry?.css ?? '',
|
|
58
|
+
),
|
|
59
|
+
// The complete sheet's address is the server's to state; the browser renders the script without it and
|
|
60
|
+
// keeps the server's attribute (the script already ran when the HTML reached it).
|
|
61
|
+
createElement('script', {
|
|
62
|
+
'data-next-styles-full': entry?.fullUrl ?? undefined,
|
|
63
|
+
suppressHydrationWarning: true,
|
|
64
|
+
dangerouslySetInnerHTML: { __html: LOADER },
|
|
65
|
+
}),
|
|
66
|
+
);
|
|
67
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The names `next-styles build` and `RouteStyles` agree on, stated once: the build writes them
|
|
3
|
+
* (`./route-styles.cjs`, `./next-styles.cjs`) and the server and client parts read them
|
|
4
|
+
* (`./route-styles-server.mjs`, `./route-styles-client.mjs`). A leaf with no imports, so the app's server and
|
|
5
|
+
* browser bundles can carry it without reaching the build tool.
|
|
6
|
+
*/
|
|
7
|
+
module.exports = {
|
|
8
|
+
/** Where `next-styles build` keeps the build's route sheets (the app's directory), and its files there. */
|
|
9
|
+
STYLES_DIR: '.next-styles',
|
|
10
|
+
BUILD_INFO: 'build.json',
|
|
11
|
+
MANIFEST: 'manifest.json',
|
|
12
|
+
/** What a prerendered page's route `<style>` holds until the build fills it with the route's rules. */
|
|
13
|
+
PLACEHOLDER: '/*next-styles:route*/',
|
|
14
|
+
/** What a page that carries the complete sheet (`RouteStyles complete`) holds until the build fills it. */
|
|
15
|
+
COMPLETE_PLACEHOLDER: '/*next-styles:complete*/',
|
|
16
|
+
/** The process-wide key the server part registers its resolver under for the client part's server render. */
|
|
17
|
+
REGISTRY_KEY: 'flamingo.next-styles',
|
|
18
|
+
};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page's stylesheet, for the root layout of an app built with `next-styles build` (`./route-styles.cjs`).
|
|
3
|
+
*
|
|
4
|
+
* import { RouteStyles } from '<package>/route-styles'
|
|
5
|
+
* <body><RouteStyles />…</body> // once, in the root layout
|
|
6
|
+
* <RouteStyles complete /> // pages that depend on who is signed in
|
|
7
|
+
*
|
|
8
|
+
* It writes the rules of the page's route into the HTML (a `<style precedence>`, which React puts in the head after
|
|
9
|
+
* the app's own stylesheets) and starts the complete sheet loading after paint. The route is the page's path
|
|
10
|
+
* (`usePathname` in the server render of the client part), matched against the routes the build sampled; a path no
|
|
11
|
+
* route matches gets the complete sheet. The rules reach the HTML only: the client part reads them from a resolver
|
|
12
|
+
* this module puts in the process, never from a prop, so they are not written again into the page's data (the RSC
|
|
13
|
+
* payload a client navigation reads). In `next dev`, and in a build not made by `next-styles build`, it renders
|
|
14
|
+
* nothing and the app's stylesheet holds every rule as before.
|
|
15
|
+
*/
|
|
16
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
17
|
+
import { join } from 'node:path';
|
|
18
|
+
import { createElement } from 'react';
|
|
19
|
+
import { RouteStyle } from './route-styles-client.mjs';
|
|
20
|
+
import markers from './route-styles-markers.cjs';
|
|
21
|
+
|
|
22
|
+
const { STYLES_DIR, MANIFEST, PLACEHOLDER, COMPLETE_PLACEHOLDER, REGISTRY_KEY } = markers;
|
|
23
|
+
const REGISTRY = Symbol.for(REGISTRY_KEY);
|
|
24
|
+
|
|
25
|
+
/** The build these rules belong to, and its complete sheet: written by `withRouteStyles` into the bundles. */
|
|
26
|
+
const BUILD = process.env.NEXT_STYLES_BUILD || '';
|
|
27
|
+
const FULL_URL = process.env.NEXT_STYLES_FULL_URL || '';
|
|
28
|
+
|
|
29
|
+
/** `/blog/[slug]` → a RegExp for its paths; `[...x]` takes one or more segments, `[[...x]]` none or more. */
|
|
30
|
+
function routePattern(route) {
|
|
31
|
+
let source = '';
|
|
32
|
+
let dynamic = 0;
|
|
33
|
+
for (const part of route.split('/').filter(Boolean)) {
|
|
34
|
+
if (/^\[\[\.\.\.[^\]]+\]\]$/.test(part)) {
|
|
35
|
+
source += '(?:/.+)?';
|
|
36
|
+
dynamic += 3;
|
|
37
|
+
} else if (/^\[\.\.\.[^\]]+\]$/.test(part)) {
|
|
38
|
+
source += '/.+';
|
|
39
|
+
dynamic += 2;
|
|
40
|
+
} else if (/^\[[^\]]+\]$/.test(part)) {
|
|
41
|
+
source += '/[^/]+';
|
|
42
|
+
dynamic += 1;
|
|
43
|
+
} else {
|
|
44
|
+
source += `/${part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return { route, dynamic, regex: new RegExp(`^${source || '/'}$`) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function normalize(pathname) {
|
|
51
|
+
const path = `/${String(pathname || '').replace(/^\/+/, '')}`.replace(/\/+$/, '');
|
|
52
|
+
return path === '' ? '/' : path;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The build's resolver, `(pathname, complete) → { css, fullUrl }`, read once per process. While the build
|
|
57
|
+
* prerenders, it answers placeholders for the rules, which the build fills in afterwards.
|
|
58
|
+
*/
|
|
59
|
+
function createResolver() {
|
|
60
|
+
// Read at run time from the server's own directory (traced in by `withRouteStyles`), never followed by the
|
|
61
|
+
// bundler's file tracing.
|
|
62
|
+
const dir = join(/* turbopackIgnore: true */ process.cwd(), STYLES_DIR);
|
|
63
|
+
const file = join(dir, MANIFEST);
|
|
64
|
+
if (!existsSync(file)) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
`next-styles: ${file} is missing: this server was built by next-styles build and needs its ${STYLES_DIR}`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const manifest = JSON.parse(readFileSync(file, 'utf8'));
|
|
70
|
+
if (manifest.pending) {
|
|
71
|
+
return (_pathname, complete) =>
|
|
72
|
+
complete ? { css: COMPLETE_PLACEHOLDER, fullUrl: null } : { css: PLACEHOLDER, fullUrl: FULL_URL };
|
|
73
|
+
}
|
|
74
|
+
if (manifest.buildId !== BUILD) {
|
|
75
|
+
throw new Error(`next-styles: ${file} belongs to build ${manifest.buildId}, this server to ${BUILD}`);
|
|
76
|
+
}
|
|
77
|
+
const patterns = Object.keys(manifest.routes)
|
|
78
|
+
.map(routePattern)
|
|
79
|
+
.sort((a, b) => a.dynamic - b.dynamic || b.route.length - a.route.length);
|
|
80
|
+
const sheets = new Map();
|
|
81
|
+
const sheet = name => {
|
|
82
|
+
if (!sheets.has(name)) sheets.set(name, readFileSync(join(dir, 'sheets', name), 'utf8'));
|
|
83
|
+
return sheets.get(name);
|
|
84
|
+
};
|
|
85
|
+
return (pathname, complete) => {
|
|
86
|
+
const path = normalize(pathname);
|
|
87
|
+
const match = complete ? undefined : patterns.find(pattern => pattern.regex.test(path));
|
|
88
|
+
if (!match) return { css: sheet(manifest.full), fullUrl: null };
|
|
89
|
+
return { css: sheet(manifest.routes[match.route].file), fullUrl: manifest.fullUrl };
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The page's rules: its route's sheet, or the complete sheet where no route matches its path or where `complete`
|
|
95
|
+
* says the page's markup depends on who is looking (a signed-in hub), so no one page can sample its route.
|
|
96
|
+
*/
|
|
97
|
+
export function RouteStyles({ complete = false } = {}) {
|
|
98
|
+
if (!BUILD) return null;
|
|
99
|
+
globalThis[REGISTRY] ??= new Map();
|
|
100
|
+
if (!globalThis[REGISTRY].has(BUILD)) globalThis[REGISTRY].set(BUILD, createResolver());
|
|
101
|
+
return createElement(RouteStyle, { build: BUILD, complete });
|
|
102
|
+
}
|
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-route stylesheets for a Next.js App Router app styled with Tailwind: each page carries only the rules
|
|
3
|
+
* for the classes it renders, and the app's complete sheet follows after paint.
|
|
4
|
+
*
|
|
5
|
+
* next-styles build [--budget 15360] [--full-config tailwind.full.config.ts] [-- <next build args>]
|
|
6
|
+
*
|
|
7
|
+
* WHY. A page cannot paint before its stylesheet, so the sheet is written into the HTML (`withInlineStyles`),
|
|
8
|
+
* and then every page pays for every rule of the app: on flamingo 287 KB raw (29 KB brotli) in every
|
|
9
|
+
* document, of which the home page uses a fifth. Cutting the sheet by what each route IMPORTS saved 10%
|
|
10
|
+
* (a site's layout reaches most of the design system); only what a page RENDERS gets a page to half.
|
|
11
|
+
* Measured on flamingo (CU-17tkuw61z4z): 11.4 to 12.6 KB brotli for the classes in each page's HTML.
|
|
12
|
+
*
|
|
13
|
+
* HOW. Three parts, one build:
|
|
14
|
+
* 1. `next build` runs with `NEXT_STYLES=routes`: the root sheet the app imports is built with no utilities
|
|
15
|
+
* (`withRouteStylesTailwind`, so it holds the tokens, preflight and the app's own rules), and the root
|
|
16
|
+
* layout's `RouteStyles` (`<package>/route-styles`) writes a placeholder where the route's rules go.
|
|
17
|
+
* 2. This step reads every page the build prerendered, takes the classes of its HTML (never its scripts: the
|
|
18
|
+
* page's data names classes a later state renders, which the complete sheet covers), and builds one sheet
|
|
19
|
+
* per route with the app's own Tailwind config, PostCSS plugins and stylesheet. It writes them where the
|
|
20
|
+
* server reads them (`.next-styles/`, traced into the server bundle) and fills each prerendered page's
|
|
21
|
+
* placeholder. A page rendered later (on its first request, or again after `revalidate`) reads its route's
|
|
22
|
+
* sheet when it renders.
|
|
23
|
+
* 3. The complete sheet, built the same way from the full config, is a static file the page loads after its
|
|
24
|
+
* first paint, for what the page renders later (a menu opened, a panel loaded, a page navigated to).
|
|
25
|
+
*
|
|
26
|
+
* ORDER. Tailwind v3 writes its rules in its own order whatever the content, so a route's sheet is the complete
|
|
27
|
+
* sheet with rules left out and the rules it keeps in the same order. The complete sheet is inserted last, so
|
|
28
|
+
* once it lands every rule's last copy is in it and the cascade is the complete sheet's. Before it lands, a
|
|
29
|
+
* page's own classes are all in its own sheet, in that order.
|
|
30
|
+
*
|
|
31
|
+
* A route with no prerendered page (one rendered per request) has no sample: its pages carry the complete
|
|
32
|
+
* sheet as before, and this step names them. Build a page of such a route ahead to give it its own sheet.
|
|
33
|
+
*/
|
|
34
|
+
const { spawn } = require('node:child_process');
|
|
35
|
+
const crypto = require('node:crypto');
|
|
36
|
+
const fs = require('node:fs');
|
|
37
|
+
const { join, relative, resolve } = require('node:path');
|
|
38
|
+
const { brotliCompressSync, constants } = require('node:zlib');
|
|
39
|
+
|
|
40
|
+
const { fullSheetUrl } = require('./next-styles.cjs');
|
|
41
|
+
const { STYLES_DIR, BUILD_INFO, MANIFEST, PLACEHOLDER, COMPLETE_PLACEHOLDER } = require('./route-styles-markers.cjs');
|
|
42
|
+
/** The mark the package's stylesheet carries before `@tailwind components`: the utilities start there. */
|
|
43
|
+
const UTILITIES_MARK = '/*! next-styles:utilities */';
|
|
44
|
+
const DEFAULT_BUDGET = 15 * 1024;
|
|
45
|
+
|
|
46
|
+
const kb = bytes => `${(bytes / 1024).toFixed(1)} KB`;
|
|
47
|
+
const brotli = css =>
|
|
48
|
+
brotliCompressSync(Buffer.from(css), { params: { [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY } })
|
|
49
|
+
.length;
|
|
50
|
+
const hash = text => crypto.createHash('sha256').update(text).digest('hex').slice(0, 16);
|
|
51
|
+
|
|
52
|
+
/** `text` with the HTML entities a class attribute can carry decoded (`[&_svg]:w-4` is written `[&_svg]`). */
|
|
53
|
+
function decodeEntities(text) {
|
|
54
|
+
return text.replace(/&(#x[0-9a-f]+|#\d+|amp|quot|apos|lt|gt);/gi, (entity, code) => {
|
|
55
|
+
const name = code.toLowerCase();
|
|
56
|
+
if (name === 'amp') return '&';
|
|
57
|
+
if (name === 'quot') return '"';
|
|
58
|
+
if (name === 'apos') return "'";
|
|
59
|
+
if (name === 'lt') return '<';
|
|
60
|
+
if (name === 'gt') return '>';
|
|
61
|
+
const point = name.startsWith('#x') ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
|
|
62
|
+
return Number.isFinite(point) ? String.fromCodePoint(point) : entity;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The class names a page's HTML renders: every `class` attribute outside `<script>`, `<style>` and comments.
|
|
68
|
+
* The page's data (the RSC payload, in scripts) is left out on purpose: what it names beyond the HTML renders
|
|
69
|
+
* after the page is interactive, when the complete sheet is there.
|
|
70
|
+
*/
|
|
71
|
+
function renderedClasses(html) {
|
|
72
|
+
const markup = html
|
|
73
|
+
.replace(/<script\b[\s\S]*?<\/script>/gi, '')
|
|
74
|
+
.replace(/<style\b[\s\S]*?<\/style>/gi, '')
|
|
75
|
+
.replace(/<!--[\s\S]*?-->/g, '');
|
|
76
|
+
const classes = new Set();
|
|
77
|
+
for (const match of markup.matchAll(/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) {
|
|
78
|
+
for (const name of decodeEntities(match[1] ?? match[2] ?? '').split(/\s+/)) if (name) classes.add(name);
|
|
79
|
+
}
|
|
80
|
+
return classes;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The stylesheet at `file` with its own `@config` dropped and each `@import` an absolute path (`next-styles`). */
|
|
84
|
+
function readInput(file, root) {
|
|
85
|
+
const { resolveImports } = require('./next-styles.cjs');
|
|
86
|
+
return resolveImports(file, root).replace(/^\s*@config\s+(['"])[^'"]+\1\s*;\s*$/gm, '');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The app's PostCSS plugins, its own Tailwind replaced by one built with `tailwindConfig` (an object). */
|
|
90
|
+
async function postcssPlugins(root, tailwindConfig) {
|
|
91
|
+
const loadPostcssConfig = require(require.resolve('postcss-load-config', { paths: [root, __dirname] }));
|
|
92
|
+
const tailwindcss = require(require.resolve('tailwindcss', { paths: [root, __dirname] }));
|
|
93
|
+
const postcssImport = require(require.resolve('postcss-import', { paths: [root, require.resolve('tailwindcss')] }));
|
|
94
|
+
const { plugins } = await loadPostcssConfig({ env: 'production' }, root);
|
|
95
|
+
const own = plugins.filter(plugin => (plugin.postcssPlugin ?? plugin().postcssPlugin) !== 'tailwindcss');
|
|
96
|
+
return [postcssImport(), tailwindcss(tailwindConfig), ...own];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The minifier the Tailwind CLI's `--minify` runs, so a measured sheet is measured as the budget gate measures. */
|
|
100
|
+
function minifier(root) {
|
|
101
|
+
const deps = require(require.resolve('tailwindcss/lib/cli/build/deps.js', { paths: [root, __dirname] }));
|
|
102
|
+
return deps.loadCssNano();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* A stylesheet builder for the app: `build(content)` is `input` built with `config` (its theme and plugins) and
|
|
107
|
+
* `content` in place of its own, minified, cut at the utilities mark. `content` is `null` for the config's own.
|
|
108
|
+
*/
|
|
109
|
+
async function stylesheetBuilder({ root, input, config }) {
|
|
110
|
+
const postcss = require(require.resolve('postcss', { paths: [root, __dirname] }));
|
|
111
|
+
const loadConfig = require(require.resolve('tailwindcss/loadConfig', { paths: [root, __dirname] }));
|
|
112
|
+
const source = readInput(resolve(root, input), root);
|
|
113
|
+
const appConfig = loadConfig(resolve(root, config));
|
|
114
|
+
const minify = minifier(root);
|
|
115
|
+
const from = resolve(root, input);
|
|
116
|
+
return async content => {
|
|
117
|
+
const tailwindConfig =
|
|
118
|
+
content === null ? appConfig : { ...appConfig, content: [{ raw: content, extension: 'html' }], safelist: [] };
|
|
119
|
+
const result = await postcss([...(await postcssPlugins(root, tailwindConfig)), minify]).process(source, { from });
|
|
120
|
+
const at = result.css.indexOf(UTILITIES_MARK);
|
|
121
|
+
if (at < 0) {
|
|
122
|
+
throw new Error(
|
|
123
|
+
`next-styles: ${input} has no "${UTILITIES_MARK}" mark: the design-system stylesheet it imports predates per-route sheets`,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
return result.css.slice(at + UTILITIES_MARK.length);
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Every file under `dir` whose name ends with `suffix`. */
|
|
131
|
+
function filesUnder(dir, suffix, out = []) {
|
|
132
|
+
if (!fs.existsSync(dir)) return out;
|
|
133
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
134
|
+
const path = join(dir, entry.name);
|
|
135
|
+
if (entry.isDirectory()) filesUnder(path, suffix, out);
|
|
136
|
+
else if (entry.name.endsWith(suffix)) out.push(path);
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The prerendered pages of the build, each with the route it belongs to: `{ file, route }`. A server build keeps
|
|
143
|
+
* them under `<distDir>/server/app` (and the standalone copy), a static export writes them into `distDir`.
|
|
144
|
+
* The route of a page is the prerender manifest's `srcRoute` (`/blog/[slug]` for `/blog/x`).
|
|
145
|
+
*/
|
|
146
|
+
function prerenderedPages(root, info) {
|
|
147
|
+
const distDir = resolve(root, info.distDir);
|
|
148
|
+
const manifestFile = join(distDir, 'prerender-manifest.json');
|
|
149
|
+
const routes = fs.existsSync(manifestFile) ? JSON.parse(fs.readFileSync(manifestFile, 'utf8')).routes : {};
|
|
150
|
+
const routeOf = new Map();
|
|
151
|
+
for (const [path, entry] of Object.entries(routes)) routeOf.set(path, entry.srcRoute ?? path);
|
|
152
|
+
const pathOfFile = (base, file) => {
|
|
153
|
+
const rel = relative(base, file)
|
|
154
|
+
.split('\\')
|
|
155
|
+
.join('/')
|
|
156
|
+
.replace(/\.html$/, '');
|
|
157
|
+
const path = `/${rel}`.replace(/\/index$/, '') || '/';
|
|
158
|
+
return path === '' ? '/' : path;
|
|
159
|
+
};
|
|
160
|
+
const bases = info.output === 'export' ? [distDir] : [join(distDir, 'server', 'app')];
|
|
161
|
+
const pages = [];
|
|
162
|
+
for (const base of bases) {
|
|
163
|
+
for (const file of filesUnder(base, '.html')) {
|
|
164
|
+
if (info.output === 'export' && relative(distDir, file).startsWith(`_next`)) continue;
|
|
165
|
+
const path = pathOfFile(base, file);
|
|
166
|
+
const route = routeOf.get(path) ?? routeOf.get(`${path}/`) ?? (path === '/' ? '/' : null);
|
|
167
|
+
// `global-error` renders its own document, never the root layout's sheet.
|
|
168
|
+
if (route && route !== '/_global-error') pages.push({ file, path, route });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return pages;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The standalone copies of a server build's files (`<distDir>/standalone/...`), found by the copy of `marker`. */
|
|
175
|
+
function standaloneCopies(root, info, marker) {
|
|
176
|
+
const standalone = resolve(root, info.distDir, 'standalone');
|
|
177
|
+
return filesUnder(standalone, marker).map(file => file.slice(0, -marker.length));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** `html` with its placeholders filled: the route's rules `css` and the complete sheet `full`. */
|
|
181
|
+
function fillPlaceholder(html, { css, full }) {
|
|
182
|
+
return html.split(PLACEHOLDER).join(css).split(COMPLETE_PLACEHOLDER).join(full);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A free TCP port on this machine. */
|
|
186
|
+
function freePort() {
|
|
187
|
+
const net = require('node:net');
|
|
188
|
+
return new Promise((resolvePort, reject) => {
|
|
189
|
+
const server = net.createServer();
|
|
190
|
+
server.unref();
|
|
191
|
+
server.on('error', reject);
|
|
192
|
+
server.listen(0, '127.0.0.1', () => {
|
|
193
|
+
const { port } = server.address();
|
|
194
|
+
server.close(() => resolvePort(port));
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The page routes of the build that no prerendered page samples and that have no dynamic segment: rendered per
|
|
201
|
+
* request (`/pricing` reads a live price), so the only sample is a request. Route handlers and `/api` are not
|
|
202
|
+
* pages; a route with a dynamic segment has no address to ask without a record.
|
|
203
|
+
*/
|
|
204
|
+
function unsampledStaticRoutes(root, info, sampled) {
|
|
205
|
+
const file = join(resolve(root, info.distDir), 'app-path-routes-manifest.json');
|
|
206
|
+
if (!fs.existsSync(file)) return [];
|
|
207
|
+
const routes = new Set();
|
|
208
|
+
for (const [entry, route] of Object.entries(JSON.parse(fs.readFileSync(file, 'utf8')))) {
|
|
209
|
+
if (!entry.endsWith('/page')) continue;
|
|
210
|
+
if (route.includes('[') || route === '/api' || route.startsWith('/api/') || route.startsWith('/_')) continue;
|
|
211
|
+
if (!sampled.has(route)) routes.add(route);
|
|
212
|
+
}
|
|
213
|
+
return [...routes].sort();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The HTML of `routes`, asked of the finished build served on this machine (`next start`): `{ route, html }` for
|
|
218
|
+
* each that answers 200 with a page. A route that answers anything else (not served here, a redirect, a refusal)
|
|
219
|
+
* keeps the complete sheet.
|
|
220
|
+
*/
|
|
221
|
+
async function crawlRoutes(root, routes, { concurrency = 4, timeoutMs = 60_000 } = {}) {
|
|
222
|
+
if (!routes.length) return [];
|
|
223
|
+
const port = await freePort();
|
|
224
|
+
const nextBin = require.resolve('next/dist/bin/next', { paths: [root] });
|
|
225
|
+
const server = spawn(process.execPath, [nextBin, 'start', '-p', String(port), '-H', '127.0.0.1'], {
|
|
226
|
+
cwd: root,
|
|
227
|
+
stdio: ['ignore', 'ignore', 'inherit'],
|
|
228
|
+
env: { ...process.env, NODE_ENV: 'production' },
|
|
229
|
+
});
|
|
230
|
+
const base = `http://127.0.0.1:${port}`;
|
|
231
|
+
try {
|
|
232
|
+
const ready = Date.now() + timeoutMs;
|
|
233
|
+
for (;;) {
|
|
234
|
+
if (server.exitCode !== null) throw new Error(`next-styles: next start exited ${server.exitCode}`);
|
|
235
|
+
const answered = await fetch(base, { redirect: 'manual' }).then(
|
|
236
|
+
() => true,
|
|
237
|
+
() => false,
|
|
238
|
+
);
|
|
239
|
+
if (answered) break;
|
|
240
|
+
if (Date.now() > ready) throw new Error('next-styles: next start did not answer');
|
|
241
|
+
await new Promise(done => setTimeout(done, 250));
|
|
242
|
+
}
|
|
243
|
+
const pages = [];
|
|
244
|
+
const queue = [...routes];
|
|
245
|
+
// An app whose pages carry the complete sheet (`RouteStyles complete`, a signed-in hub) reads no route sheet.
|
|
246
|
+
let everyPageComplete = false;
|
|
247
|
+
const worker = async () => {
|
|
248
|
+
for (let route = queue.shift(); route; route = queue.shift()) {
|
|
249
|
+
try {
|
|
250
|
+
const response = await fetch(`${base}${route}`, {
|
|
251
|
+
redirect: 'manual',
|
|
252
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
253
|
+
headers: { accept: 'text/html' },
|
|
254
|
+
});
|
|
255
|
+
const html = await response.text();
|
|
256
|
+
if (html.includes(COMPLETE_PLACEHOLDER) && !html.includes(PLACEHOLDER)) {
|
|
257
|
+
everyPageComplete = true;
|
|
258
|
+
queue.length = 0;
|
|
259
|
+
} else if (response.status === 200 && /<html[\s>]/i.test(html)) pages.push({ route, html });
|
|
260
|
+
} catch (error) {
|
|
261
|
+
console.warn(`[next-styles] ${route}: no sample (${error.message})`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
await Promise.all(Array.from({ length: concurrency }, worker));
|
|
266
|
+
return everyPageComplete ? [] : pages;
|
|
267
|
+
} finally {
|
|
268
|
+
server.kill('SIGTERM');
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The route sheets of a finished build: built, written, filled into the prerendered pages and checked against
|
|
274
|
+
* `budget` (brotli bytes per route). Resolves to the report; sets a failing exit code over the budget.
|
|
275
|
+
*/
|
|
276
|
+
async function writeRouteStyles({ root, input, config, fullConfig, budget = DEFAULT_BUDGET, crawl = true }) {
|
|
277
|
+
const stylesDir = join(root, STYLES_DIR);
|
|
278
|
+
const info = JSON.parse(fs.readFileSync(join(stylesDir, BUILD_INFO), 'utf8'));
|
|
279
|
+
const pages = prerenderedPages(root, info);
|
|
280
|
+
|
|
281
|
+
const classesByRoute = new Map();
|
|
282
|
+
const sample = (route, html) => {
|
|
283
|
+
const classes = classesByRoute.get(route) ?? new Set();
|
|
284
|
+
for (const name of renderedClasses(html)) classes.add(name);
|
|
285
|
+
classesByRoute.set(route, classes);
|
|
286
|
+
};
|
|
287
|
+
for (const page of pages) sample(page.route, fs.readFileSync(page.file, 'utf8'));
|
|
288
|
+
// A static export has no server; every other build is asked for the pages it renders per request.
|
|
289
|
+
const unsampled =
|
|
290
|
+
info.output === 'export' || !crawl ? [] : unsampledStaticRoutes(root, info, new Set(classesByRoute.keys()));
|
|
291
|
+
const crawled = await crawlRoutes(root, unsampled);
|
|
292
|
+
for (const page of crawled) sample(page.route, page.html);
|
|
293
|
+
|
|
294
|
+
const routeSheet = await stylesheetBuilder({ root, input, config });
|
|
295
|
+
const fullSheet = fullConfig === config ? routeSheet : await stylesheetBuilder({ root, input, config: fullConfig });
|
|
296
|
+
const full = await fullSheet(null);
|
|
297
|
+
const fullUrl = fullSheetUrl(info);
|
|
298
|
+
const fullFile = fullUrl.split('/').pop();
|
|
299
|
+
|
|
300
|
+
const routes = {};
|
|
301
|
+
const sheets = new Map();
|
|
302
|
+
for (const [route, classes] of [...classesByRoute].sort(([a], [b]) => a.localeCompare(b))) {
|
|
303
|
+
const css = await routeSheet([...classes].sort().join(' '));
|
|
304
|
+
const file = `route-${hash(css)}.css`;
|
|
305
|
+
sheets.set(file, css);
|
|
306
|
+
routes[route] = { file, raw: Buffer.byteLength(css), brotli: brotli(css), pages: 0 };
|
|
307
|
+
}
|
|
308
|
+
for (const page of [...pages, ...crawled]) routes[page.route].pages += 1;
|
|
309
|
+
|
|
310
|
+
// The server reads these (traced into its bundle by `withRouteStyles`); the complete sheet is also a static file.
|
|
311
|
+
const targets = [
|
|
312
|
+
stylesDir,
|
|
313
|
+
...standaloneCopies(root, info, join(STYLES_DIR, BUILD_INFO)).map(dir => join(dir, STYLES_DIR)),
|
|
314
|
+
];
|
|
315
|
+
for (const dir of targets) {
|
|
316
|
+
fs.mkdirSync(join(dir, 'sheets'), { recursive: true });
|
|
317
|
+
for (const [file, css] of sheets) fs.writeFileSync(join(dir, 'sheets', file), css);
|
|
318
|
+
fs.writeFileSync(join(dir, 'sheets', fullFile), full);
|
|
319
|
+
}
|
|
320
|
+
const staticDir =
|
|
321
|
+
info.output === 'export'
|
|
322
|
+
? join(resolve(root, info.distDir), '_next', 'static')
|
|
323
|
+
: join(resolve(root, info.distDir), 'static');
|
|
324
|
+
fs.mkdirSync(join(staticDir, 'next-styles'), { recursive: true });
|
|
325
|
+
fs.writeFileSync(join(staticDir, 'next-styles', fullFile), full);
|
|
326
|
+
const manifest = { version: 1, buildId: info.buildId, full: fullFile, fullUrl, routes };
|
|
327
|
+
for (const dir of targets) fs.writeFileSync(join(dir, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
328
|
+
|
|
329
|
+
// Fill every prerendered page, the standalone copies included (the server answers those directly).
|
|
330
|
+
const copies = standaloneCopies(root, info, join(STYLES_DIR, BUILD_INFO)).map(dir =>
|
|
331
|
+
join(dir, relative(root, resolve(root, info.distDir)), 'server', 'app'),
|
|
332
|
+
);
|
|
333
|
+
for (const page of pages) {
|
|
334
|
+
const css = sheets.get(routes[page.route].file);
|
|
335
|
+
const files = [
|
|
336
|
+
page.file,
|
|
337
|
+
...copies.map(dir => join(dir, relative(join(resolve(root, info.distDir), 'server', 'app'), page.file))),
|
|
338
|
+
];
|
|
339
|
+
for (const file of files) {
|
|
340
|
+
if (!fs.existsSync(file)) continue;
|
|
341
|
+
const html = fs.readFileSync(file, 'utf8');
|
|
342
|
+
if (html.includes(PLACEHOLDER) || html.includes(COMPLETE_PLACEHOLDER)) {
|
|
343
|
+
fs.writeFileSync(file, fillPlaceholder(html, { css, full }));
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const missed = unsampled.filter(route => !routes[route]);
|
|
349
|
+
if (missed.length)
|
|
350
|
+
console.log(
|
|
351
|
+
`[next-styles] complete sheet for ${missed.length} route(s) that answered no page: ${missed.join(', ')}`,
|
|
352
|
+
);
|
|
353
|
+
const over = Object.entries(routes).filter(([, sheet]) => sheet.brotli > budget);
|
|
354
|
+
console.log(
|
|
355
|
+
`[next-styles] complete sheet ${kb(Buffer.byteLength(full))} raw, ${kb(brotli(full))} brotli (after paint)`,
|
|
356
|
+
);
|
|
357
|
+
for (const [route, sheet] of Object.entries(routes)) {
|
|
358
|
+
console.log(
|
|
359
|
+
`[next-styles] ${sheet.brotli > budget ? 'OVER' : 'ok '} ${kb(sheet.brotli).padStart(8)} brotli ${route} (${sheet.pages} page${sheet.pages === 1 ? '' : 's'})`,
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
if (over.length) {
|
|
363
|
+
console.error(
|
|
364
|
+
`[next-styles] FAIL: ${over.length} route sheet(s) over ${kb(budget)} brotli. A route's sheet is what its page renders ` +
|
|
365
|
+
'before it is interactive: render less on the first screen (load the rest when it opens), or raise the budget with the reason.',
|
|
366
|
+
);
|
|
367
|
+
process.exitCode = 1;
|
|
368
|
+
}
|
|
369
|
+
return manifest;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Runs `command args` in `root` with `env` added, resolving on exit 0. */
|
|
373
|
+
function run(command, args, { root, env }) {
|
|
374
|
+
return new Promise((resolvePromise, reject) => {
|
|
375
|
+
const child = spawn(command, args, { cwd: root, stdio: 'inherit', env: { ...process.env, ...env } });
|
|
376
|
+
child.on('error', reject);
|
|
377
|
+
child.on('exit', code =>
|
|
378
|
+
code === 0 ? resolvePromise() : reject(new Error(`${command} ${args.join(' ')} exited ${code}`)),
|
|
379
|
+
);
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* `next build` with per-route sheets: prepares `.next-styles/`, runs the build with `NEXT_STYLES=routes`, then
|
|
385
|
+
* writes the route sheets. `nextArgs` are passed to `next build`.
|
|
386
|
+
*/
|
|
387
|
+
async function buildWithRouteStyles({ root, nextArgs = [], ...options }) {
|
|
388
|
+
const stylesDir = join(root, STYLES_DIR);
|
|
389
|
+
fs.rmSync(stylesDir, { recursive: true, force: true });
|
|
390
|
+
fs.mkdirSync(join(stylesDir, 'sheets'), { recursive: true });
|
|
391
|
+
// The server bundle traces these files when it is built, so they exist before it is (filled after it).
|
|
392
|
+
fs.writeFileSync(join(stylesDir, MANIFEST), `${JSON.stringify({ version: 1, pending: true })}\n`);
|
|
393
|
+
const nextBin = require.resolve('next/dist/bin/next', { paths: [root] });
|
|
394
|
+
await run(process.execPath, [nextBin, 'build', ...nextArgs], { root, env: { NEXT_STYLES: 'routes' } });
|
|
395
|
+
if (!fs.existsSync(join(stylesDir, BUILD_INFO))) {
|
|
396
|
+
throw new Error('next-styles: the build did not record its settings: wrap next.config with withRouteStyles');
|
|
397
|
+
}
|
|
398
|
+
return writeRouteStyles({ root, ...options });
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
module.exports = {
|
|
402
|
+
STYLES_DIR,
|
|
403
|
+
MANIFEST,
|
|
404
|
+
BUILD_INFO,
|
|
405
|
+
UTILITIES_MARK,
|
|
406
|
+
PLACEHOLDER,
|
|
407
|
+
COMPLETE_PLACEHOLDER,
|
|
408
|
+
DEFAULT_BUDGET,
|
|
409
|
+
renderedClasses,
|
|
410
|
+
stylesheetBuilder,
|
|
411
|
+
prerenderedPages,
|
|
412
|
+
crawlRoutes,
|
|
413
|
+
writeRouteStyles,
|
|
414
|
+
buildWithRouteStyles,
|
|
415
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ReactElement } from 'react';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The page's own stylesheet in its HTML, and the complete sheet loading after paint, for an app built with
|
|
5
|
+
* `next-styles build`. Render it once, in the root layout's body. Renders nothing in `next dev` and in any other
|
|
6
|
+
* build.
|
|
7
|
+
*/
|
|
8
|
+
export function RouteStyles(props?: {
|
|
9
|
+
/** The page's markup depends on the visitor (a signed-in hub): carry the complete sheet. */
|
|
10
|
+
complete?: boolean;
|
|
11
|
+
}): ReactElement | null;
|
|
@@ -259,4 +259,17 @@ if (require.main === module) {
|
|
|
259
259
|
);
|
|
260
260
|
}
|
|
261
261
|
|
|
262
|
-
|
|
262
|
+
/**
|
|
263
|
+
* The Tailwind config of the stylesheet the root layout imports, for `next-styles build`: under it that sheet is
|
|
264
|
+
* built with no utilities (its tokens, preflight and the app's own rules), because each route's utilities arrive
|
|
265
|
+
* in a sheet of their own. Anywhere else (`next dev`, any other build, the route step itself) it is `config`.
|
|
266
|
+
*
|
|
267
|
+
* It lives here, beside `appStyleSources`, because Turbopack traces what a Tailwind config imports: imported from
|
|
268
|
+
* `next-styles` it pulled esbuild's package into the trace and failed the build.
|
|
269
|
+
*/
|
|
270
|
+
function withRouteStylesTailwind(config) {
|
|
271
|
+
if (process.env.NEXT_STYLES !== 'routes') return config;
|
|
272
|
+
return { ...config, content: [{ raw: '', extension: 'html' }], safelist: [] };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
module.exports = { appStyleSources, routePaths, servedRouteFiles, LAZY_STYLED, withRouteStylesTailwind };
|
|
@@ -10,3 +10,6 @@ export interface AppStyleSourcesOptions {
|
|
|
10
10
|
|
|
11
11
|
/** The files a Next.js app's served routes import, for Tailwind's `content`. */
|
|
12
12
|
export function appStyleSources(options: AppStyleSourcesOptions): string[];
|
|
13
|
+
|
|
14
|
+
/** The root sheet's Tailwind config: no utilities under `next-styles build` (each route brings its own). */
|
|
15
|
+
export function withRouteStylesTailwind<T extends object>(config: T): T;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flamingo-stack/openframe-frontend-core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.832",
|
|
4
4
|
"description": "Shared design system and components for all Flamingo platforms",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|
|
@@ -43,6 +43,11 @@
|
|
|
43
43
|
"require": "./dist/build/next-styles.cjs",
|
|
44
44
|
"default": "./dist/build/next-styles.cjs"
|
|
45
45
|
},
|
|
46
|
+
"./route-styles": {
|
|
47
|
+
"types": "./dist/build/route-styles.d.ts",
|
|
48
|
+
"import": "./dist/build/route-styles-server.mjs",
|
|
49
|
+
"default": "./dist/build/route-styles-server.mjs"
|
|
50
|
+
},
|
|
46
51
|
"./dist/*.js": {
|
|
47
52
|
"import": "./dist/*.js",
|
|
48
53
|
"default": "./dist/*.js"
|
package/src/styles/index.css
CHANGED