feat(island,apps): serve fonts and icon sprite under fixed names

Replace the hashing asset plugin with two build-time plugins that never
rename their files, so an unchanged font or sprite stays in every
visitor's cache across deploys (0011, 0012):

- icon-sprite-plugin builds icons/*.svg with svgo into
  public/icons/symbol-defs.svg. The Icon atom links it as
  symbol-defs.svg?v=<ICON_SPRITE_VERSION>; the file's first line stamps
  its version, so dev warns when the sprite changes without a bump.
- font-copy-plugin copies island fonts/ byte for byte into public/fonts/
  and warns when a font changes under its old name.
- island fonts.css declares both Yekan Bakh faces with root paths and a
  fallback face; theme.css points font-sans and font-latin at them.
- Root layouts preload CRITICAL_FONT_URL. next/font is gone.
- Both apps serve /fonts and /icons as immutable.
- island env, the apps' island-env bootstrap, NEXT_PUBLIC_ISLAND_* and
  NEXT_PUBLIC_CDN_ORIGIN are removed; paths live in island constants.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-10-05 19:00:46 +04:00
parent dc229a3949
commit 86944adb97
42 changed files with 311 additions and 415 deletions

2
.gitignore vendored
View File

@ -26,7 +26,7 @@ build
.next
next-env.d.ts
.vercel
# Hashed fonts and icon sprite, written by island's asset plugin on next dev and next build (0008)
# Fonts and icon sprite, written by island's font-copy and icon-sprite plugins on next dev and next build (0012)
apps/*/public/icons/
apps/*/public/fonts/

View File

@ -6,10 +6,6 @@ NEXT_PUBLIC_BALE_HANDLE=lumina_support
NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support
NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸
# Optional: the CDN origin, without a trailing slash, that serves public/fonts/ under the same paths.
# It must send Access-Control-Allow-Origin. The icon sprite always loads from the app's own origin.
NEXT_PUBLIC_CDN_ORIGIN=
# Server only: the API origin from inside the deployment network.
API_INTERNAL_ORIGIN=http://localhost:3000

View File

@ -1,6 +1,13 @@
import { withIslandAssets } from '@lumina/island/tools/asset-plugin';
import { withFontCopy } from '@lumina/island/tools/font-copy-plugin';
import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin';
import type { NextConfig } from 'next';
// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new
// ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again.
const immutable = [
{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' },
];
const nextConfig: NextConfig = {
// Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [
@ -21,6 +28,12 @@ const nextConfig: NextConfig = {
},
];
},
async headers() {
return [
{ source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable },
];
},
// One canonical URL per channel: send direct `/channels/…` hits to `/@…`.
async redirects() {
return [
@ -33,5 +46,6 @@ const nextConfig: NextConfig = {
},
};
// On next dev and next build, writes island's hashed fonts and icon sprite into public/ (0008).
export default withIslandAssets(nextConfig);
// On next dev and next build, island's plugins write the fonts and icon sprite into public/
// under their fixed names, with no hash (0012).
export default withIconSprite(withFontCopy(nextConfig));

View File

@ -8,7 +8,6 @@ import { Element } from '@lumina/island/primitives/element';
import { ErrorFallback } from '@lumina/market/app/error-boundaries';
import { i18n } from '../i18n/i18n.client';
import { yekanBakh } from '../styles';
type GlobalErrorProps = {
error: Error & { digest?: string };
@ -17,12 +16,7 @@ type GlobalErrorProps = {
/** The app boundary (EB-W): the last resort when nothing below caught the error. */
export default function GlobalError({ error }: GlobalErrorProps) {
return (
<Element
tag="html"
lang={i18n.language}
dir={i18n.dir()}
className={yekanBakh.variable}
>
<Element tag="html" lang={i18n.language} dir={i18n.dir()}>
<Element tag="body">
<Element tag="meta" name="robots" content="noindex" />
<ErrorFallback

View File

@ -2,13 +2,14 @@
import '../bootstrap/bootstrap.server';
import '../styles/app.css';
import { CRITICAL_FONT_URL } from '@lumina/island/constants';
import { Element } from '@lumina/island/primitives/element';
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { preload } from 'react-dom';
import { rootMetadata } from '../configs';
import { i18n } from '../i18n';
import { yekanBakh, yekanBakhLatin } from '../styles';
import { AppProviders } from './organisms/app-providers';
export function generateMetadata(): Metadata {
@ -16,13 +17,15 @@ export function generateMetadata(): Metadata {
}
export default function RootLayout({ children }: { children: ReactNode }) {
// Only the face every page renders first; the Latin face loads where شبا is shown.
preload(CRITICAL_FONT_URL, {
as: 'font',
type: 'font/woff2',
crossOrigin: 'anonymous',
});
return (
<Element
tag="html"
lang={i18n.language}
dir={i18n.dir()}
className={`${yekanBakh.variable} ${yekanBakhLatin.variable}`}
>
<Element tag="html" lang={i18n.language} dir={i18n.dir()}>
<Element tag="body">
<AppProviders>{children}</AppProviders>
</Element>

View File

@ -1,6 +1,5 @@
import { configureErrorHandler } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter';
import { setEnv as setIslandEnv } from '@lumina/island/env';
import { http } from '@lumina/libs/http';
import { mapApiErrorBody } from '@lumina/market/app/http';
import { setEnv as setMarketEnv } from '@lumina/market/env';
@ -9,7 +8,6 @@ import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth';
import { API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
import { ISLAND_ENV } from './island-env';
// Fills the client module graph with public values only, before client components render (during
// SSR and in the browser). Idempotent: safe to run again.
@ -19,7 +17,6 @@ setMarketEnv({
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
});
setIslandEnv(ISLAND_ENV);
// The session lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the
// whole app; when that fails the session is over and the shell signs the user out.
http.configure({

View File

@ -1,6 +1,5 @@
import 'server-only';
import { setEnv as setIslandEnv } from '@lumina/island/env';
import { configureErrorHandler } from '@lumina/libs/error-handler';
import { http } from '@lumina/libs/http';
import { configureServerHttp } from '@lumina/libs/server';
@ -12,7 +11,6 @@ import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
import { ISLAND_ENV } from './island-env';
// Fills the server module graph once, before rendering. Idempotent: safe to run again.
setMarketEnv({
@ -21,7 +19,6 @@ setMarketEnv({
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
});
setIslandEnv(ISLAND_ENV);
// Server requests forward only the allowlisted cookies, never the session: the server render is
// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each
// request; nothing per visitor is kept in module state.

View File

@ -1,18 +0,0 @@
import type { IslandEnv } from '@lumina/island/env';
import { clientEnv } from '../env';
const cdnOrigin = clientEnv.NEXT_PUBLIC_CDN_ORIGIN ?? '';
/**
* island's settings for both sides, from the hashed paths its asset plugin wrote into `public/`.
* Fonts may load from the CDN under the same paths; the sprite never does, because `<use href>`
* only loads same-origin.
*/
export const ISLAND_ENV: IslandEnv = {
iconSpritePath: clientEnv.NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH,
fontUrls: {
sans: `${cdnOrigin}${clientEnv.NEXT_PUBLIC_ISLAND_FONT_SANS_PATH}`,
latin: `${cdnOrigin}${clientEnv.NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH}`,
},
};

View File

@ -3,7 +3,6 @@ import * as v from 'valibot';
const required = v.pipe(v.string(), v.nonEmpty());
const url = v.pipe(v.string(), v.url());
const rootPath = v.pipe(v.string(), v.startsWith('/'));
/** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */
export const clientEnv = createClientEnv({
@ -14,11 +13,6 @@ export const clientEnv = createClientEnv({
NEXT_PUBLIC_BALE_HANDLE: required,
NEXT_PUBLIC_TELEGRAM_HANDLE: required,
NEXT_PUBLIC_SUPPORT_HOURS: required,
NEXT_PUBLIC_CDN_ORIGIN: v.optional(url),
// Written by island's asset plugin in next.config, never set in .env.
NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH: rootPath,
NEXT_PUBLIC_ISLAND_FONT_SANS_PATH: rootPath,
NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH: rootPath,
},
runtimeEnv: {
NEXT_PUBLIC_API_ORIGIN: process.env.NEXT_PUBLIC_API_ORIGIN,
@ -26,12 +20,5 @@ export const clientEnv = createClientEnv({
NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE,
NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE,
NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS,
NEXT_PUBLIC_CDN_ORIGIN: process.env.NEXT_PUBLIC_CDN_ORIGIN,
NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH:
process.env.NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH,
NEXT_PUBLIC_ISLAND_FONT_SANS_PATH:
process.env.NEXT_PUBLIC_ISLAND_FONT_SANS_PATH,
NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH:
process.env.NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH,
},
});

View File

@ -1,23 +0,0 @@
import localFont from 'next/font/local';
// Variable fonts from island. next/font self-hosts them, preloads the critical face,
// and adds a size-adjusted fallback so the swap doesn't shift the layout.
/** Yekan Bakh with Persian digit shapes: every UI text. */
export const yekanBakh = localFont({
src: '../../../../packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2',
variable: '--font-yekan-bakh',
weight: '100 1000',
display: 'swap',
adjustFontFallback: 'Arial',
});
/** Yekan Bakh with Latin digits: شبا and other bank codes. Loaded only where used. */
export const yekanBakhLatin = localFont({
src: '../../../../packages/island/src/fonts/yekan-bakh-vf.woff2',
variable: '--font-yekan-bakh-latin',
weight: '100 1000',
display: 'swap',
preload: false,
adjustFontFallback: 'Arial',
});

View File

@ -1 +0,0 @@
export { yekanBakh, yekanBakhLatin } from './fonts';

View File

@ -6,10 +6,6 @@ NEXT_PUBLIC_BALE_HANDLE=lumina_support
NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support
NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸
# Optional: the CDN origin, without a trailing slash, that serves public/fonts/ under the same paths.
# It must send Access-Control-Allow-Origin. The icon sprite always loads from the app's own origin.
NEXT_PUBLIC_CDN_ORIGIN=
# Server only: the API origin from inside the deployment network.
API_INTERNAL_ORIGIN=http://localhost:3000

View File

@ -1,6 +1,13 @@
import { withIslandAssets } from '@lumina/island/tools/asset-plugin';
import { withFontCopy } from '@lumina/island/tools/font-copy-plugin';
import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin';
import type { NextConfig } from 'next';
// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new
// ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again.
const immutable = [
{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' },
];
const nextConfig: NextConfig = {
// Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [
@ -21,6 +28,12 @@ const nextConfig: NextConfig = {
},
];
},
async headers() {
return [
{ source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable },
];
},
// One canonical URL per channel: send direct `/channels/…` hits to `/@…`.
async redirects() {
return [
@ -33,5 +46,6 @@ const nextConfig: NextConfig = {
},
};
// On next dev and next build, writes island's hashed fonts and icon sprite into public/ (0008).
export default withIslandAssets(nextConfig);
// On next dev and next build, island's plugins write the fonts and icon sprite into public/
// under their fixed names, with no hash (0012).
export default withIconSprite(withFontCopy(nextConfig));

View File

@ -8,7 +8,6 @@ import { Element } from '@lumina/island/primitives/element';
import { ErrorFallback } from '@lumina/market/app/error-boundaries';
import { i18n } from '../i18n/i18n.client';
import { yekanBakh } from '../styles';
type GlobalErrorProps = {
error: Error & { digest?: string };
@ -17,12 +16,7 @@ type GlobalErrorProps = {
/** The app boundary (EB-W): the last resort when nothing below caught the error. */
export default function GlobalError({ error }: GlobalErrorProps) {
return (
<Element
tag="html"
lang={i18n.language}
dir={i18n.dir()}
className={yekanBakh.variable}
>
<Element tag="html" lang={i18n.language} dir={i18n.dir()}>
<Element tag="body">
<Element tag="meta" name="robots" content="noindex" />
<ErrorFallback

View File

@ -2,13 +2,14 @@
import '../bootstrap/bootstrap.server';
import '../styles/app.css';
import { CRITICAL_FONT_URL } from '@lumina/island/constants';
import { Element } from '@lumina/island/primitives/element';
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { preload } from 'react-dom';
import { rootMetadata } from '../configs';
import { i18n } from '../i18n';
import { yekanBakh, yekanBakhLatin } from '../styles';
import { AppProviders } from './organisms/app-providers';
export function generateMetadata(): Metadata {
@ -16,13 +17,15 @@ export function generateMetadata(): Metadata {
}
export default function RootLayout({ children }: { children: ReactNode }) {
// Only the face every page renders first; the Latin face loads where شبا is shown.
preload(CRITICAL_FONT_URL, {
as: 'font',
type: 'font/woff2',
crossOrigin: 'anonymous',
});
return (
<Element
tag="html"
lang={i18n.language}
dir={i18n.dir()}
className={`${yekanBakh.variable} ${yekanBakhLatin.variable}`}
>
<Element tag="html" lang={i18n.language} dir={i18n.dir()}>
<Element tag="body">
<AppProviders>{children}</AppProviders>
</Element>

View File

@ -1,6 +1,5 @@
import { configureErrorHandler } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter';
import { setEnv as setIslandEnv } from '@lumina/island/env';
import { http } from '@lumina/libs/http';
import { mapApiErrorBody } from '@lumina/market/app/http';
import { setEnv as setMarketEnv } from '@lumina/market/env';
@ -9,7 +8,6 @@ import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth';
import { API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
import { ISLAND_ENV } from './island-env';
// Fills the client module graph with public values only, before client components render (during
// SSR and in the browser). Idempotent: safe to run again.
@ -19,7 +17,6 @@ setMarketEnv({
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
});
setIslandEnv(ISLAND_ENV);
// The session lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the
// whole app; when that fails the session is over and the shell signs the user out.
http.configure({

View File

@ -1,6 +1,5 @@
import 'server-only';
import { setEnv as setIslandEnv } from '@lumina/island/env';
import { configureErrorHandler } from '@lumina/libs/error-handler';
import { http } from '@lumina/libs/http';
import { configureServerHttp } from '@lumina/libs/server';
@ -12,7 +11,6 @@ import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
import { ISLAND_ENV } from './island-env';
// Fills the server module graph once, before rendering. Idempotent: safe to run again.
setMarketEnv({
@ -21,7 +19,6 @@ setMarketEnv({
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
});
setIslandEnv(ISLAND_ENV);
// Server requests forward only the allowlisted cookies, never the session: the server render is
// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each
// request; nothing per visitor is kept in module state.

View File

@ -1,18 +0,0 @@
import type { IslandEnv } from '@lumina/island/env';
import { clientEnv } from '../env';
const cdnOrigin = clientEnv.NEXT_PUBLIC_CDN_ORIGIN ?? '';
/**
* island's settings for both sides, from the hashed paths its asset plugin wrote into `public/`.
* Fonts may load from the CDN under the same paths; the sprite never does, because `<use href>`
* only loads same-origin.
*/
export const ISLAND_ENV: IslandEnv = {
iconSpritePath: clientEnv.NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH,
fontUrls: {
sans: `${cdnOrigin}${clientEnv.NEXT_PUBLIC_ISLAND_FONT_SANS_PATH}`,
latin: `${cdnOrigin}${clientEnv.NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH}`,
},
};

View File

@ -3,7 +3,6 @@ import * as v from 'valibot';
const required = v.pipe(v.string(), v.nonEmpty());
const url = v.pipe(v.string(), v.url());
const rootPath = v.pipe(v.string(), v.startsWith('/'));
/** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */
export const clientEnv = createClientEnv({
@ -14,11 +13,6 @@ export const clientEnv = createClientEnv({
NEXT_PUBLIC_BALE_HANDLE: required,
NEXT_PUBLIC_TELEGRAM_HANDLE: required,
NEXT_PUBLIC_SUPPORT_HOURS: required,
NEXT_PUBLIC_CDN_ORIGIN: v.optional(url),
// Written by island's asset plugin in next.config, never set in .env.
NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH: rootPath,
NEXT_PUBLIC_ISLAND_FONT_SANS_PATH: rootPath,
NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH: rootPath,
},
runtimeEnv: {
NEXT_PUBLIC_API_ORIGIN: process.env.NEXT_PUBLIC_API_ORIGIN,
@ -26,12 +20,5 @@ export const clientEnv = createClientEnv({
NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE,
NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE,
NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS,
NEXT_PUBLIC_CDN_ORIGIN: process.env.NEXT_PUBLIC_CDN_ORIGIN,
NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH:
process.env.NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH,
NEXT_PUBLIC_ISLAND_FONT_SANS_PATH:
process.env.NEXT_PUBLIC_ISLAND_FONT_SANS_PATH,
NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH:
process.env.NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH,
},
});

View File

@ -1,23 +0,0 @@
import localFont from 'next/font/local';
// Variable fonts from island. next/font self-hosts them, preloads the critical face,
// and adds a size-adjusted fallback so the swap doesn't shift the layout.
/** Yekan Bakh with Persian digit shapes: every UI text. */
export const yekanBakh = localFont({
src: '../../../../packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2',
variable: '--font-yekan-bakh',
weight: '100 1000',
display: 'swap',
adjustFontFallback: 'Arial',
});
/** Yekan Bakh with Latin digits: شبا and other bank codes. Loaded only where used. */
export const yekanBakhLatin = localFont({
src: '../../../../packages/island/src/fonts/yekan-bakh-vf.woff2',
variable: '--font-yekan-bakh-latin',
weight: '100 1000',
display: 'swap',
preload: false,
adjustFontFallback: 'Arial',
});

View File

@ -1 +0,0 @@
export { yekanBakh, yekanBakhLatin } from './fonts';

View File

@ -16,7 +16,7 @@
"./primitives/*": "./src/primitives/*/index.ts",
"./hooks/*": "./src/hooks/*/index.ts",
"./tools/*": "./src/tools/*/index.ts",
"./env": "./src/env/index.ts",
"./constants": "./src/constants.ts",
"./styles/*": "./src/styles/*",
"./icons/*": "./src/icons/*",
"./fonts/*": "./src/fonts/*",

View File

@ -1,4 +1,4 @@
import { getEnv } from '../../env';
import { ICON_SPRITE_URL } from '../../constants';
import { Element } from '../../primitives/element';
import { cn } from '../../tools/cn';
import type { IconProps } from './types';
@ -30,8 +30,8 @@ export function Icon({
className={cn('inline-block flex-none align-middle', className)}
{...props}
>
{/* One hashed sprite the browser caches; each icon is a `<use>` into it, so icons add no JavaScript. */}
<Element tag="use" href={`${getEnv().iconSpritePath}#${name}`} />
{/* One sprite under a fixed name, linked with its version, that the browser caches across deploys; each icon is a `<use>` into it, so icons add no JavaScript. */}
<Element tag="use" href={`${ICON_SPRITE_URL}#${name}`} />
</Element>
);
}

View File

@ -0,0 +1,24 @@
// Fonts and the icon sprite keep fixed names that no build step hashes or renames, so a file that
// didn't change stays in every visitor's cache across deploys (0011, 0012). Fonts have no version: a
// changed font ships as a new file with a new name. The sprite's version lives only in its link.
/**
* Raise it with every change to `icons/*.svg` or to the svgo step in `icon-sprite-plugin`, in the
* same commit. Never reuse or lower it.
*/
export const ICON_SPRITE_VERSION = 1;
/** Where `icon-sprite-plugin` writes the sprite, under each app's `public/`. Its name never changes. */
export const ICON_SPRITE_PATH = '/icons/symbol-defs.svg';
/**
* Root-relative and same-origin: `<use href>` never loads across origins, and CORS can't change
* that. The version is a query string, so a CDN must keep the query in its cache key.
*/
export const ICON_SPRITE_URL = `${ICON_SPRITE_PATH}?v=${ICON_SPRITE_VERSION}`;
/**
* The face every page renders first, Yekan Bakh FaNum. Each root layout preloads it. A font file
* is named only here and in `styles/fonts.css`.
*/
export const CRITICAL_FONT_URL = '/fonts/yekan-bakh-fa-num-vf.woff2';

View File

@ -1,18 +0,0 @@
import type { IslandEnv } from './types';
let islandEnv: IslandEnv | undefined;
/** Called by each app bootstrap, on the server and in the browser. Idempotent. */
export function setEnv(env: IslandEnv): void {
islandEnv = env;
}
/** Read inside functions, never at module top level: bootstrap may not have run yet. */
export function getEnv(): Readonly<IslandEnv> {
if (!islandEnv) {
throw new Error(
'island env is not set. The app bootstrap must call setEnv from @lumina/island/env first.',
);
}
return islandEnv;
}

View File

@ -1,2 +0,0 @@
export { getEnv, setEnv } from './env';
export type { IslandEnv } from './types';

View File

@ -1,15 +0,0 @@
/** island's settings: the hashed asset URLs that the asset plugin wrote into the app's `public/`. */
export type IslandEnv = {
/**
* Root-relative URL of the icon sprite (`/icons/symbol-defs.<hash>.svg`). Always same-origin:
* `<use href>` never loads across origins, and CORS can't change that.
*/
iconSpritePath: string;
/** Font URL per font token, from the app's `public/fonts/` or the CDN under the same paths. */
fontUrls: {
/** Yekan Bakh FaNum: every UI text. */
sans: string;
/** Yekan Bakh: only text that must show Latin digits, such as شبا. */
latin: string;
};
};

View File

@ -204,5 +204,9 @@ export type {
ValidTags,
} from './primitives/element';
export { cn } from './tools/cn';
export { getEnv, setEnv } from './env';
export type { IslandEnv } from './env';
export {
CRITICAL_FONT_URL,
ICON_SPRITE_PATH,
ICON_SPRITE_URL,
ICON_SPRITE_VERSION,
} from './constants';

View File

@ -0,0 +1,41 @@
/*
* Yekan Bakh, served from each app's public/fonts/ by font-copy-plugin (0011, 0012).
* Every `src` is a root path to a file under its fixed name. Next.js leaves root paths alone; a
* relative url('../fonts/…') would go through the bundler and get a hash.
* A font file is named only here and in CRITICAL_FONT_URL (constants.ts). A changed font ships
* under a new name, never under its old one.
*
* Both faces are variable: wght 100–950 and wdth 62.5–150%. The ranges must be declared:
* without font-stretch the browser leaves wdth at its default, 62.5%, and text renders condensed.
*/
/* Persian digit shapes for Latin digits: every UI text (`font-sans`). Preloaded. */
@font-face {
font-family: 'Yekan Bakh FaNum';
src: url('/fonts/yekan-bakh-fa-num-vf.woff2') format('woff2');
font-weight: 100 950;
font-stretch: 62.5% 150%;
font-display: swap;
}
/* Latin digits: only شبا and other codes banks print that way (`font-latin`). Not preloaded. */
@font-face {
font-family: 'Yekan Bakh';
src: url('/fonts/yekan-bakh-vf.woff2') format('woff2');
font-weight: 100 950;
font-stretch: 62.5% 150%;
font-display: swap;
}
/*
* Shown until Yekan Bakh loads. Its vertical metrics are the web font's own (hhea: ascent 1000,
* descent 550, line gap 0, per 1000 units), so lines keep their height when the font swaps in.
* size-adjust isn't measured yet; it needs Persian text set in Tahoma against Yekan Bakh.
*/
@font-face {
font-family: 'Yekan Bakh Fallback';
src: local('Tahoma'), local('Arial');
ascent-override: 100%;
descent-override: 55%;
line-gap-override: 0%;
}

View File

@ -1,4 +1,5 @@
/* Entry that apps import after `tailwindcss`. Fonts are loaded by each app with next/font. */
/* Entry that apps import after `tailwindcss`. Never load fonts with next/font: it hashes them (0011). */
@import './fonts.css';
@import './theme.css';
@import './utilities.css';
@source '../';

View File

@ -13,9 +13,10 @@
--breakpoint-*: initial;
--container-*: initial;
--font-sans: var(--font-yekan-bakh), Tahoma, sans-serif;
/* Faces and their fallback are declared in fonts.css. */
--font-sans: 'Yekan Bakh FaNum', 'Yekan Bakh Fallback', Tahoma, sans-serif;
/* Latin digits, for شبا and other codes banks print in Latin digits. */
--font-latin: var(--font-yekan-bakh-latin), Tahoma, sans-serif;
--font-latin: 'Yekan Bakh', 'Yekan Bakh Fallback', Tahoma, sans-serif;
/* Sizes are the design system's px values ÷ 16, in rem, so text and spacing follow
the reader's browser font size. */

View File

@ -1,135 +0,0 @@
import { createHash } from 'node:crypto';
import {
existsSync,
mkdirSync,
readdirSync,
readFileSync,
renameSync,
writeFileSync,
} from 'node:fs';
import { basename, dirname, extname, join } from 'node:path';
import type { NextConfig } from 'next';
import { optimize } from 'svgo';
import {
ASSET_PHASES,
FONTS,
FONTS_DIR,
HASH_LENGTH,
ICONS_DIR,
IMMUTABLE_CACHE_CONTROL,
SPRITE,
} from './constants';
import type { HashedAsset } from './types';
const ROOT_SVG = /^<svg\b([^>]*)>([\s\S]*)<\/svg>$/;
const VIEW_BOX = /viewBox="([^"]+)"/;
/**
* Wraps an app's `next.config`. On `next dev` and `next build` it writes island's fonts and icon
* sprite into the app's `public/` under content-hashed names, puts their paths in `env`
* (`NEXT_PUBLIC_ISLAND_*`), and serves each file with an immutable `Cache-Control`.
* Build-time only: import it from `next.config.ts`, never from app code.
*/
export function withIslandAssets(
config: NextConfig,
): (phase: string) => NextConfig {
return (phase) =>
ASSET_PHASES.has(phase) ? addIslandAssets(config) : config;
}
function addIslandAssets(config: NextConfig): NextConfig {
const assets: HashedAsset[] = [
{ ...SPRITE, content: buildSprite() },
...FONTS.map((font) => ({
...font,
content: readFileSync(join(FONTS_DIR, font.file)),
})),
].map(({ dir, file, envKey, content }) => ({
envKey,
content,
// Header sources match without basePath; Next adds it.
route: `/${dir}/${hashedName(file, content)}`,
}));
const basePath = config.basePath ?? '';
return {
...config,
env: {
...config.env,
...Object.fromEntries(
assets.map(({ envKey, route }) => [envKey, `${basePath}${route}`]),
),
},
// Only Next loads the headers, on `next dev` and `next build`, so the files are written here.
// Others that evaluate the config, such as Nx's project graph, read it without side effects.
async headers() {
writeAssets(assets);
return [
...((await config.headers?.()) ?? []),
...assets.map(({ route }) => ({
source: route,
headers: [{ key: 'Cache-Control', value: IMMUTABLE_CACHE_CONTROL }],
})),
];
},
};
}
/**
* Optimizes every icon with svgo and joins them into one sprite. Stroke and fill are dropped
* from each root, so the `<Icon>` that references a symbol sets them and a caller can change them.
*/
function buildSprite(): string {
const symbols = readdirSync(ICONS_DIR)
.filter((file) => file.endsWith('.svg'))
.sort()
.map((file) => {
const { data } = optimize(readFileSync(join(ICONS_DIR, file), 'utf8'), {
multipass: true,
// svgo 4 keeps the viewBox by default.
plugins: ['preset-default'],
});
const [, attributes, body] = ROOT_SVG.exec(data) ?? [];
const viewBox = VIEW_BOX.exec(attributes ?? '')?.[1];
if (body === undefined || !viewBox) {
throw new Error(`${file}: expected one root <svg> with a viewBox`);
}
return `<symbol id="${basename(file, '.svg')}" viewBox="${viewBox}">${body}</symbol>`;
});
return `<svg xmlns="http://www.w3.org/2000/svg">${symbols.join('')}</svg>\n`;
}
/** `symbol-defs.svg` → `symbol-defs.<hash>.svg`. */
function hashedName(file: string, content: string | Buffer): string {
const hash = createHash('sha256')
.update(content)
.digest('hex')
.slice(0, HASH_LENGTH);
const extension = extname(file);
return `${basename(file, extension)}.${hash}${extension}`;
}
/**
* Next can load the headers more than once per command, in more than one process. A hashed name
* always holds the same bytes, so an existing file is kept, and a new one is written to a temp
* file, then renamed, so no request ever sees half a file.
*/
function writeAssets(assets: readonly HashedAsset[]): void {
// Next runs from the app's folder, as every Nx target does.
const publicDir = join(process.cwd(), 'public');
if (!existsSync(publicDir)) {
throw new Error(
`island asset plugin: ${publicDir} doesn't exist. Run next from the app's folder.`,
);
}
for (const { route, content } of assets) {
const target = join(publicDir, route);
if (existsSync(target)) continue;
mkdirSync(dirname(target), { recursive: true });
const temp = `${target}.${process.pid}.tmp`;
writeFileSync(temp, content);
renameSync(temp, target);
}
}

View File

@ -1,52 +0,0 @@
import { fileURLToPath } from 'node:url';
import {
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_BUILD,
} from 'next/constants';
import type { IslandAsset } from './types';
/** island's sources, resolved from this file, so the plugin works from every app. */
export const ICONS_DIR = fileURLToPath(
new URL('../../icons/', import.meta.url),
);
export const FONTS_DIR = fileURLToPath(
new URL('../../fonts/', import.meta.url),
);
/** Built with svgo from every `icons/*.svg`, one `<symbol id="<name>">` per icon. */
export const SPRITE: IslandAsset = {
dir: 'icons',
file: 'symbol-defs.svg',
envKey: 'NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH',
};
/** Copied as they are from `fonts/`, one per font token. */
export const FONTS: readonly IslandAsset[] = [
{
dir: 'fonts',
file: 'yekan-bakh-fa-num-vf.woff2',
envKey: 'NEXT_PUBLIC_ISLAND_FONT_SANS_PATH',
},
{
dir: 'fonts',
file: 'yekan-bakh-vf.woff2',
envKey: 'NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH',
},
];
/**
* `next dev` and `next build`. Every other phase, `next start` included, gets the config unchanged:
* the build already inlined `env` and wrote the headers into its routes manifest.
*/
export const ASSET_PHASES: ReadonlySet<string> = new Set([
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_BUILD,
]);
/** A hashed name never gets new content, so browsers and CDNs keep the file without asking again. */
export const IMMUTABLE_CACHE_CONTROL = 'public, max-age=31536000, immutable';
/** Hex characters of the SHA-256 content hash in each file name. */
export const HASH_LENGTH = 8;

View File

@ -1,2 +0,0 @@
// Build-time only, so island's root index.ts leaves it out (0008).
export { withIslandAssets } from './asset-plugin';

View File

@ -1,16 +0,0 @@
/** One island file the plugin copies into the app's `public/`. */
export type IslandAsset = {
/** Folder under `public/`, which is also the URL path. */
dir: 'icons' | 'fonts';
/** Source file name; the written copy gets its content hash before the extension. */
file: string;
/** The variable that carries the hashed path to the app's `env/`. */
envKey: `NEXT_PUBLIC_ISLAND_${string}`;
};
/** An asset ready to write: its bytes and its hashed path under `public/`. */
export type HashedAsset = Pick<IslandAsset, 'envKey'> & {
content: string | Buffer;
/** `/<dir>/<name>.<hash>.<ext>`, without basePath. */
route: string;
};

View File

@ -0,0 +1,6 @@
import { fileURLToPath } from 'node:url';
/** island's fonts, resolved from this file, so the plugin works from every app. */
export const FONTS_DIR = fileURLToPath(
new URL('../../fonts/', import.meta.url),
);

View File

@ -0,0 +1,63 @@
import {
copyFileSync,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
renameSync,
} from 'node:fs';
import { join } from 'node:path';
import type { NextConfig } from 'next';
import { FONTS_DIR } from './constants';
/**
* Wraps an app's `next.config`. On `next dev` and `next build` it copies island's `fonts/` byte
* for byte into `public/fonts/`, keeping their fixed names with no hash (0011, 0012).
* Build-time only: import it from `next.config.ts`, never from app code.
*/
export function withFontCopy(config: NextConfig): NextConfig {
return {
...config,
// Only Next calls `headers()`, and only on `next dev` and `next build`; `next start` reads the
// build's routes manifest. Others that evaluate the config, such as Nx's project graph, never
// call it, so the files are copied here and nowhere else.
async headers() {
copyFonts();
return (await config.headers?.()) ?? [];
},
};
}
/**
* Next can call `headers()` more than once per command, in more than one process. An unchanged
* file is left alone, and a new one is copied to a temp file, then renamed, so no request ever
* sees half a font.
*/
function copyFonts(): void {
// Next runs from the app's folder, as every Nx target does.
const publicDir = join(process.cwd(), 'public');
if (!existsSync(publicDir)) {
throw new Error(
`font-copy-plugin: ${publicDir} doesn't exist. Run next from the app's folder.`,
);
}
const targetDir = join(publicDir, 'fonts');
mkdirSync(targetDir, { recursive: true });
for (const file of readdirSync(FONTS_DIR)) {
if (!file.endsWith('.woff2')) continue;
const source = join(FONTS_DIR, file);
const target = join(targetDir, file);
if (existsSync(target)) {
if (readFileSync(target).equals(readFileSync(source))) continue;
// Visitors who cached this name keep its old bytes for a year.
console.warn(
`font-copy-plugin: ${file} changed under the same name. Ship the changed font under a new name in fonts/, fonts.css and CRITICAL_FONT_URL before this ships.`,
);
}
const temp = `${target}.${process.pid}.tmp`;
copyFileSync(source, temp);
renameSync(temp, target);
}
}

View File

@ -0,0 +1,2 @@
// Build-time only, so island's root index.ts leaves it out (0012).
export { withFontCopy } from './font-copy-plugin';

View File

@ -5,7 +5,7 @@ import type { IconNameExtractionOptions } from './types';
/**
* Writes the `IconName` union from the icon file names, so `<Icon name>` only accepts an icon
* the sprite has. The sprite itself is built by `tools/asset-plugin` on `next dev` and `next build`.
* the sprite has. The sprite itself is built by `tools/icon-sprite-plugin` on `next dev` and `next build`.
*/
export function extractIconNames({
iconsDir,

View File

@ -0,0 +1,6 @@
import { fileURLToPath } from 'node:url';
/** island's icons, resolved from this file, so the plugin works from every app. */
export const ICONS_DIR = fileURLToPath(
new URL('../../icons/', import.meta.url),
);

View File

@ -0,0 +1,94 @@
import {
existsSync,
mkdirSync,
readdirSync,
readFileSync,
renameSync,
writeFileSync,
} from 'node:fs';
import { basename, dirname, join } from 'node:path';
import type { NextConfig } from 'next';
import { ICON_SPRITE_PATH, ICON_SPRITE_VERSION } from '../../constants';
import { ICONS_DIR } from './constants';
const ROOT_SVG = /^<svg\b([^>]*)>([\s\S]*)<\/svg>$/;
const VIEW_BOX = /viewBox="([^"]+)"/;
/** The sprite's first line, so the next run knows which version the file in `public/` was built for. */
const VERSION_STAMP = `<!-- ICON_SPRITE_VERSION ${ICON_SPRITE_VERSION} -->`;
/**
* Wraps an app's `next.config`. On `next dev` and `next build` it builds island's icon sprite
* with svgo and writes it to `public/` at `ICON_SPRITE_PATH`, a fixed name with no hash (0012). The
* version lives only in `ICON_SPRITE_URL`'s query string.
* Build-time only: import it from `next.config.ts`, never from app code.
*/
export function withIconSprite(config: NextConfig): NextConfig {
return {
...config,
// Only Next calls `headers()`, and only on `next dev` and `next build`; `next start` reads the
// build's routes manifest. Others that evaluate the config, such as Nx's project graph, never
// call it, so the file is written here and nowhere else.
async headers() {
writeSprite(await buildSprite());
return (await config.headers?.()) ?? [];
},
};
}
/**
* Optimizes every icon with svgo and joins them into one sprite. Stroke and fill are dropped
* from each root, so the `<Icon>` that references a symbol sets them and a caller can change them.
*/
async function buildSprite(): Promise<string> {
// Loaded here, so `next start` never needs svgo.
const { optimize } = await import('svgo');
const symbols = readdirSync(ICONS_DIR)
.filter((file) => file.endsWith('.svg'))
.sort()
.map((file) => {
const { data } = optimize(readFileSync(join(ICONS_DIR, file), 'utf8'), {
multipass: true,
// svgo 4 keeps the viewBox by default.
plugins: ['preset-default'],
});
const [, attributes, body] = ROOT_SVG.exec(data) ?? [];
const viewBox = VIEW_BOX.exec(attributes ?? '')?.[1];
if (body === undefined || !viewBox) {
throw new Error(`${file}: expected one root <svg> with a viewBox`);
}
return `<symbol id="${basename(file, '.svg')}" viewBox="${viewBox}">${body}</symbol>`;
});
return `${VERSION_STAMP}\n<svg xmlns="http://www.w3.org/2000/svg">${symbols.join('')}</svg>\n`;
}
/**
* Next can call `headers()` more than once per command, in more than one process. An unchanged
* file is left alone, and a new one is written to a temp file, then renamed, so no request ever
* sees half a file.
*/
function writeSprite(sprite: string): void {
// Next runs from the app's folder, as every Nx target does.
const publicDir = join(process.cwd(), 'public');
if (!existsSync(publicDir)) {
throw new Error(
`icon-sprite-plugin: ${publicDir} doesn't exist. Run next from the app's folder.`,
);
}
const target = join(publicDir, ICON_SPRITE_PATH);
if (existsSync(target)) {
const current = readFileSync(target, 'utf8');
if (current === sprite) return;
// Same version, new icons: visitors who cached this version keep the old icons for a year.
if (current.startsWith(VERSION_STAMP)) {
console.warn(
`icon-sprite-plugin: the sprite changed, but ICON_SPRITE_VERSION is still ${ICON_SPRITE_VERSION}. Raise it in island's constants.ts before this ships.`,
);
}
}
mkdirSync(dirname(target), { recursive: true });
const temp = `${target}.${process.pid}.tmp`;
writeFileSync(temp, sprite);
renameSync(temp, target);
}

View File

@ -0,0 +1,2 @@
// Build-time only, so island's root index.ts leaves it out (0012).
export { withIconSprite } from './icon-sprite-plugin';