@hamur/fonts 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/src/index.js +2472 -0
- package/dist/src/providers/index.js +386 -0
- package/dist/src/server/index.js +22 -0
- package/dist/types/src/build/cache.d.ts +17 -0
- package/dist/types/src/build/data.d.ts +19 -0
- package/dist/types/src/build/fallbacks.d.ts +49 -0
- package/dist/types/src/build/files.d.ts +7 -0
- package/dist/types/src/build/global.d.ts +3 -0
- package/dist/types/src/build/preload.d.ts +25 -0
- package/dist/types/src/build/providers.d.ts +5 -0
- package/dist/types/src/build/public-url.d.ts +2 -0
- package/dist/types/src/build/scan.d.ts +6 -0
- package/dist/types/src/build/subset.d.ts +7 -0
- package/dist/types/src/index.d.ts +18 -0
- package/dist/types/src/inject.d.ts +21 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +46 -0
- package/dist/types/src/providers/adobe.d.ts +2 -0
- package/dist/types/src/providers/bunny.d.ts +4 -0
- package/dist/types/src/providers/css.d.ts +27 -0
- package/dist/types/src/providers/fontshare.d.ts +4 -0
- package/dist/types/src/providers/fontsource.d.ts +18 -0
- package/dist/types/src/providers/google.d.ts +4 -0
- package/dist/types/src/providers/googleicons.d.ts +2 -0
- package/dist/types/src/providers/index.d.ts +3 -0
- package/dist/types/src/providers/local.d.ts +17 -0
- package/dist/types/src/providers/npm.d.ts +5 -0
- package/dist/types/src/resolve.d.ts +32 -0
- package/dist/types/src/runtime/global.d.ts +3 -0
- package/dist/types/src/scan.d.ts +29 -0
- package/dist/types/src/server/data.d.ts +11 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/index.d.ts +9 -0
- package/dist/types/src/server/preload.d.ts +2 -0
- package/dist/types/src/subset/cmap.d.ts +2 -0
- package/dist/types/src/subset/glyf.d.ts +15 -0
- package/dist/types/src/subset/sfnt.d.ts +21 -0
- package/dist/types/src/subset/woff2.d.ts +7 -0
- package/dist/types/src/types.d.ts +71 -0
- package/package.json +32 -4
- package/src/build/cache.ts +50 -0
- package/src/build/data.ts +145 -0
- package/src/build/fallbacks.ts +384 -0
- package/src/build/files.ts +102 -0
- package/src/build/global.ts +14 -0
- package/src/build/preload.ts +104 -0
- package/src/build/providers.ts +19 -0
- package/src/build/public-url.ts +21 -0
- package/src/build/scan.ts +172 -0
- package/src/build/subset.ts +74 -0
- package/src/env.d.ts +13 -0
- package/src/index.ts +25 -0
- package/src/inject.ts +59 -0
- package/src/module.ts +29 -0
- package/src/options.ts +375 -0
- package/src/providers/adobe.ts +18 -0
- package/src/providers/bunny.ts +35 -0
- package/src/providers/css.ts +154 -0
- package/src/providers/fontshare.ts +37 -0
- package/src/providers/fontsource.ts +53 -0
- package/src/providers/google.ts +31 -0
- package/src/providers/googleicons.ts +20 -0
- package/src/providers/index.ts +17 -0
- package/src/providers/local.ts +141 -0
- package/src/providers/npm.ts +96 -0
- package/src/resolve.ts +134 -0
- package/src/runtime/global.ts +5 -0
- package/src/scan.ts +275 -0
- package/src/server/data.ts +20 -0
- package/src/server/door.ts +13 -0
- package/src/server/index.ts +9 -0
- package/src/server/preload.ts +50 -0
- package/src/subset/cmap.ts +79 -0
- package/src/subset/glyf.ts +93 -0
- package/src/subset/sfnt.ts +196 -0
- package/src/subset/woff2.ts +68 -0
- package/src/types.ts +71 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { existsSync } from "node:fs"
|
|
2
|
+
import { readFile } from "node:fs/promises"
|
|
3
|
+
import { isAbsolute, join } from "node:path"
|
|
4
|
+
import { addTransform, diagnostic, useLogger, type HamurContext } from "hamur/kit"
|
|
5
|
+
import { fallbackFaceRule, fontFaceRule, insertEdits, insertRules, quote } from "../inject.ts"
|
|
6
|
+
import type { ResolvedFontsOptions } from "../options.ts"
|
|
7
|
+
import { createLocalProvider } from "../providers/local.ts"
|
|
8
|
+
import { createNpmProvider, remoteProviders } from "../providers/index.ts"
|
|
9
|
+
import { createResolver } from "../resolve.ts"
|
|
10
|
+
import { familyKey, isSystemFamily, scanCss } from "../scan.ts"
|
|
11
|
+
import { createMetaCache, fontsDirOf } from "./cache.ts"
|
|
12
|
+
import type { FontRegistry } from "./data.ts"
|
|
13
|
+
import type { PreloadNames } from "./preload.ts"
|
|
14
|
+
import { fallbackFamily, fallbackOverrides, familyMetrics, SYSTEM_METRICS, type FontMetrics } from "./fallbacks.ts"
|
|
15
|
+
import { createFontFiles } from "./files.ts"
|
|
16
|
+
import { createSubsetter } from "./subset.ts"
|
|
17
|
+
import { publicUrlsKept } from "./public-url.ts"
|
|
18
|
+
import { setupProviders } from "./providers.ts"
|
|
19
|
+
import type { FontFaceData, FontProvider } from "../types.ts"
|
|
20
|
+
import { DiagnosticError } from "hamur/kit"
|
|
21
|
+
|
|
22
|
+
/** The `fonts:css` transform, which writes the `@font-face` rules of the families a stylesheet names. */
|
|
23
|
+
export function setupScan(
|
|
24
|
+
options: ResolvedFontsOptions,
|
|
25
|
+
hamur: HamurContext,
|
|
26
|
+
preload: PreloadNames,
|
|
27
|
+
registry: FontRegistry,
|
|
28
|
+
): void {
|
|
29
|
+
const log = useLogger("fonts")
|
|
30
|
+
const { srcDir, publicDir, layers, app } = hamur.options
|
|
31
|
+
const roots = [{ srcDir, publicDir }, ...layers]
|
|
32
|
+
const report = (message: string) => {
|
|
33
|
+
if (options.throwOnError) throw new DiagnosticError("HAMUR_E5703", message)
|
|
34
|
+
log.warn(diagnostic("HAMUR_W5704", message.replace(/^\[fonts\] /, "")))
|
|
35
|
+
}
|
|
36
|
+
const fontsDir = fontsDirOf(options.cache, hamur)
|
|
37
|
+
const files = createFontFiles(join(fontsDir, "files"), report, options.cache)
|
|
38
|
+
const providers: Record<string, FontProvider> = {
|
|
39
|
+
...remoteProviders,
|
|
40
|
+
npm: createNpmProvider({ rootDir: hamur.options.rootDir }),
|
|
41
|
+
local: createLocalProvider({
|
|
42
|
+
assetDirs: roots.map((root) => `${root.srcDir}/assets/fonts`),
|
|
43
|
+
publicDirs: roots.map((root) => root.publicDir),
|
|
44
|
+
baseURL: app.baseURL,
|
|
45
|
+
publicUrlsKept,
|
|
46
|
+
}),
|
|
47
|
+
}
|
|
48
|
+
setupProviders(options, hamur, providers)
|
|
49
|
+
const resolver = createResolver({
|
|
50
|
+
options,
|
|
51
|
+
builtIn: providers,
|
|
52
|
+
report,
|
|
53
|
+
...(options.cache
|
|
54
|
+
? { cache: { store: createMetaCache(join(fontsDir, "meta")), providers: new Set(Object.keys(remoteProviders)) } }
|
|
55
|
+
: {}),
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
const fallbacks = options.fallbacks
|
|
59
|
+
const systemsFor = (generic: string | undefined): string[] =>
|
|
60
|
+
fallbacks ? (fallbacks[generic ?? "sans-serif"] ?? []) : []
|
|
61
|
+
const publicPrefix = `${app.baseURL.replace(/\/+$/, "")}/`
|
|
62
|
+
const read = async (url: string): Promise<Uint8Array | undefined> => {
|
|
63
|
+
const candidates =
|
|
64
|
+
isAbsolute(url) && existsSync(url)
|
|
65
|
+
? [url]
|
|
66
|
+
: url.startsWith(publicPrefix)
|
|
67
|
+
? roots.map((root) => join(root.publicDir, decodeURI(url.slice(publicPrefix.length))))
|
|
68
|
+
: []
|
|
69
|
+
const file = candidates.find((path) => existsSync(path))
|
|
70
|
+
return file ? new Uint8Array(await readFile(file)) : undefined
|
|
71
|
+
}
|
|
72
|
+
const subsetter = createSubsetter(join(fontsDir, "subset"), read, report)
|
|
73
|
+
const notified = new Set<string>()
|
|
74
|
+
const withoutLocal = (faces: FontFaceData[]): FontFaceData[] =>
|
|
75
|
+
faces
|
|
76
|
+
.map((face) => ({ ...face, src: face.src.filter((entry) => "url" in entry) }))
|
|
77
|
+
.filter((face) => face.src.length > 0)
|
|
78
|
+
const metrics = new Map<string, Promise<FontMetrics | undefined>>()
|
|
79
|
+
const metricsOf = (family: string, faces: FontFaceData[]): Promise<FontMetrics | undefined> => {
|
|
80
|
+
const key = familyKey(family)
|
|
81
|
+
let found = metrics.get(key)
|
|
82
|
+
if (!found) metrics.set(key, (found = familyMetrics(family, faces, { read, report })))
|
|
83
|
+
return found
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
addTransform({
|
|
87
|
+
name: "fonts:css",
|
|
88
|
+
filter: { id: /\.(?:css|s[ac]ss|less|styl)$/ },
|
|
89
|
+
target: "client",
|
|
90
|
+
version: () => resolver.version(),
|
|
91
|
+
async transform(code, { loader }) {
|
|
92
|
+
if (loader !== "css" || !/font/i.test(code)) return null
|
|
93
|
+
const scan = scanCss(code, { customProperties: options.processCSSVariables })
|
|
94
|
+
const declared = new Set(scan.declared)
|
|
95
|
+
const wanted = new Map<string, string>()
|
|
96
|
+
for (const use of scan.uses) {
|
|
97
|
+
for (const { name } of use.names) {
|
|
98
|
+
const key = familyKey(name)
|
|
99
|
+
if (declared.has(key) || wanted.has(key) || (isSystemFamily(name) && !resolver.listed(name))) continue
|
|
100
|
+
wanted.set(key, name)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const rules: string[] = []
|
|
104
|
+
const fallbackOf = new Map<string, string>()
|
|
105
|
+
for (const [key, name] of wanted) {
|
|
106
|
+
const resolved = await resolver.resolve(name)
|
|
107
|
+
if (!resolved) continue
|
|
108
|
+
const descriptors = {
|
|
109
|
+
display: resolved.entry?.display ?? options.defaults.display,
|
|
110
|
+
...(resolved.entry?.unicodeRange !== undefined ? { unicodeRange: resolved.entry.unicodeRange } : {}),
|
|
111
|
+
...(resolved.entry?.stretch !== undefined ? { stretch: resolved.entry.stretch } : {}),
|
|
112
|
+
...(resolved.entry?.featureSettings !== undefined ? { featureSettings: resolved.entry.featureSettings } : {}),
|
|
113
|
+
...(resolved.entry?.variationSettings !== undefined
|
|
114
|
+
? { variationSettings: resolved.entry.variationSettings }
|
|
115
|
+
: {}),
|
|
116
|
+
}
|
|
117
|
+
const glyphs = resolved.entry?.glyphs
|
|
118
|
+
const whole = await files.localize(
|
|
119
|
+
resolved.name,
|
|
120
|
+
options.localSources ? resolved.faces : withoutLocal(resolved.faces),
|
|
121
|
+
glyphs,
|
|
122
|
+
)
|
|
123
|
+
const faces =
|
|
124
|
+
glyphs && resolved.provider !== "google" && resolved.provider !== "googleicons"
|
|
125
|
+
? await subsetter.subset(resolved.name, whole, glyphs)
|
|
126
|
+
: whole
|
|
127
|
+
if (!notified.has(key)) {
|
|
128
|
+
notified.add(key)
|
|
129
|
+
const paths = faces.flatMap((face) =>
|
|
130
|
+
face.src.flatMap((entry) =>
|
|
131
|
+
"url" in entry && !/^https?:\/\//i.test(entry.url) && existsSync(entry.url) ? [entry.url] : [],
|
|
132
|
+
),
|
|
133
|
+
)
|
|
134
|
+
registry.record(resolved.name, faces)
|
|
135
|
+
await hamur.hooks.callHook("fonts:resolved", { family: resolved.name, faces, files: [...new Set(paths)] })
|
|
136
|
+
}
|
|
137
|
+
if (resolved.entry?.preload ?? options.defaults.preload)
|
|
138
|
+
preload.add(faces, (resolved.entry ?? options.defaults).subsets)
|
|
139
|
+
for (const face of faces) rules.push(fontFaceRule(resolved.name, face, descriptors))
|
|
140
|
+
const systems = [
|
|
141
|
+
...new Set(
|
|
142
|
+
scan.uses
|
|
143
|
+
.filter((use) => use.names.some((family) => familyKey(family.name) === key))
|
|
144
|
+
.flatMap((use) => systemsFor(use.generic)),
|
|
145
|
+
),
|
|
146
|
+
]
|
|
147
|
+
if (systems.length === 0) continue
|
|
148
|
+
const font = await metricsOf(resolved.name, whole)
|
|
149
|
+
if (!font) continue
|
|
150
|
+
for (const system of systems)
|
|
151
|
+
rules.push(fallbackFaceRule(resolved.name, system, fallbackOverrides(font, SYSTEM_METRICS[system]!)))
|
|
152
|
+
fallbackOf.set(key, resolved.name)
|
|
153
|
+
}
|
|
154
|
+
if (rules.length === 0) return null
|
|
155
|
+
const edits = scan.uses.flatMap((use) =>
|
|
156
|
+
use.names.flatMap((family) => {
|
|
157
|
+
const resolvedName = fallbackOf.get(familyKey(family.name))
|
|
158
|
+
const systems = systemsFor(use.generic)
|
|
159
|
+
return resolvedName && systems.length
|
|
160
|
+
? [
|
|
161
|
+
{
|
|
162
|
+
at: family.end,
|
|
163
|
+
text: systems.map((system) => `, ${quote(fallbackFamily(resolvedName, system))}`).join(""),
|
|
164
|
+
},
|
|
165
|
+
]
|
|
166
|
+
: []
|
|
167
|
+
}),
|
|
168
|
+
)
|
|
169
|
+
return insertRules(insertEdits(code, edits), scan.insertAt, rules)
|
|
170
|
+
},
|
|
171
|
+
})
|
|
172
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { basename, extname, join } from "node:path"
|
|
2
|
+
import { subsetFont } from "../subset/sfnt.ts"
|
|
3
|
+
import { writeWoff2 } from "../subset/woff2.ts"
|
|
4
|
+
import type { FontFaceData } from "../types.ts"
|
|
5
|
+
import { sha256, writeAtomic } from "./cache.ts"
|
|
6
|
+
|
|
7
|
+
export interface FontSubsetter {
|
|
8
|
+
/** Each face's first readable TrueType file cut to `glyphs` and written as WOFF2; a CFF or `gvar` font, and a face with no readable file, is kept whole. */
|
|
9
|
+
subset(family: string, faces: FontFaceData[], glyphs: string): Promise<FontFaceData[]>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
type Cut = { path: string } | { skipped: "cff" | "gvar" } | undefined
|
|
13
|
+
|
|
14
|
+
/** Subsets of `local`, `src` and downloaded files, written to `<dir>/<file>-<hash>.woff2`. */
|
|
15
|
+
export function createSubsetter(
|
|
16
|
+
dir: string,
|
|
17
|
+
read: (url: string) => Promise<Uint8Array | undefined>,
|
|
18
|
+
report: (message: string) => void,
|
|
19
|
+
): FontSubsetter {
|
|
20
|
+
const cuts = new Map<string, Promise<Cut>>()
|
|
21
|
+
const reported = new Set<string>()
|
|
22
|
+
|
|
23
|
+
const cut = async (url: string, glyphs: string): Promise<Cut> => {
|
|
24
|
+
const bytes = await read(url)
|
|
25
|
+
if (!bytes) return undefined
|
|
26
|
+
let result: ReturnType<typeof subsetFont>
|
|
27
|
+
try {
|
|
28
|
+
result = subsetFont(bytes, glyphs)
|
|
29
|
+
} catch {
|
|
30
|
+
return undefined
|
|
31
|
+
}
|
|
32
|
+
if (result.outlines !== "glyf") return { skipped: result.outlines }
|
|
33
|
+
const target = join(
|
|
34
|
+
dir,
|
|
35
|
+
`${basename(url, extname(url))}-${sha256(`${sha256(bytes)}\n${glyphs}`).slice(0, 8)}.woff2`,
|
|
36
|
+
)
|
|
37
|
+
await writeAtomic(target, writeWoff2(result.tables))
|
|
38
|
+
return { path: target }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
subset(family, faces, glyphs) {
|
|
43
|
+
const set = [...new Set(Array.from(glyphs))].sort().join("")
|
|
44
|
+
return Promise.all(
|
|
45
|
+
faces.map(async (face) => {
|
|
46
|
+
for (const entry of face.src) {
|
|
47
|
+
if (!("url" in entry)) continue
|
|
48
|
+
const key = `${entry.url}\n${set}`
|
|
49
|
+
let pending = cuts.get(key)
|
|
50
|
+
if (!pending) cuts.set(key, (pending = cut(entry.url, set)))
|
|
51
|
+
const result = await pending
|
|
52
|
+
if (!result) continue
|
|
53
|
+
if ("skipped" in result) {
|
|
54
|
+
const message =
|
|
55
|
+
result.skipped === "cff"
|
|
56
|
+
? `[fonts] ${family} is CFF; glyphs applies to TrueType outlines only`
|
|
57
|
+
: `[fonts] ${family} is a variable font with gvar; glyphs does not subset it`
|
|
58
|
+
if (!reported.has(message)) {
|
|
59
|
+
reported.add(message)
|
|
60
|
+
report(message)
|
|
61
|
+
}
|
|
62
|
+
return face
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
...face,
|
|
66
|
+
src: [...face.src.filter((source) => !("url" in source)), { url: result.path, format: "woff2" as const }],
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return face
|
|
70
|
+
}),
|
|
71
|
+
)
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/env.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
declare module "#hamur/fonts/preloads" {
|
|
2
|
+
/** The font files each stylesheet of the client manifest asks for, by the stylesheet's URL. */
|
|
3
|
+
const preloads: Record<string, string[]>
|
|
4
|
+
export default preloads
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
declare module "#hamur/fonts/global.css" {}
|
|
8
|
+
|
|
9
|
+
declare module "#hamur/fonts/data" {
|
|
10
|
+
/** The self-hosted files of each resolved family, by the family's name. */
|
|
11
|
+
const data: Record<string, Array<{ src: string; weight: string; style: string; format: string }>>
|
|
12
|
+
export default data
|
|
13
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { FontFaceData, FontProvider, FontsOptions } from "./types.ts"
|
|
2
|
+
|
|
3
|
+
export { default } from "./module.ts"
|
|
4
|
+
export type {
|
|
5
|
+
FontDefaults,
|
|
6
|
+
FontFaceData,
|
|
7
|
+
FontFamilyOptions,
|
|
8
|
+
FontFormat,
|
|
9
|
+
FontProvider,
|
|
10
|
+
FontResolution,
|
|
11
|
+
FontsOptions,
|
|
12
|
+
ResolveFontOptions,
|
|
13
|
+
} from "./types.ts"
|
|
14
|
+
|
|
15
|
+
declare module "hamur" {
|
|
16
|
+
interface HamurModuleOptions {
|
|
17
|
+
fonts?: FontsOptions
|
|
18
|
+
}
|
|
19
|
+
interface HamurHooks {
|
|
20
|
+
/** Once in `modules:done`; add a provider or replace one by name. */
|
|
21
|
+
"fonts:providers": (providers: Record<string, FontProvider>) => void | Promise<void>
|
|
22
|
+
/** A family's faces as written and the absolute paths of their files, once per family. */
|
|
23
|
+
"fonts:resolved": (resolved: { family: string; faces: FontFaceData[]; files: string[] }) => void | Promise<void>
|
|
24
|
+
}
|
|
25
|
+
}
|
package/src/inject.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { fallbackFamily, type FallbackOverrides } from "./build/fallbacks.ts"
|
|
2
|
+
import type { FontFaceData, FontFormat } from "./types.ts"
|
|
3
|
+
|
|
4
|
+
export interface FaceDescriptors {
|
|
5
|
+
display: string
|
|
6
|
+
unicodeRange?: string
|
|
7
|
+
stretch?: string
|
|
8
|
+
featureSettings?: string
|
|
9
|
+
variationSettings?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const CSS_FORMAT: Record<FontFormat, string> = { woff2: "woff2", woff: "woff", ttf: "truetype", otf: "opentype" }
|
|
13
|
+
|
|
14
|
+
export const quote = (text: string): string => `"${text.replace(/[\\"]/g, "\\$&").replace(/\n/g, "\\a ")}"`
|
|
15
|
+
const cssUrl = (url: string): string => (/^[\w\-./%~]+$/.test(url) ? `url(${url})` : `url(${quote(url)})`)
|
|
16
|
+
|
|
17
|
+
/** One `@font-face` rule. A descriptor the family sets (`descriptors`) wins over the provider's. */
|
|
18
|
+
export function fontFaceRule(family: string, face: FontFaceData, descriptors: FaceDescriptors): string {
|
|
19
|
+
const src = face.src.map((entry) =>
|
|
20
|
+
"name" in entry
|
|
21
|
+
? `local(${quote(entry.name)})`
|
|
22
|
+
: `${cssUrl(entry.url)}${entry.format ? ` format(${quote(CSS_FORMAT[entry.format])})` : ""}`,
|
|
23
|
+
)
|
|
24
|
+
const parts = [`font-family: ${quote(family)}`, `src: ${src.join(", ")}`]
|
|
25
|
+
const add = (name: string, value: string | undefined) => {
|
|
26
|
+
if (value !== undefined && value !== "") parts.push(`${name}: ${value}`)
|
|
27
|
+
}
|
|
28
|
+
add("font-weight", face.weight)
|
|
29
|
+
add("font-style", face.style === "normal" ? undefined : face.style)
|
|
30
|
+
add("font-stretch", descriptors.stretch ?? face.stretch)
|
|
31
|
+
add("unicode-range", descriptors.unicodeRange ?? face.unicodeRange)
|
|
32
|
+
add("font-display", descriptors.display)
|
|
33
|
+
add("font-feature-settings", descriptors.featureSettings ?? face.featureSettings)
|
|
34
|
+
add("font-variation-settings", descriptors.variationSettings ?? face.variationSettings)
|
|
35
|
+
return `@font-face { ${parts.join("; ")} }`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const percent = (ratio: number): string => `${Number((ratio * 100).toFixed(4))}%`
|
|
39
|
+
|
|
40
|
+
/** The face `"<Family> Fallback: <System>"`, the installed system font scaled to the web font's metrics. */
|
|
41
|
+
export function fallbackFaceRule(family: string, system: string, overrides: FallbackOverrides): string {
|
|
42
|
+
return `@font-face { font-family: ${quote(fallbackFamily(family, system))}; src: local(${quote(system)}); size-adjust: ${percent(overrides.sizeAdjust)}; ascent-override: ${percent(overrides.ascent)}; descent-override: ${percent(overrides.descent)}; line-gap-override: ${percent(overrides.lineGap)} }`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Puts each `text` into `css` at its `at`, an offset of the original text. */
|
|
46
|
+
export function insertEdits(css: string, edits: Array<{ at: number; text: string }>): string {
|
|
47
|
+
let out = css
|
|
48
|
+
for (const edit of [...edits].sort((a, b) => b.at - a.at))
|
|
49
|
+
out = `${out.slice(0, edit.at)}${edit.text}${out.slice(edit.at)}`
|
|
50
|
+
return out
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Puts `rules` into `css` at `at`, each on its own line. */
|
|
54
|
+
export function insertRules(css: string, at: number, rules: string[]): string {
|
|
55
|
+
if (rules.length === 0) return css
|
|
56
|
+
const head = css.slice(0, at)
|
|
57
|
+
const tail = css.slice(at).replace(/^\r?\n/, "")
|
|
58
|
+
return `${head}${head === "" || head.endsWith("\n") ? "" : "\n"}${rules.join("\n")}\n${tail}`
|
|
59
|
+
}
|
package/src/module.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { existsSync } from "node:fs"
|
|
2
|
+
import { pathToFileURL } from "node:url"
|
|
3
|
+
import { defineModule } from "hamur/kit"
|
|
4
|
+
import { fontsDirOf } from "./build/cache.ts"
|
|
5
|
+
import { setupData } from "./build/data.ts"
|
|
6
|
+
import { setupGlobal } from "./build/global.ts"
|
|
7
|
+
import { createPreloadNames, setupPreload } from "./build/preload.ts"
|
|
8
|
+
import { publicUrlsKept } from "./build/public-url.ts"
|
|
9
|
+
import { setupScan } from "./build/scan.ts"
|
|
10
|
+
import { resolveOptions } from "./options.ts"
|
|
11
|
+
import type { FontsOptions } from "./types.ts"
|
|
12
|
+
|
|
13
|
+
export default defineModule<FontsOptions>({
|
|
14
|
+
meta: { name: "fonts", configKey: "fonts", hooks: ["fonts:providers", "fonts:resolved"] },
|
|
15
|
+
async setup(input, hamur) {
|
|
16
|
+
const options = await resolveOptions(input, {
|
|
17
|
+
rootDir: hamur.options.rootDir,
|
|
18
|
+
exists: existsSync,
|
|
19
|
+
load: async (file) => (await import(pathToFileURL(file).href)).default,
|
|
20
|
+
})
|
|
21
|
+
if (!options.enabled) return
|
|
22
|
+
// A Bun.build started from inside a running build's transform never returns, so the probe runs here.
|
|
23
|
+
await publicUrlsKept()
|
|
24
|
+
const preload = createPreloadNames()
|
|
25
|
+
setupScan(options, hamur, preload, setupData(hamur, fontsDirOf(options.cache, hamur)))
|
|
26
|
+
setupPreload(options, hamur, preload)
|
|
27
|
+
setupGlobal(options)
|
|
28
|
+
},
|
|
29
|
+
})
|