@flamingo-stack/openframe-frontend-core 0.0.831 → 0.0.833

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 (62) hide show
  1. package/dist/build/next-styles.cjs +93 -3
  2. package/dist/build/next-styles.d.ts +8 -0
  3. package/dist/build/route-styles-client.mjs +67 -0
  4. package/dist/build/route-styles-markers.cjs +18 -0
  5. package/dist/build/route-styles-server.mjs +102 -0
  6. package/dist/build/route-styles.cjs +415 -0
  7. package/dist/build/route-styles.d.ts +11 -0
  8. package/dist/build/style-sources.cjs +14 -1
  9. package/dist/build/style-sources.d.ts +3 -0
  10. package/dist/{chunk-DAQMCWCK.cjs → chunk-4OP2VVPV.cjs} +3 -3
  11. package/dist/{chunk-HDLY6OMQ.cjs → chunk-AZRDKZNG.cjs} +4 -4
  12. package/dist/{chunk-CP46CVUC.cjs → chunk-DAOVWHCN.cjs} +42 -42
  13. package/dist/{chunk-ZJ5K6XHW.cjs → chunk-DQ6JYOHD.cjs} +3 -3
  14. package/dist/{chunk-VBGBKRDO.cjs → chunk-EQB3NSY6.cjs} +76 -76
  15. package/dist/{chunk-QHBKZJ6A.cjs → chunk-HBFYEBXN.cjs} +2 -2
  16. package/dist/{chunk-SRHHLDBP.cjs → chunk-I7QIIZAI.cjs} +10 -10
  17. package/dist/{chunk-P5DWAVWK.cjs → chunk-IUHV55D7.cjs} +5 -5
  18. package/dist/{chunk-EYSIQORA.cjs → chunk-LQDPAMXK.cjs} +1 -1
  19. package/dist/{chunk-7WQD3R5J.cjs → chunk-M5PGFNJG.cjs} +41 -41
  20. package/dist/{chunk-UGM3YDCK.cjs → chunk-SFJXIHFR.cjs} +9 -9
  21. package/dist/{chunk-X7VQM5TU.cjs → chunk-UFF4TRZH.cjs} +3 -3
  22. package/dist/{chunk-7COZUANC.cjs → chunk-UQ52NWTB.cjs} +32 -32
  23. package/dist/{chunk-OGPAVRNF.cjs → chunk-VMFBLMP6.cjs} +2 -2
  24. package/dist/{chunk-X76TZ5YR.cjs → chunk-WAMDWVYC.cjs} +11 -11
  25. package/dist/{chunk-R6QZHOJB.cjs → chunk-XXHCM2XS.cjs} +32 -32
  26. package/dist/{cloud-tenants-E2AC4WEJ.cjs → cloud-tenants-THCHEWBM.cjs} +3 -3
  27. package/dist/components/case-studies/index.cjs +12 -12
  28. package/dist/components/chat/embeddable-chat.d.ts +2 -2
  29. package/dist/components/chat/embeddable-chat.js +2 -14
  30. package/dist/components/chat/guide-welcome.d.ts +2 -2
  31. package/dist/components/chat/guide-welcome.d.ts.map +1 -1
  32. package/dist/components/chat/index.cjs +2 -2
  33. package/dist/components/chat/mingo-quick-action-wall.d.ts +1 -2
  34. package/dist/components/chat/mingo-quick-action-wall.d.ts.map +1 -1
  35. package/dist/components/chat/mingo-welcome.d.ts +1 -1
  36. package/dist/components/contact/index.cjs +4 -4
  37. package/dist/components/docs/index.cjs +6 -6
  38. package/dist/components/embeds/index.cjs +4 -4
  39. package/dist/components/faq/index.cjs +5 -5
  40. package/dist/components/features/index.cjs +3 -3
  41. package/dist/components/help-center-pages/index.cjs +55 -55
  42. package/dist/components/index.cjs +32 -32
  43. package/dist/components/meeting-scheduler/index.cjs +26 -26
  44. package/dist/components/navigation/index.cjs +6 -6
  45. package/dist/components/onboarding-guides/index.cjs +4 -4
  46. package/dist/components/product-demo/index.cjs +12 -12
  47. package/dist/components/tickets/index.cjs +8 -8
  48. package/dist/components/ui/index.cjs +3 -3
  49. package/dist/{devices-CAYUGD2N.cjs → devices-MPRDMXXU.cjs} +4 -4
  50. package/dist/{embeddable-chat-FYHMR66R.cjs → embeddable-chat-TRGESG7U.cjs} +2 -14
  51. package/dist/index.cjs +7 -7
  52. package/dist/{knowledge-OI4OPEVL.cjs → knowledge-TFTDHYGR.cjs} +3 -3
  53. package/dist/{logs-B3XV2NHV.cjs → logs-CSSJG4F7.cjs} +10 -10
  54. package/dist/{policies-ZB4Z42DV.cjs → policies-ELFYUN5P.cjs} +7 -7
  55. package/dist/{scripts-I4DNUOQC.cjs → scripts-37L6FIKG.cjs} +8 -8
  56. package/dist/{software-update-AWH4WXOH.cjs → software-update-BSA4NLHO.cjs} +6 -6
  57. package/package.json +6 -1
  58. package/src/components/chat/embeddable-chat.tsx +7 -21
  59. package/src/components/chat/guide-welcome.tsx +2 -2
  60. package/src/components/chat/mingo-quick-action-wall.tsx +1 -2
  61. package/src/components/chat/mingo-welcome.tsx +1 -1
  62. package/src/styles/index.css +2 -0
