Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 20 additions & 0 deletions openframe-authorization-service-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,24 @@
<scope>test</scope>
</dependency>
</dependencies>

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<!-- The design system's fonts, from the one place they live (openframe-frontend-core's
src/styles): fonts.css and its woff2 files, served at /fonts.css and /fonts/ for the
sign-in page. Never a copy in this module. -->
<resource>
<directory>${project.basedir}/../openframe-frontend-core/src/styles</directory>
<targetPath>static</targetPath>
<includes>
<include>fonts.css</include>
<include>fonts/*.woff2</include>
<include>fonts/LICENSE-*</include>
</includes>
</resource>
</resources>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http,
"/oauth2/**",
"/login",
"/favicon.ico",
"/fonts.css",
"/fonts/**",
"/tenant/**",
"/mobile/version-policy",
"/management/**",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenFrame &bull; Sign In</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Azeret+Mono:wght@500;600;700&family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<!-- The design system's fonts (openframe-frontend-core's fonts.css, packaged by this module's build):
self-hosted, the same files every OpenFrame app loads. The body font is fetched at once. -->
<link rel="preload" as="font" type="font/woff2" crossorigin th:href="@{/fonts/dm-sans-latin-500-normal.woff2}">
<link rel="stylesheet" th:href="@{/fonts.css}">
<style>
:root {
--color-bg: #161616;
Expand Down
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
17 changes: 16 additions & 1 deletion openframe-frontend-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"bin": {
"next-styles": "./dist/build/next-styles.cjs"
},
"files": [
"dist",
"src",
Expand All @@ -28,6 +31,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 +493,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.0.4",
"date-fns": "^3.6.0",
"esbuild": "^0.28.2",
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 +556,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
12 changes: 12 additions & 0 deletions openframe-frontend-core/scripts/build-export-map.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
*/

import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join, posix } from 'node:path';
import { fileURLToPath } from 'node:url';

Expand Down Expand Up @@ -141,6 +142,17 @@ 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'));
// style-sources leaves these built files out of the first-paint stylesheet by path: a build that moves
// one would silently put its classes back on every page, so a missing one fails the build instead.
const missing = createRequire(import.meta.url)(join(ROOT, 'scripts', 'style-sources.cjs')).LAZY_STYLED.filter(
file => !existsSync(join(ROOT, file)),
);
if (missing.length > 0)
throw new Error(`build-export-map: LAZY_STYLED names files the build did not write: ${missing.join(', ')}`);
console.log(`Export map: ${names} names over ${Object.keys(entries).length} entries`);
}

Expand Down
170 changes: 170 additions & 0 deletions openframe-frontend-core/scripts/next-styles.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
#!/usr/bin/env node
/**
* 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
*
* next-styles budget --budget 31500 // the build gate (package.json script)
*
* `budget` finds the app's stylesheet (`src/app/globals.css`, else `app/globals.css`) and Tailwind config
* (`tailwind.config.{ts,js,cjs,mjs}`) itself and is named after the app's package; `--input`, `--config`
* and `--name` say otherwise.
*
* 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 { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { 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-'));
try {
// The copy lives in the temp folder, never beside the input (a file watcher or linter there would see
// it). A stylesheet's own `@config` is relative to ITS folder and Tailwind refuses an absolute one, so
// it is dropped: `config` is what the sheet is built with, as the app's build states it.
const source = join(dir, 'input.css');
const output = join(dir, 'output.css');
writeFileSync(source, resolveImports(file, root).replace(/^\s*@config\s+(['"])[^'"]+\1\s*;\s*$/gm, ''));
// 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(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;
}

/** The first of `candidates` (relative to `root`) that exists. */
const firstExisting = (root, candidates) => candidates.find(file => existsSync(resolve(root, file)));

/** `budget --budget <brotli bytes> [--input <css>] [--config <tailwind config>] [--name <label>] [--env K=V]` */
async function budgetCommand(argv) {
const root = process.cwd();
const args = parseArgs(argv);
const budget = Number(args.budget);
const input = args.input ?? firstExisting(root, ['src/app/globals.css', 'app/globals.css']);
const config =
args.config ??
firstExisting(
root,
['ts', 'js', 'cjs', 'mjs'].map(ext => `tailwind.config.${ext}`),
);
if (!input || !config || !Number.isInteger(budget) || budget <= 0) {
throw new Error('usage: next-styles budget --budget <brotli bytes> [--input <css>] [--config <tailwind config>]');
}
const name = args.name ?? (existsSync(join(root, 'package.json')) ? require(join(root, 'package.json')).name : input);
const { raw, brotli } = await measureStylesheet({ root, input, 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