Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions openframe-frontend-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,35 @@ Extend the shared Tailwind config in your project:

```ts
import designSystemConfig from '@flamingo-stack/openframe-frontend-core/tailwind.config.ts'
import { appStyleSources } from '@flamingo-stack/openframe-frontend-core/style-sources'

export default {
...designSystemConfig,
content: [
'./src/**/*.{js,ts,jsx,tsx}',
'./node_modules/@flamingo-stack/openframe-frontend-core/src/**/*.{js,ts,jsx,tsx}'
]
presets: [designSystemConfig],
// The files your App Router routes import, yours and this library's: never this library's whole
// `dist` or `src`, which puts every component's classes in the stylesheet every page blocks on.
content: appStyleSources({ root: __dirname, appDir: 'src/app' }),
}
```

`appStyleSources` (`scripts/style-sources.cjs`) walks the import graph from the route files, tree-shaken
as your bundler does. A host can leave the lazily loaded chat out of the page's stylesheet with
`firstPaint: true`, and give `EmbeddableChat` a `loadStyles` that loads a full stylesheet built
without it (see the file's header).

Then send the stylesheet inside each page's HTML, so a page never waits on a second request to paint,
and hold its size to a budget in your checks (`scripts/next-styles.cjs` says why and what it costs):

```js
// next.config.mjs
import { withInlineStyles } from '@flamingo-stack/openframe-frontend-core/next-styles'
export default withInlineStyles(nextConfig)
```

```bash
node node_modules/@flamingo-stack/openframe-frontend-core/dist/build/next-styles.cjs budget \
--input src/app/globals.css --config tailwind.config.ts --budget 31500
```

## Package Exports

| Export Path | Description |
Expand All @@ -67,6 +86,8 @@ export default {
| `./utils` | Utilities (cn, formatDate, formatPrice, getPlatformUrl, platform-config) |
| `./types` | TypeScript type definitions |
| `./styles` | CSS styles and ODS design tokens |
| `./style-sources` | Tailwind `content` for an app: the files its routes import (`appStyleSources`) |
| `./next-styles` | The stylesheet inside each page's HTML (`withInlineStyles`) and its size gate (`measureStylesheet`, `budget` command) |
| `./nats` | NATS WebSocket utilities |
| `./fonts` | Font configuration |

Expand Down
14 changes: 13 additions & 1 deletion openframe-frontend-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,18 @@
"require": "./dist/build/optimize-imports-loader.cjs",
"default": "./dist/build/optimize-imports-loader.cjs"
},
"./style-sources": {
"types": "./dist/build/style-sources.d.ts",
"import": "./dist/build/style-sources.cjs",
"require": "./dist/build/style-sources.cjs",
"default": "./dist/build/style-sources.cjs"
},
"./next-styles": {
"types": "./dist/build/next-styles.d.ts",
"import": "./dist/build/next-styles.cjs",
"require": "./dist/build/next-styles.cjs",
"default": "./dist/build/next-styles.cjs"
},
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
"./dist/*.js": {
"import": "./dist/*.js",
"default": "./dist/*.js"
Expand Down Expand Up @@ -478,6 +490,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.0.4",
"date-fns": "^3.6.0",
"esbuild": "^0.28.2",

Check notice on line 493 in openframe-frontend-core/package.json

View workflow job for this annotation

GitHub Actions / Flamingo Code Review

esbuild moved from devDependencies to dependencies but is only used by a build-time script

esbuild moved from devDependencies to dependencies but is only used by a build-time script The diff moves `esbuild` out of `devDependencies` into `dependencies` (package.json). `esbuild` is only required by `scripts/style-sources.cjs`, which runs at the HOST APP's build/config-evaluation time (inside `appStyleSources`), not at runtime of any shipped component. Making it a regular `dependencies` entry means every consumer that installs `@flamingo-stack/openframe-frontend-core` for its React components/hooks now also pulls in esbuild (a sizeable native-binary package) even if they never call `appStyleSources`. The more conventional fix is to keep it as a `peerDependency` (optional) or document it as required only by that specific script, rather than as an unconditional transitive dependency of the whole package. **What it risks:** Every consumer's install picks up esbuild and its native binaries unconditionally, inflating install size and surface for supply-chain issues, even for consumers that only use UI components and never touch `style-sources`. **How to fix:** Move `esbuild` to a peerDependency (with `peerDependenciesMeta.esbuild.optional = true`) or keep it a devDependency and instruct hosts that use `style-sources`/`next-styles` to install esbuild themselves, since it is only required by that opt-in script.
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
"eslint-config-next": "^16.3.0",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^3.10.1",
Expand Down Expand Up @@ -540,7 +553,6 @@
"@types/node": "^24.10.4",
"@vitest/ui": "^4.0.16",
"autoprefixer": "^10.4.23",
"esbuild": "^0.28.2",
"eslint": "^9.39.0",
"husky": "9.1.7",
"jsdom": "^27.4.0",
Expand Down
4 changes: 4 additions & 0 deletions openframe-frontend-core/scripts/build-export-map.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ function main() {
mkdirSync(OUT_DIR, { recursive: true });
writeFileSync(join(OUT_DIR, 'export-map.json'), `${JSON.stringify({ package: pkg.name, entries })}\n`);
copyFileSync(join(ROOT, 'scripts', 'optimize-imports-loader.cjs'), join(OUT_DIR, 'optimize-imports-loader.cjs'));
copyFileSync(join(ROOT, 'scripts', 'style-sources.cjs'), join(OUT_DIR, 'style-sources.cjs'));
copyFileSync(join(ROOT, 'scripts', 'style-sources.d.ts'), join(OUT_DIR, 'style-sources.d.ts'));
copyFileSync(join(ROOT, 'scripts', 'next-styles.cjs'), join(OUT_DIR, 'next-styles.cjs'));
copyFileSync(join(ROOT, 'scripts', 'next-styles.d.ts'), join(OUT_DIR, 'next-styles.d.ts'));
console.log(`Export map: ${names} names over ${Object.keys(entries).length} entries`);
}

Expand Down
160 changes: 160 additions & 0 deletions openframe-frontend-core/scripts/next-styles.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/**
* How a Next.js app that uses this library ships its stylesheet: inside the page, and measured.
*
* const { withInlineStyles } = require('<package>/next-styles')
* export default withInlineStyles(nextConfig) // next.config
*
* node node_modules/<package>/dist/build/next-styles.cjs budget \
* --input src/app/globals.css --config tailwind.config.ts --budget 31500 // the build gate
*
* WHY. A page cannot paint before its stylesheet arrives, and a stylesheet in a file of its own is
* requested only once the HTML names it: one more round trip after the HTML, whatever the file weighs.
* Measured on flamingo.run (CU-17tkuw617h7, Lighthouse mobile, slow 4G): the 44 KB sheet took 856 ms
* from request to last byte, a 1 KB sheet beside it 570 ms, and the page painted 65 ms after the large
* one landed. Cutting the sheet by a quarter moved LCP by nothing measurable; sending the sheet inside
* the HTML moved the home page's LCP from 1.50 s to 0.93 s and a blog post's from 1.60 s to 0.95 s.
*
* WHAT. `withInlineStyles` turns on Next's `experimental.inlineCss`: every stylesheet a route links is
* written into its HTML as a `<style>` tag instead (production builds, `output: 'export'` included;
* `next dev` keeps its links). The price is paid in the HTML: the sheet arrives with every page and is
* not cached apart from it, and Next sends it twice on a first load (the tag and the page's data).
* That is a good trade only while the sheet is small, so it comes with its gate: `measureStylesheet`
* builds the app's stylesheet the way its build does (Tailwind, minified) and reports its size
* brotli-compressed, as a CDN serves it, and the `budget` command fails past a stated size. Keep the
* sheet small with `appStyleSources` (`./style-sources`): Tailwind content from what the routes import.
*
* Per page: a sheet cut per route from the import graph was measured too, and saved 10% (26.4 KB
* against 29.3 KB brotli on flamingo): a site's shared layout reaches most of the design system, so a
* page's sheet is mostly its layout's. Inlining removes the wait; a smaller sheet only makes it cheap.
*/
const { execFile } = require('node:child_process');
const { mkdtempSync, readFileSync, rmSync, writeFileSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { basename, dirname, isAbsolute, join, resolve } = require('node:path');
const { promisify } = require('node:util');
const { brotliCompressSync, constants } = require('node:zlib');

/** `nextConfig` with every route's stylesheets written into its HTML. Composes with a config function. */
function withInlineStyles(nextConfig) {
const apply = config => ({ ...config, experimental: { ...config.experimental, inlineCss: true } });
if (typeof nextConfig === 'function') {
return async (...args) => apply(await nextConfig(...args));
}
return apply(nextConfig);
}

/**
* The stylesheet `input` with each `@import` made an absolute path: the Tailwind CLI resolves an import
* by path only, never through a package's `exports` (`@import '<package>/styles'`), which a bundler does.
*/
function resolveImports(input, root) {
const from = dirname(input);
return readFileSync(input, 'utf8').replace(/@import\s+(['"])([^'"]+)\1\s*;/g, (statement, _quote, specifier) => {
if (/^(https?:)?\/\//.test(specifier)) return statement;
const file =
specifier.startsWith('.') || isAbsolute(specifier)
? resolve(from, specifier)
: require.resolve(specifier, { paths: [root, from] });
return `@import "${file}";`;
});
}
Comment thread
michaelassraf marked this conversation as resolved.
Resolved

/**
* Builds `input` with Tailwind and `config` the way the app's build does, minified, and measures it.
*
* root the app's directory (absolute); `input` and `config` are relative to it.
* input the stylesheet the root layout imports ('src/app/globals.css').
* config the Tailwind config that builds it ('tailwind.config.ts').
* env variables the config reads (an app that builds one site per `NEXT_PUBLIC_APP_TYPE`).
*
* Resolves to `{ css, raw, brotli }`: the minified stylesheet, its bytes, and its bytes brotli-compressed
* at the quality a CDN serves static files with.
*/
async function measureStylesheet({ root, input, config, env = {} }) {
if (!isAbsolute(root)) throw new Error('measureStylesheet: root must be an absolute path');
const file = resolve(root, input);
const dir = mkdtempSync(join(tmpdir(), 'next-styles-'));
// The resolved copy sits BESIDE the input, so what it names relative to its own folder still resolves:
// an `@config '../tailwind.full.config.ts'` (Tailwind refuses an absolute one) and a relative `url()`.
const source = join(dirname(file), `.${basename(file)}.${process.pid}-${basename(dir)}.measure.css`);

Check notice on line 79 in openframe-frontend-core/scripts/next-styles.cjs

View workflow job for this annotation

GitHub Actions / Flamingo Code Review

measure-file name collision risk between concurrent calls on the same input and same PID

measure-file name collision risk between concurrent calls on the same input and same PID The temp source filename is derived from `process.pid` and the temp directory's basename (`basename(dir)`), e.g. `.full.css.1234-next-styles-abcde.measure.css`. Since `mkdtempSync` guarantees `dir` is unique even for concurrent calls in the same process, this is actually fine for concurrency within one process. However, if `measureStylesheet` is invoked twice concurrently for the SAME `input` file from the SAME process (e.g. a caller that runs `budget` for several pages in parallel via `Promise.all`), each call does get a distinct temp-dir basename so the filenames differ — but the file is written into the app's own source directory (`dirname(file)`), not a temp directory. This means every build run leaves a window where a dotfile is visible inside the app's `src/app` directory, which can be picked up by a concurrently running dev server/file watcher or linter scanning that directory, or by git status. The comment in the diff only explains the relative-resolution rationale, not this side effect. **What it risks:** A file watcher, bundler dev-mode rebuild, or lint-staged run triggered during the measurement window may see and process the transient dotfile inside the real source tree, causing spurious rebuilds, lint errors, or stale cache entries; this did not happen before because the temp file lived entirely under the OS temp directory. **How to fix:** Document or mitigate the fact that the resolved copy is now written inside the app's tracked source directory instead of an isolated temp directory, e.g. by ensuring the filename is excluded from watch/lint globs, or by confirming this is an accepted tradeoff.
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
try {
const output = join(dir, 'output.css');
writeFileSync(source, resolveImports(file, root));
// The app's own Tailwind, the one its build runs; this package's where the app has none of its own.
const cli = require.resolve('tailwindcss/lib/cli.js', { paths: [root, __dirname] });
await promisify(execFile)(
process.execPath,
[cli, '-c', resolve(root, config), '-i', source, '-o', output, '--minify'],
{
cwd: root,
env: { ...process.env, ...env },
maxBuffer: 64 * 1024 * 1024,
},
);
const css = readFileSync(output, 'utf8');
const brotli = brotliCompressSync(Buffer.from(css), {
params: { [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY },
}).length;
return { css, raw: Buffer.byteLength(css), brotli };
} finally {
rmSync(source, { force: true });
rmSync(dir, { recursive: true, force: true });
}
}

const kb = bytes => `${(bytes / 1024).toFixed(1)} KB`;

/** `--name value` pairs of the command line; `--env KEY=VALUE` may repeat. */
function parseArgs(argv) {
const args = { env: {} };
for (let i = 0; i < argv.length; i += 2) {
const [name, value] = [argv[i], argv[i + 1]];
if (!name.startsWith('--') || value === undefined) throw new Error(`next-styles: bad argument ${name}`);
if (name === '--env') {
const at = value.indexOf('=');
args.env[value.slice(0, at)] = value.slice(at + 1);
} else {
args[name.slice(2)] = value;
}
}
return args;
}

/** `budget --input <css> --config <tailwind config> --budget <brotli bytes> [--name <label>] [--env K=V]` */
async function budgetCommand(argv) {
const args = parseArgs(argv);
const budget = Number(args.budget);
if (!args.input || !args.config || !Number.isInteger(budget) || budget <= 0) {
throw new Error('usage: next-styles budget --input <css> --config <tailwind config> --budget <brotli bytes>');
}
const name = args.name ?? args.input;
const { raw, brotli } = await measureStylesheet({
root: process.cwd(),
input: args.input,
config: args.config,
env: args.env,
});
console.log(`[css-budget] ${name}: ${kb(raw)} raw, ${kb(brotli)} brotli (budget ${kb(budget)})`);
if (brotli > budget) {
console.error(
`[css-budget] FAIL: ${name} is over its budget. Every page carries this stylesheet in its HTML: find what a ` +
'route now imports that it does not render, or raise the budget with the reason.',
);
process.exitCode = 1;
}
}

if (require.main === module) {
const [command, ...rest] = process.argv.slice(2);
Promise.resolve()
.then(() => {
if (command !== 'budget') throw new Error(`next-styles: unknown command ${command ?? '(none)'}; try "budget"`);
return budgetCommand(rest);
})
.catch(error => {
console.error(`[css-budget] ${error.message}`);
process.exitCode = 1;
});
}

module.exports = { withInlineStyles, measureStylesheet, resolveImports };
21 changes: 21 additions & 0 deletions openframe-frontend-core/scripts/next-styles.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/** `nextConfig` (an object, or a config function) with every route's stylesheets written into its HTML. */
export function withInlineStyles<A extends unknown[], T extends object>(
nextConfig: (...args: A) => T | Promise<T>,
): (...args: A) => Promise<T & { experimental: { inlineCss: true } }>;
export function withInlineStyles<T extends object>(nextConfig: T): T & { experimental: { inlineCss: true } };

/** Options of {@link measureStylesheet}; each is described in `next-styles.cjs`. */
export interface MeasureStylesheetOptions {
root: string;
input: string;
config: string;
env?: Record<string, string>;
}

/** The app's stylesheet built as its build builds it, minified: its bytes raw and brotli-compressed. */
export function measureStylesheet(
options: MeasureStylesheetOptions,
): Promise<{ css: string; raw: number; brotli: number }>;

/** The stylesheet at `input` with each `@import` resolved to an absolute path (packages through their `exports`). */
export function resolveImports(input: string, root: string): string;
Loading
Loading