@@ -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 `[&amp;_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
- module.exports = { appStyleSources, routePaths, servedRouteFiles, LAZY_STYLED };
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;
@@ -5,12 +5,12 @@ var _chunkFDZOE5TLcjs = require('./chunk-FDZOE5TL.cjs');
5
5
 
6
6
 
7
7
 
8
- var _chunkVBGBKRDOcjs = require('./chunk-VBGBKRDO.cjs');
8
+ var _chunkEQB3NSY6cjs = require('./chunk-EQB3NSY6.cjs');
9
9
 
10
10
  // src/components/product-demo/screens/devices-view.tsx
11
11
  var _jsxruntime = require('react/jsx-runtime');
12
12
  var DEVICES_SEARCH_QUERY = "Windows";
13
- var TOOLBAR = { ..._chunkVBGBKRDOcjs.IDLE_DEVICES_TOOLBAR, searchValue: DEVICES_SEARCH_QUERY };
13
+ var TOOLBAR = { ..._chunkEQB3NSY6cjs.IDLE_DEVICES_TOOLBAR, searchValue: DEVICES_SEARCH_QUERY };
14
14
  var NO_HEADER = /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, {});
15
15
  var HIDDEN_WHEN_COMPACT = ["organization"];
16
16
  var NO_DEVICES = [];
@@ -22,7 +22,7 @@ function DevicesScreenView({
22
22
  loading = false
23
23
  }) {
24
24
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "h-full bg-ods-bg", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
25
- _chunkVBGBKRDOcjs.DevicesPanelView,
25
+ _chunkEQB3NSY6cjs.DevicesPanelView,
26
26
  {
27
27
  className: "p-[var(--spacing-system-l)]",
28
28
  headerSlot: NO_HEADER,
@@ -1,10 +1,10 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }"use client";
2
2
 
3
3
 
4
- var _chunkZJ5K6XHWcjs = require('./chunk-ZJ5K6XHW.cjs');
4
+ var _chunkDQ6JYOHDcjs = require('./chunk-DQ6JYOHD.cjs');
5
5
 
6
6
 
7
- var _chunkVBGBKRDOcjs = require('./chunk-VBGBKRDO.cjs');
7
+ var _chunkEQB3NSY6cjs = require('./chunk-EQB3NSY6.cjs');
8
8
 
9
9
 
10
10
  var _chunkFNNDGOR3cjs = require('./chunk-FNNDGOR3.cjs');
@@ -36,7 +36,7 @@ function FaqDocumentPage({
36
36
  onClick: () => router.push(_nullishCoalesce(_optionalChain([backButton, 'optionalAccess', _2 => _2.href]), () => ( "/")))
37
37
  };
38
38
  const inner = /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkFNNDGOR3cjs.PageLayout, { title, subtitle, backButton: backCfg, titleSize: "h1", titleWrap: true, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
39
- _chunkZJ5K6XHWcjs.FaqSection,
39
+ _chunkDQ6JYOHDcjs.FaqSection,
40
40
  {
41
41
  initialFaqs,
42
42
  heading: null,
@@ -51,7 +51,7 @@ function FaqDocumentPage({
51
51
  skeletonNav
52
52
  }
53
53
  ) });
54
- return shell ? /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkVBGBKRDOcjs.PageShell, { children: inner }) : /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "page-shell-content", children: inner });
54
+ return shell ? /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkEQB3NSY6cjs.PageShell, { children: inner }) : /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "page-shell-content", children: inner });
55
55
  }
56
56
 
57
57