feat(island,apps): island asset plugin writes hashed fonts and icon sprite
Add withIslandAssets (island tools/asset-plugin) per ADR 0008. On next dev and next build it builds the svgo sprite from src/icons and copies the Yekan Bakh fonts into the app's public/ under content-hashed names, puts their paths in env (NEXT_PUBLIC_ISLAND_*) and serves them with an immutable Cache-Control. Files are written in headers(), which only Next calls, because Nx's next plugin also evaluates the config from the workspace root. - island env (setEnv/getEnv); Icon reads the sprite path from it - icon-sprite-plugin becomes icon-name-extraction (IconName type only); the committed sprite.svg is removed - bull and bear register the plugin, validate the paths, pass them to island through their bootstraps, and add an optional CDN origin for fonts - gitignore the generated files; Nx build outputs include them Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
aafac927bf
commit
bbf84069c9
|
|
@ -26,6 +26,9 @@ 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)
|
||||
apps/*/public/icons/
|
||||
apps/*/public/fonts/
|
||||
|
||||
# Testing
|
||||
coverage
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ 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
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { withIslandAssets } from '@lumina/island/tools/asset-plugin';
|
||||
import type { NextConfig } from 'next';
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
|
|
@ -32,4 +33,5 @@ const nextConfig: NextConfig = {
|
|||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
// On next dev and next build, writes island's hashed fonts and icon sprite into public/ (0008).
|
||||
export default withIslandAssets(nextConfig);
|
||||
|
|
|
|||
|
|
@ -10,6 +10,14 @@
|
|||
"scope:market"
|
||||
],
|
||||
"targets": {
|
||||
"build": {
|
||||
"outputs": [
|
||||
"{projectRoot}/.next/!(cache)/**/*",
|
||||
"{projectRoot}/.next/!(cache)",
|
||||
"{projectRoot}/public/icons",
|
||||
"{projectRoot}/public/fonts"
|
||||
]
|
||||
},
|
||||
"dev": {
|
||||
"options": {
|
||||
"command": "next dev --port 3002"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
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';
|
||||
|
|
@ -8,6 +9,7 @@ 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.
|
||||
|
|
@ -17,6 +19,7 @@ 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({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
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';
|
||||
|
|
@ -11,6 +12,7 @@ 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({
|
||||
|
|
@ -19,6 +21,7 @@ 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.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
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}`,
|
||||
},
|
||||
};
|
||||
|
|
@ -3,6 +3,7 @@ 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({
|
||||
|
|
@ -13,6 +14,11 @@ 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,
|
||||
|
|
@ -20,5 +26,12 @@ 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,
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ 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
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { withIslandAssets } from '@lumina/island/tools/asset-plugin';
|
||||
import type { NextConfig } from 'next';
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
|
|
@ -32,4 +33,5 @@ const nextConfig: NextConfig = {
|
|||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
// On next dev and next build, writes island's hashed fonts and icon sprite into public/ (0008).
|
||||
export default withIslandAssets(nextConfig);
|
||||
|
|
|
|||
|
|
@ -10,6 +10,14 @@
|
|||
"scope:market"
|
||||
],
|
||||
"targets": {
|
||||
"build": {
|
||||
"outputs": [
|
||||
"{projectRoot}/.next/!(cache)/**/*",
|
||||
"{projectRoot}/.next/!(cache)",
|
||||
"{projectRoot}/public/icons",
|
||||
"{projectRoot}/public/fonts"
|
||||
]
|
||||
},
|
||||
"dev": {
|
||||
"options": {
|
||||
"command": "next dev --port 3001"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
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';
|
||||
|
|
@ -8,6 +9,7 @@ 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.
|
||||
|
|
@ -17,6 +19,7 @@ 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({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
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';
|
||||
|
|
@ -11,6 +12,7 @@ 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({
|
||||
|
|
@ -19,6 +21,7 @@ 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.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
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}`,
|
||||
},
|
||||
};
|
||||
|
|
@ -3,6 +3,7 @@ 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({
|
||||
|
|
@ -13,6 +14,11 @@ 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,
|
||||
|
|
@ -20,5 +26,12 @@ 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,
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -19,4 +19,4 @@ Lumina uses two variable faces from `packages/island/src/fonts/`: Yekan Bakh FaN
|
|||
## Consequences
|
||||
- We now own what `next/font` did: hashed names and immutable `Cache-Control` (the asset plugin), the preload (`FontFaces`), and the fallback metrics (`FONT_FALLBACK` in island `constants.ts`, measured on Persian text).
|
||||
- The font is licensed. "Never a public CDN" means only the company's own CDN. Confirm the licence covers web embedding from that CDN.
|
||||
- Debt: both apps still load the faces with `next/font/local` in `src/styles/fonts.ts`, and `island.css` says so. `FontFaces`, island env, `FONT_FALLBACK`, and the asset plugin don't exist yet.
|
||||
- Debt: both apps still load the faces with `next/font/local` in `src/styles/fonts.ts`, and `island.css` says so. `FontFaces` and `FONT_FALLBACK` don't exist yet; island env and the asset plugin do, and already write and pass the hashed font URLs.
|
||||
|
|
|
|||
|
|
@ -25,3 +25,4 @@ Fonts (0007) and the icon sprite live in island, but browsers load them from eac
|
|||
- In dev, edits to island assets need a dev-server restart (Next watches only next.config), unless the plugin adds a watcher.
|
||||
- Other phases, `next start` included, get the config back unchanged: the build already inlined `env` and wrote the headers into its routes manifest, so production needs neither island's sources nor svgo. `next typegen` and other build-phase commands still run it.
|
||||
- Standalone and Docker builds must copy `public/`.
|
||||
- Nx's `@nx/next` plugin also calls the config with `PHASE_PRODUCTION_BUILD`, from the workspace root, to read `distDir`. So the plugin hashes when the config is evaluated but writes only in `headers()`, which only Next calls. Each app's Nx `build` outputs include `public/icons` and `public/fonts`.
|
||||
|
|
|
|||
|
|
@ -30,16 +30,15 @@
|
|||
],
|
||||
"targets": {
|
||||
"icons": {
|
||||
"command": "jiti src/tools/icon-sprite-plugin/run.ts",
|
||||
"command": "jiti src/tools/icon-name-extraction/run.ts",
|
||||
"options": {
|
||||
"cwd": "{projectRoot}"
|
||||
},
|
||||
"inputs": [
|
||||
"{projectRoot}/src/icons/*.svg",
|
||||
"{projectRoot}/src/tools/icon-sprite-plugin/**/*"
|
||||
"{projectRoot}/src/tools/icon-name-extraction/**/*"
|
||||
],
|
||||
"outputs": [
|
||||
"{projectRoot}/src/atoms/icon/sprite.svg",
|
||||
"{projectRoot}/src/atoms/icon/icon-names.ts"
|
||||
],
|
||||
"cache": true
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { getEnv } from '../../env';
|
||||
import { Element } from '../../primitives/element';
|
||||
import { cn } from '../../tools/cn';
|
||||
import { SPRITE_URL } from './constants';
|
||||
import type { IconProps } from './types';
|
||||
|
||||
/** A line icon from the sprite, drawn in `currentColor` on a 24px grid. */
|
||||
|
|
@ -30,7 +30,8 @@ export function Icon({
|
|||
className={cn('inline-block flex-none align-middle', className)}
|
||||
{...props}
|
||||
>
|
||||
<Element tag="use" href={`${SPRITE_URL}#${name}`} />
|
||||
{/* 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}`} />
|
||||
</Element>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
import sprite from './sprite.svg';
|
||||
|
||||
/** Next.js imports a static file as `{ src }`, other bundlers as a URL string. */
|
||||
const asset = sprite as unknown as string | { src: string };
|
||||
|
||||
/** One hashed file the browser caches; each icon is a `<use>` into it, so icons add no JavaScript. */
|
||||
export const SPRITE_URL = typeof asset === 'string' ? asset : asset.src;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
// Generated by tools/icon-sprite-plugin from src/icons/*.svg. Run `pnpm nx run island:icons`.
|
||||
// Generated by tools/icon-name-extraction from src/icons/*.svg. Run `pnpm nx run island:icons`.
|
||||
|
||||
export const ICON_NAMES = [
|
||||
'alert',
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 8.6 KiB |
|
|
@ -0,0 +1,18 @@
|
|||
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;
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { getEnv, setEnv } from './env';
|
||||
export type { IslandEnv } from './types';
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
/** 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;
|
||||
};
|
||||
};
|
||||
|
|
@ -204,3 +204,5 @@ export type {
|
|||
ValidTags,
|
||||
} from './primitives/element';
|
||||
export { cn } from './tools/cn';
|
||||
export { getEnv, setEnv } from './env';
|
||||
export type { IslandEnv } from './env';
|
||||
|
|
|
|||
|
|
@ -0,0 +1,135 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
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;
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
// Build-time only, so island's root index.ts leaves it out (0008).
|
||||
export { withIslandAssets } from './asset-plugin';
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
/** 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;
|
||||
};
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import { readdirSync, writeFileSync } from 'node:fs';
|
||||
import { basename } from 'node:path';
|
||||
|
||||
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`.
|
||||
*/
|
||||
export function extractIconNames({
|
||||
iconsDir,
|
||||
namesFile,
|
||||
}: IconNameExtractionOptions): string[] {
|
||||
const names = readdirSync(iconsDir)
|
||||
.filter((file) => file.endsWith('.svg'))
|
||||
.sort()
|
||||
.map((file) => basename(file, '.svg'));
|
||||
|
||||
writeFileSync(
|
||||
namesFile,
|
||||
[
|
||||
'// Generated by tools/icon-name-extraction from src/icons/*.svg. Run `pnpm nx run island:icons`.',
|
||||
'',
|
||||
'export const ICON_NAMES = [',
|
||||
...names.map((name) => ` '${name}',`),
|
||||
'] as const;',
|
||||
'',
|
||||
'export type IconName = (typeof ICON_NAMES)[number];',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
return names;
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { extractIconNames } from './icon-name-extraction';
|
||||
export type { IconNameExtractionOptions } from './types';
|
||||
|
|
@ -1,14 +1,13 @@
|
|||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { buildIconSprite } from './icon-sprite-plugin';
|
||||
import { extractIconNames } from './icon-name-extraction';
|
||||
|
||||
const src = (path: string) =>
|
||||
fileURLToPath(new URL(`../../${path}`, import.meta.url));
|
||||
|
||||
const names = buildIconSprite({
|
||||
const names = extractIconNames({
|
||||
iconsDir: src('icons'),
|
||||
spriteFile: src('atoms/icon/sprite.svg'),
|
||||
namesFile: src('atoms/icon/icon-names.ts'),
|
||||
});
|
||||
|
||||
console.log(`Icon sprite: ${names.length} icons`);
|
||||
console.log(`Icon names: ${names.length} icons`);
|
||||
|
|
@ -1,8 +1,6 @@
|
|||
export type IconSpriteOptions = {
|
||||
export type IconNameExtractionOptions = {
|
||||
/** Folder of source icons, one `<name>.svg` each, drawn on a 24px grid in `currentColor`. */
|
||||
iconsDir: string;
|
||||
/** The sprite to write: one `<symbol id="<name>">` per icon. */
|
||||
spriteFile: string;
|
||||
/** The TypeScript file to write with the `IconName` union. */
|
||||
namesFile: string;
|
||||
};
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { optimize } from 'svgo';
|
||||
|
||||
import type { IconSpriteOptions } from './types';
|
||||
|
||||
const ROOT_SVG = /^<svg\b([^>]*)>([\s\S]*)<\/svg>$/;
|
||||
const VIEW_BOX = /viewBox="([^"]+)"/;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function buildIconSprite({
|
||||
iconsDir,
|
||||
spriteFile,
|
||||
namesFile,
|
||||
}: IconSpriteOptions): string[] {
|
||||
const files = readdirSync(iconsDir)
|
||||
.filter((file) => file.endsWith('.svg'))
|
||||
.sort();
|
||||
const names = files.map((file) => basename(file, '.svg'));
|
||||
|
||||
const symbols = files.map((file, index) => {
|
||||
const { data } = optimize(readFileSync(join(iconsDir, 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="${names[index]}" viewBox="${viewBox}">${body}</symbol>`;
|
||||
});
|
||||
|
||||
// Next.js reads a static SVG's size on import, so the root carries one; `<use>` ignores it.
|
||||
writeFileSync(
|
||||
spriteFile,
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24">${symbols.join('')}</svg>\n`,
|
||||
);
|
||||
writeFileSync(
|
||||
namesFile,
|
||||
[
|
||||
'// Generated by tools/icon-sprite-plugin from src/icons/*.svg. Run `pnpm nx run island:icons`.',
|
||||
'',
|
||||
'export const ICON_NAMES = [',
|
||||
...names.map((name) => ` '${name}',`),
|
||||
'] as const;',
|
||||
'',
|
||||
'export type IconName = (typeof ICON_NAMES)[number];',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
return names;
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
export { buildIconSprite } from './icon-sprite-plugin';
|
||||
export type { IconSpriteOptions } from './types';
|
||||
Loading…
Reference in New Issue