-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcss2.mjs
More file actions
213 lines (193 loc) · 7.87 KB
/
css2.mjs
File metadata and controls
213 lines (193 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
export const css2 = (request, reply, data, domain, subsets, fontCache = {}) => {
try {
let { family: families, display, text } = request.query;
if (families) {
if (typeof families === "string") {
families = [families];
}
const payload = [];
if (text) {
payload.push(`/* Optimized for text: ${decodeURIComponent(text)} */`);
}
for (let family of families) {
let style = "normal";
let weights = ["400"];
let dashFamily = family.toLowerCase().replace(/ /g, "-");
if (family.includes("wght") || family.includes("ital")) {
const params = family.split(":")[1];
if (params?.startsWith("wght@")) {
const weightParam = params.split("@")[1];
const weightSpecs = weightParam.split(";");
weights = [];
for (const spec of weightSpecs) {
if (spec.includes("..")) {
// Handle weight range (e.g., 100..900)
const [start, end] = spec.split("..").map(Number);
const standardWeights = [100, 200, 300, 400, 500, 600, 700, 800, 900];
standardWeights.forEach(weight => {
if (weight >= start && weight <= end) {
weights.push(weight.toString());
}
});
} else {
weights.push(spec);
}
}
} else if (params?.includes("@")) {
// Handle ital,wght@ syntax
const [axes, values] = params.split("@");
const valuesList = values.split(";");
if (axes.includes(",")) {
// Handle combined axes like ital,wght or ital,opsz,wght
// Parse axis names dynamically to support any number of axes
const axisNames = axes.split(",");
const italIndex = axisNames.indexOf("ital");
const wghtIndex = axisNames.indexOf("wght");
weights = [];
for (const value of valuesList) {
if (value.includes(",")) {
const axisValues = value.split(",");
// Get ital value (default to "0" if not present)
const italValue = italIndex >= 0 ? axisValues[italIndex] : "0";
// Get weight value (default to "400" if not present)
const weightValue = wghtIndex >= 0 ? axisValues[wghtIndex] : "400";
if (weightValue?.includes("..")) {
// Handle weight range (e.g., 200..700)
const [start, end] = weightValue.split("..").map(Number);
const standardWeights = [100, 200, 300, 400, 500, 600, 700, 800, 900];
standardWeights.forEach(weight => {
if (weight >= start && weight <= end) {
weights.push(`${italValue},${weight}`);
}
});
} else if (weightValue) {
weights.push(`${italValue},${weightValue}`);
}
} else {
weights.push(value);
}
}
} else {
weights = valuesList.filter((n) => n);
}
}
dashFamily = family.toLowerCase().replace(/ /g, "-")?.split(":")[0];
}
family = family.split(":")[0];
if (dashFamily === 'source-sans-pro') {
dashFamily = 'source-sans-3';
}
// Get subsets for the font from cache or fallback to defaults
const fontSubsets = getSubsetsFromCache(family, dashFamily, fontCache);
if (weights && weights.length > 0) {
for (let weight of weights) {
for (const subset of fontSubsets) {
if (weight.includes(",")) {
style = weight.split(",")[0] === "0" ? "normal" : "italic";
weight = weight.split(",")[1];
} else {
if (weight === "0") {
style = "normal";
weight = "400";
}
if (weight === "1") {
style = "italic";
weight = "400";
}
}
let css = `
/* ${subset} */
@font-face {
font-family: '${family}';
font-style: ${style};
font-weight: ${weight};
font-stretch: 100%;`;
if (display)
css += `
font-display: ${display};`;
let url = `https://${domain}/${dashFamily}/${style}/${weight}-${subset}.woff2`;
if (text) {
url += `?text=${encodeURIComponent(text)}`;
}
css += `
src: url(${url}) format('woff2');
unicode-range: ${subsets[subset] || 'U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD'};
}`;
payload.push(css);
}
}
} else {
// No weights specified, use default
for (const subset of fontSubsets) {
let css = `
/* ${subset} */
@font-face {
font-family: '${family}';
font-style: normal;
font-weight: 400;
font-stretch: 100%;`;
if (display)
css += `
font-display: ${display};`;
let url = `https://${domain}/${dashFamily}/normal/400-${subset}.woff2`;
if (text) {
url += `?text=${encodeURIComponent(text)}`;
}
css += `
src: url(${url}) format('woff2');
unicode-range: ${subsets[subset] || 'U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD'};
}`;
payload.push(css);
}
}
}
reply.header("content-type", "text/css");
reply.send(payload.join(" ").trim());
return reply;
}
throw { statusCode: 500, message: "Wrong request" };
} catch (error) {
throw { statusCode: 500, message: error.message };
}
};
function getSubsetsFromCache(family, dashFamily, fontCache) {
// Try to find font in cache by original family name
const cacheEntry = fontCache[family];
if (cacheEntry && cacheEntry.variants) {
// Get subsets from the first variant that has them
for (const variant of Object.values(cacheEntry.variants)) {
if (variant.subsets && Array.isArray(variant.subsets) && variant.subsets.length > 0) {
return variant.subsets;
}
}
}
// Fall back to hardcoded defaults if no subsets in cache
return getDefaultSubsets(dashFamily);
}
function getDefaultSubsets(dashFamily) {
// Return common subsets for most fonts
// Special cases for known fonts can be added here
const specialCases = {
'roboto': ['cyrillic', 'cyrillic-ext', 'greek', 'greek-ext', 'latin', 'latin-ext', 'math', 'symbols', 'vietnamese'],
'open-sans': ['cyrillic', 'cyrillic-ext', 'greek', 'greek-ext', 'hebrew', 'latin', 'latin-ext', 'math', 'symbols', 'vietnamese'],
'noto-sans-jp': ['cyrillic', 'japanese', 'latin', 'latin-ext', 'vietnamese'],
'noto-sans-kr': ['cyrillic', 'korean', 'latin', 'latin-ext', 'vietnamese'],
'noto-sans-tc': ['chinese-traditional', 'cyrillic', 'latin', 'latin-ext', 'vietnamese'],
'noto-sans-sc': ['chinese-simplified', 'cyrillic', 'latin', 'latin-ext', 'vietnamese'],
'noto-color-emoji': ['emoji'],
'noto-sans': ['cyrillic', 'cyrillic-ext', 'devanagari', 'greek', 'greek-ext', 'latin', 'latin-ext', 'vietnamese'],
'noto-serif': ['cyrillic', 'cyrillic-ext', 'greek', 'greek-ext', 'latin', 'latin-ext', 'math', 'vietnamese']
};
// Common subsets for popular fonts
const commonSubsets = [
'cyrillic',
'cyrillic-ext',
'greek',
'greek-ext',
'latin',
'latin-ext',
'vietnamese'
];
// Return special case if it exists, otherwise return common subsets
return specialCases[dashFamily] || commonSubsets;
}