rainbowindex 0.4.1 → 0.5.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.
@@ -19,393 +19,755 @@ import {
19
19
  renderCSS,
20
20
  scanCSSForTokenUsage,
21
21
  withTimeout
22
- } from "./chunk-6GTG5SZJ.mjs";
22
+ } from "./chunk-PDORZSQX.mjs";
23
23
  import {
24
24
  checkPaletteContrast,
25
25
  generateAllColorVariables,
26
26
  generateThemeOverrides
27
- } from "./chunk-KRZL4IDK.mjs";
27
+ } from "./chunk-4UKFK2GE.mjs";
28
28
 
29
- // src/integrations/font-providers/google/state.ts
30
- var googleFontInternals = {
31
- googleFontState: { cache: /* @__PURE__ */ new Map(), fetched: false },
32
- googleFontListPromise: null,
33
- lastFetchFailureMs: 0,
34
- validatedCacheDir: null,
35
- resolvedCachePath: null
36
- };
29
+ // src/scanner/sources.ts
30
+ import { readFile, stat } from "fs/promises";
31
+ import { resolve as resolve2 } from "path";
32
+ import { glob } from "tinyglobby";
37
33
 
38
- // src/integrations/font-providers/google/cache.ts
39
- import { createHash, randomUUID } from "crypto";
40
- import { open as fsOpen, writeFile, rename, unlink, mkdir } from "fs/promises";
41
- import { resolve, dirname, join, isAbsolute } from "path";
42
- import { isAbsolute as win32IsAbsolute } from "path/win32";
43
- var MAX_FONT_CACHE_TTL_SECONDS = 30 * 24 * 60 * 60;
44
- function getFontCacheDir() {
45
- if (googleFontInternals.validatedCacheDir !== null) return googleFontInternals.validatedCacheDir;
46
- const raw = process.env.RI_CACHE_DIR || "node_modules/.cache/rainbowindex";
47
- if (isAbsolute(raw) || win32IsAbsolute(raw)) {
48
- throw new Error(
49
- `[RI-1208] RI_CACHE_DIR must be a relative path, got absolute path: "${raw}". Use a relative path like "node_modules/.cache/rainbowindex".`
50
- );
51
- }
52
- if (raw.split(/[\\/]/).some((s) => s === "..")) {
53
- throw new Error(
54
- `[RI-1209] RI_CACHE_DIR must not contain ".." segments: "${raw}". Use a direct relative path like "node_modules/.cache/rainbowindex".`
55
- );
56
- }
57
- googleFontInternals.validatedCacheDir = raw;
58
- return raw;
59
- }
60
- function getFontCacheFile() {
61
- return `${getFontCacheDir()}/google.json`;
62
- }
63
- function getResolvedCachePath() {
64
- if (googleFontInternals.resolvedCachePath !== null && googleFontInternals.validatedCacheDir !== null) {
65
- return googleFontInternals.resolvedCachePath;
34
+ // src/scanner/glob-utils.ts
35
+ import { isAbsolute, win32 } from "path";
36
+ function validateGlobPattern(pattern) {
37
+ if (!pattern?.trim()) {
38
+ return "Glob pattern is empty.";
66
39
  }
67
- googleFontInternals.resolvedCachePath = resolve(process.cwd(), getFontCacheFile());
68
- return googleFontInternals.resolvedCachePath;
69
- }
70
- function getFontCacheTTL() {
71
- const envVal = process.env.RI_FONT_CACHE_TTL;
72
- if (envVal) {
73
- const seconds = Number(envVal);
74
- if (!Number.isNaN(seconds) && seconds >= 0) {
75
- if (seconds > MAX_FONT_CACHE_TTL_SECONDS) {
76
- console.warn(
77
- `[RI-1211] RI_FONT_CACHE_TTL=${seconds} exceeds maximum of ${MAX_FONT_CACHE_TTL_SECONDS} seconds (30 days). Clamping to 30 days.`
78
- );
79
- return MAX_FONT_CACHE_TTL_SECONDS * 1e3;
80
- }
81
- return seconds * 1e3;
82
- }
40
+ if (pattern.includes("\0")) {
41
+ return "Glob pattern contains a null byte, which is invalid in file paths.";
83
42
  }
84
- return 7 * 24 * 60 * 60 * 1e3;
85
- }
86
- function parseCachedMetaEntries(raw) {
87
- const parsed = JSON.parse(raw);
88
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !("checksum" in parsed) || !("entries" in parsed)) {
89
- return null;
43
+ if (isAbsolute(pattern) || win32.isAbsolute(pattern)) {
44
+ return `Glob pattern "${pattern}" must be relative, not absolute.`;
90
45
  }
91
- if (!Array.isArray(parsed.entries)) return null;
92
- const entriesJson = JSON.stringify(parsed.entries);
93
- const expected = createHash("sha256").update(entriesJson).digest("hex");
94
- if (typeof parsed.checksum !== "string" || parsed.checksum !== expected) return null;
95
- const entries = parsed.entries;
96
- const newCache = /* @__PURE__ */ new Map();
97
- for (const rawItem of entries) {
98
- if (!rawItem || typeof rawItem !== "object") continue;
99
- const item = rawItem;
100
- if (typeof item.family !== "string" || typeof item.variable !== "boolean" || typeof item.category !== "string" || item.axes !== void 0 && !Array.isArray(item.axes)) {
101
- continue;
46
+ const segments = pattern.split(/[\\/]+/);
47
+ for (const seg of segments) {
48
+ if (seg === "..") {
49
+ return `Glob pattern "${pattern}" must not traverse parent directories (".."). Restructure your project layout so source files are within the project root, or use @source with a pattern rooted at the project directory.`;
102
50
  }
103
- if (!SAFE_FONT_FAMILY_RE.test(item.family)) continue;
104
- const axes = Array.isArray(item.axes) ? item.axes.filter((a) => {
105
- if (!a || typeof a !== "object") return false;
106
- const axis = a;
107
- return typeof axis.tag === "string" && typeof axis.start === "number" && Number.isFinite(axis.start) && typeof axis.end === "number" && Number.isFinite(axis.end);
108
- }).map((a) => {
109
- const axis = { tag: a.tag, start: a.start, end: a.end };
110
- Object.freeze(axis);
111
- return axis;
112
- }) : void 0;
113
- if (axes) Object.freeze(axes);
114
- const entry = {
115
- family: item.family,
116
- variable: item.variable,
117
- axes,
118
- category: item.category
119
- };
120
- Object.freeze(entry);
121
- newCache.set(entry.family, entry);
122
51
  }
123
- return newCache.size > 0 ? newCache : null;
52
+ return null;
124
53
  }
125
- async function loadFontCache(ignoreExpiry = false) {
54
+
55
+ // src/scanner/package-discovery.ts
56
+ import { existsSync, readFileSync, realpathSync, statSync } from "fs";
57
+ import { dirname, join, posix, resolve } from "path";
58
+ var EMPTY = Object.freeze({ sources: [], warnings: [] });
59
+ var discoveryCache = /* @__PURE__ */ new Map();
60
+ function discoverPackageSafelistSources(cwd) {
61
+ const cwdAbs = resolve(cwd);
62
+ let mtimeMs;
126
63
  try {
127
- const cachePath = getResolvedCachePath();
128
- const fh = await fsOpen(cachePath, "r");
129
- let raw;
130
- try {
131
- if (!ignoreExpiry) {
132
- const st = await fh.stat();
133
- if (Date.now() - st.mtimeMs > getFontCacheTTL()) return false;
134
- }
135
- raw = await fh.readFile("utf-8");
136
- } finally {
137
- await fh.close();
138
- }
139
- const newCache = parseCachedMetaEntries(raw);
140
- if (!newCache) return false;
141
- googleFontInternals.googleFontState = { cache: newCache, fetched: true };
142
- return true;
64
+ mtimeMs = statSync(join(cwdAbs, "package.json")).mtimeMs;
143
65
  } catch {
144
- return false;
66
+ return EMPTY;
145
67
  }
68
+ const cached = discoveryCache.get(cwdAbs);
69
+ if (cached && cached.mtimeMs === mtimeMs) return cached.result;
70
+ const result = runDiscovery(cwdAbs);
71
+ discoveryCache.set(cwdAbs, { mtimeMs, result });
72
+ return result;
146
73
  }
147
- async function saveFontCache() {
74
+ function runDiscovery(cwdAbs) {
75
+ let consumer;
148
76
  try {
149
- const cachePath = getResolvedCachePath();
150
- await mkdir(dirname(cachePath), { recursive: true });
151
- const entries = Array.from(googleFontInternals.googleFontState.cache.values());
152
- const entriesJson = JSON.stringify(entries);
153
- const checksum = createHash("sha256").update(entriesJson).digest("hex");
154
- const payload = `{"checksum":${JSON.stringify(checksum)},"entries":${entriesJson}}`;
155
- const tmpPath = join(dirname(cachePath), `.google-${process.pid}-${randomUUID()}.tmp`);
77
+ consumer = readPackageJson(join(cwdAbs, "package.json"));
78
+ } catch {
79
+ return EMPTY;
80
+ }
81
+ const deps = [
82
+ ...Object.keys(consumer.dependencies ?? {}),
83
+ ...Object.keys(consumer.peerDependencies ?? {})
84
+ ];
85
+ if (deps.length === 0) return EMPTY;
86
+ const sources = [];
87
+ const warnings = [];
88
+ for (const depName of deps) {
89
+ const depPkgPath = findDepPackageJson(cwdAbs, depName);
90
+ if (!depPkgPath) {
91
+ continue;
92
+ }
93
+ let depPkg;
156
94
  try {
157
- await writeFile(tmpPath, payload);
158
- await rename(tmpPath, cachePath);
159
- } finally {
160
- await unlink(tmpPath).catch(() => {
161
- });
95
+ depPkg = readPackageJson(depPkgPath);
96
+ } catch (err) {
97
+ warnings.push(
98
+ `[RI-1410] Could not read ${depName}/package.json during safelist discovery: ${errMessage(err)}`
99
+ );
100
+ continue;
101
+ }
102
+ const patterns = depPkg.rainbowindex?.safelistSources;
103
+ if (patterns == null) continue;
104
+ if (!Array.isArray(patterns)) {
105
+ warnings.push(
106
+ `[RI-1410] Invalid rainbowindex.safelistSources in ${depName} \u2014 expected an array of glob strings.`
107
+ );
108
+ continue;
109
+ }
110
+ if (patterns.length === 0) continue;
111
+ const depRoot = realpathOrFallback(dirname(depPkgPath)).replace(/\\/g, "/");
112
+ for (const pattern of patterns) {
113
+ if (typeof pattern !== "string" || !pattern) {
114
+ warnings.push(
115
+ `[RI-1410] Invalid rainbowindex.safelistSources entry in ${depName} \u2014 expected a non-empty glob string.`
116
+ );
117
+ continue;
118
+ }
119
+ if (validateGlobPattern(pattern) !== null) {
120
+ warnings.push(
121
+ `[RI-1410] Invalid rainbowindex.safelistSources entry "${pattern}" in ${depName} \u2014 patterns must be relative to the package root and must not traverse parent directories.`
122
+ );
123
+ continue;
124
+ }
125
+ const absolute = posix.normalize(`${depRoot}/${pattern.replace(/^\.\//, "")}`);
126
+ if (absolute !== depRoot && !absolute.startsWith(`${depRoot}/`)) {
127
+ warnings.push(
128
+ `[RI-1410] Invalid rainbowindex.safelistSources entry "${pattern}" in ${depName} \u2014 resolved outside the package root.`
129
+ );
130
+ continue;
131
+ }
132
+ sources.push({ pattern: absolute, negated: false, inline: false, absolute: true });
162
133
  }
163
- } catch (err) {
164
- const reason = err instanceof Error ? err.message : String(err);
165
- console.warn(
166
- `[RI-1210] Failed to write font cache to ${getFontCacheFile()}: ${reason}. Each build will fetch from Google Fonts. Set RI_CACHE_DIR to a writable path or use RI_OFFLINE=1 with a pre-populated cache.`
167
- );
168
134
  }
135
+ return { sources, warnings };
169
136
  }
170
-
171
- // src/integrations/font-providers/google/client.ts
172
- var MAX_RESPONSE_SIZE = 10 * 1024 * 1024;
173
- var MAX_RETRIES = 2;
174
- var FETCH_TIMEOUT_MS = 5e3;
175
- function wait(ms) {
176
- return new Promise((resolve4) => setTimeout(resolve4, ms));
137
+ function readPackageJson(path) {
138
+ const raw = readFileSync(path, "utf8");
139
+ return JSON.parse(raw);
177
140
  }
178
- function toGoogleFontMetaMap(data) {
179
- const newCache = /* @__PURE__ */ new Map();
180
- for (const font of data.familyMetadataList) {
181
- const wghtAxis = font.axes.find((a) => a.tag === "wght");
182
- const axes = font.axes.map((a) => {
183
- const axis = { tag: a.tag, start: a.min, end: a.max };
184
- Object.freeze(axis);
185
- return axis;
186
- });
187
- Object.freeze(axes);
188
- const entry = {
189
- family: font.family,
190
- variable: wghtAxis ? wghtAxis.min !== wghtAxis.max : false,
191
- axes,
192
- category: font.category
193
- };
194
- Object.freeze(entry);
195
- newCache.set(font.family, entry);
141
+ function findDepPackageJson(cwd, depName) {
142
+ let dir = cwd;
143
+ while (true) {
144
+ const candidate = join(dir, "node_modules", depName, "package.json");
145
+ if (existsSync(candidate)) return candidate;
146
+ const parent = dirname(dir);
147
+ if (parent === dir) return null;
148
+ dir = parent;
196
149
  }
197
- return newCache;
198
150
  }
199
- async function readJsonResponse(res) {
200
- const reader = res.body?.getReader();
201
- if (!reader) {
202
- throw new Error("[RI-1207] Google Fonts metadata response has no readable body.");
151
+ function realpathOrFallback(path) {
152
+ try {
153
+ return realpathSync(path);
154
+ } catch {
155
+ return path;
203
156
  }
204
- const chunks = [];
205
- let totalBytes = 0;
206
- for (; ; ) {
207
- const { done, value } = await reader.read();
208
- if (done) break;
209
- totalBytes += value.byteLength;
210
- if (totalBytes > MAX_RESPONSE_SIZE) {
211
- reader.cancel();
212
- throw new Error(
213
- `[RI-1207] Google Fonts metadata response too large (>${MAX_RESPONSE_SIZE} bytes).`
214
- );
215
- }
216
- chunks.push(value);
217
- }
218
- const text = new TextDecoder().decode(
219
- chunks.length === 1 ? chunks[0] : await new Blob(chunks).arrayBuffer()
220
- );
221
- return JSON.parse(text);
222
157
  }
223
- async function fetchGoogleFontMetadata() {
224
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
225
- const controller = new AbortController();
226
- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
227
- try {
228
- const res = await fetch("https://fonts.google.com/metadata/fonts", {
229
- signal: controller.signal
230
- });
231
- const contentLength = res.headers.get("content-length");
232
- if (contentLength && Number(contentLength) > MAX_RESPONSE_SIZE) {
233
- throw new Error(
234
- `[RI-1207] Google Fonts metadata response too large (${contentLength} bytes).`
235
- );
236
- }
237
- if (!res.ok) {
238
- throw new Error(`[RI-1205] Google Fonts metadata request failed with HTTP ${res.status}.`);
239
- }
240
- const contentType = res.headers.get("content-type") ?? "";
241
- if (contentType && !contentType.includes("json")) {
242
- throw new Error(
243
- `[RI-1207] Google Fonts metadata returned unexpected Content-Type "${contentType}" instead of JSON.`
244
- );
245
- }
246
- const data = await readJsonResponse(res);
247
- return toGoogleFontMetaMap(data);
248
- } catch (err) {
249
- if (attempt < MAX_RETRIES) {
250
- await wait(1e3 * 2 ** attempt);
158
+ function errMessage(err) {
159
+ return err instanceof Error ? err.message : String(err);
160
+ }
161
+
162
+ // src/scanner/sources.ts
163
+ var DEFAULT_PATTERNS = Object.freeze([
164
+ "*.html",
165
+ "src/**/*.{html,js,jsx,ts,tsx,mdx,vue,svelte}"
166
+ ]);
167
+ var DEFAULT_EXCLUDES = Object.freeze([
168
+ "node_modules/**",
169
+ "dist/**",
170
+ "build/**",
171
+ "coverage/**",
172
+ "public/**",
173
+ "**/*.config.*",
174
+ "**/*.d.ts"
175
+ ]);
176
+ var MAX_FILE_SIZE = 1048576;
177
+ var MAX_INLINE_SOURCE_SIZE = 102400;
178
+ var GLOB_TIMEOUT_MS = 3e4;
179
+ var GLOB_TIMEOUT_MESSAGE = `glob() timed out after ${GLOB_TIMEOUT_MS / 1e3}s \u2014 check for network filesystem issues or overly broad @source patterns`;
180
+ var SOURCE_LIST_CACHE_MAX_ENTRIES = 50;
181
+ var sourceListCacheEnabled = false;
182
+ var sourceListCache = /* @__PURE__ */ new Map();
183
+ var sourceListCacheGeneration = 0;
184
+ function enableSourceFileListCache() {
185
+ sourceListCacheEnabled = true;
186
+ }
187
+ function invalidateSourceFileListCache() {
188
+ sourceListCacheGeneration++;
189
+ sourceListCache.clear();
190
+ }
191
+ function collectPatterns(sources) {
192
+ const includePatterns = [];
193
+ const nodeModulesIncludePatterns = [];
194
+ const excludePatterns = [...DEFAULT_EXCLUDES];
195
+ const hasUserPositiveGlobs = sources.some((s) => !s.inline && !s.negated && !s.absolute);
196
+ if (!hasUserPositiveGlobs) {
197
+ includePatterns.push(...DEFAULT_PATTERNS);
198
+ }
199
+ const warnings = [];
200
+ for (const src of sources) {
201
+ if (src.inline) continue;
202
+ if (!src.absolute) {
203
+ const err = validateGlobPattern(src.pattern);
204
+ if (err) {
205
+ warnings.push(`[RI-1404] @source pattern rejected: ${err}`);
251
206
  continue;
252
207
  }
253
- throw err;
254
- } finally {
255
- clearTimeout(timeout);
208
+ }
209
+ if (src.negated) {
210
+ excludePatterns.push(src.pattern);
211
+ } else if (src.absolute || src.pattern.replace(/^\.\//, "").startsWith("node_modules/")) {
212
+ nodeModulesIncludePatterns.push(src.pattern);
213
+ } else {
214
+ includePatterns.push(src.pattern);
256
215
  }
257
216
  }
258
- throw new Error("[RI-1205] Exhausted Google Fonts metadata fetch retries.");
217
+ return {
218
+ includePatterns,
219
+ nodeModulesIncludePatterns,
220
+ excludePatterns,
221
+ warnings,
222
+ hasUserPositiveGlobs
223
+ };
259
224
  }
260
-
261
- // src/integrations/font-providers/google/index.ts
262
- var FETCH_RETRY_COOLDOWN_MS = 3e4;
263
- async function fetchGoogleFontList() {
264
- if (googleFontInternals.googleFontState.fetched) return;
265
- if (googleFontInternals.googleFontListPromise) return googleFontInternals.googleFontListPromise;
266
- if (googleFontInternals.lastFetchFailureMs > 0 && Date.now() - googleFontInternals.lastFetchFailureMs < FETCH_RETRY_COOLDOWN_MS) {
267
- return;
268
- }
269
- const localPromise = (async () => {
270
- try {
271
- const isOffline = process.env.RI_OFFLINE === "1" || process.env.RI_OFFLINE === "true";
272
- if (isOffline) {
273
- if (await loadFontCache(true)) return;
274
- console.warn(
275
- `[RI-1206] RI_OFFLINE is set but no local font cache found at ${getFontCacheFile()}. Run once with network access to populate it. Non-variable fonts will default to weight "100 900" and may produce broken Google Fonts URLs \u2014 set an explicit weight in the @font directive to avoid this.`
276
- );
277
- return;
278
- }
279
- if (await loadFontCache()) return;
280
- const fetchDisabled = process.env.RI_FETCH_FONTS === "0" || process.env.RI_FETCH_FONTS === "false";
281
- if (fetchDisabled) {
282
- if (await loadFontCache(true)) return;
283
- return;
284
- }
285
- if (typeof globalThis.fetch !== "function") {
286
- console.warn(
287
- "[RI-1212] Global fetch() is not available. Google Fonts metadata requires Node.js >= 18. Skipping font fetch."
225
+ async function resolveSourceFilesAsync(sources, cwd, hasInlineClasses = false) {
226
+ const {
227
+ includePatterns,
228
+ nodeModulesIncludePatterns,
229
+ excludePatterns,
230
+ warnings,
231
+ hasUserPositiveGlobs
232
+ } = collectPatterns(sources);
233
+ const allIncludes = [...includePatterns, ...nodeModulesIncludePatterns];
234
+ if (allIncludes.length === 0) return { files: [], warnings };
235
+ const cacheKey = sourceListCacheEnabled ? [
236
+ cwd,
237
+ includePatterns.join("\0"),
238
+ nodeModulesIncludePatterns.join("\0"),
239
+ excludePatterns.join("\0")
240
+ ].join("") : null;
241
+ try {
242
+ const generationAtStart = sourceListCacheGeneration;
243
+ let files = cacheKey !== null ? sourceListCache.get(cacheKey) : void 0;
244
+ if (files === void 0) {
245
+ const globPasses = [];
246
+ if (includePatterns.length > 0) {
247
+ globPasses.push(
248
+ withTimeout(
249
+ glob(includePatterns, { cwd, ignore: excludePatterns }),
250
+ GLOB_TIMEOUT_MS,
251
+ GLOB_TIMEOUT_MESSAGE
252
+ )
288
253
  );
289
- return;
290
- }
291
- if (isRIDebug()) {
292
- console.warn("[RI-DEBUG] Fetching Google Fonts metadata...");
293
254
  }
294
- try {
295
- const newCache = await fetchGoogleFontMetadata();
296
- googleFontInternals.googleFontState = { cache: newCache, fetched: true };
297
- await saveFontCache();
298
- return;
299
- } catch (err) {
300
- const message = err instanceof Error ? err.message : String(err);
301
- if (message.startsWith("[RI-1207]")) {
302
- console.warn(`${message} Skipping.`);
303
- if (await loadFontCache(true)) return;
304
- return;
305
- }
306
- if (await loadFontCache(true)) return;
307
- console.warn(
308
- `[RI-1205] Could not fetch Google Fonts metadata after 3 attempts (${message}). Fonts without explicit weight/style will default to "100 900" + "normal italic" \u2014 non-variable fonts may produce broken Google Fonts URLs. Run with network access to populate the metadata cache, or set an explicit weight/style in the @font directive.`
255
+ if (nodeModulesIncludePatterns.length > 0) {
256
+ const relaxedExcludes = excludePatterns.filter((p) => p !== "node_modules/**");
257
+ globPasses.push(
258
+ withTimeout(
259
+ glob(nodeModulesIncludePatterns, { cwd, ignore: relaxedExcludes }),
260
+ GLOB_TIMEOUT_MS,
261
+ GLOB_TIMEOUT_MESSAGE
262
+ )
309
263
  );
310
264
  }
311
- } finally {
312
- if (!googleFontInternals.googleFontState.fetched) {
313
- googleFontInternals.lastFetchFailureMs = Date.now();
265
+ const matched = (await Promise.all(globPasses)).flat();
266
+ files = [...new Set(matched.map((f) => resolve2(cwd, f)))].sort(codepointCompare);
267
+ if (cacheKey !== null && sourceListCacheGeneration === generationAtStart) {
268
+ if (sourceListCache.size >= SOURCE_LIST_CACHE_MAX_ENTRIES) sourceListCache.clear();
269
+ sourceListCache.set(cacheKey, files);
314
270
  }
315
- googleFontInternals.googleFontListPromise = null;
316
271
  }
317
- })();
318
- googleFontInternals.googleFontListPromise = localPromise;
319
- return localPromise;
320
- }
321
- var refreshMemo = /* @__PURE__ */ new WeakMap();
322
- function refreshFontWeightDefaults(fonts) {
323
- const state = googleFontInternals.googleFontState;
324
- const memo = refreshMemo.get(fonts);
325
- if (memo && memo.state === state) return memo.result;
326
- let anyChanged = false;
327
- const refreshed = fonts.map((slot) => {
328
- if (slot.kind !== "google") return slot;
329
- const meta = googleFontInternals.googleFontState.cache.get(slot.family);
330
- if (!meta) return slot;
331
- let changed = false;
332
- const faces = slot.faces.map((f) => {
333
- let next = f;
334
- if (!f._weightExplicit) {
335
- const wghtAxis = meta.axes?.find((a) => a.tag === "wght");
336
- const axisWeight = wghtAxis && wghtAxis.start !== wghtAxis.end ? `${wghtAxis.start} ${wghtAxis.end}` : "400";
337
- if (next.weight !== axisWeight) next = { ...next, weight: axisWeight };
338
- }
339
- if (!f._styleExplicit) {
340
- const italAxis = meta.axes?.find((a) => a.tag === "ital");
341
- const axisStyle = italAxis ? "normal italic" : "normal";
342
- if (next.style !== axisStyle) next = { ...next, style: axisStyle };
343
- }
344
- if (next !== f) changed = true;
345
- return next;
346
- });
347
- if (changed) anyChanged = true;
348
- return changed ? { ...slot, faces } : slot;
349
- });
350
- const result = anyChanged ? refreshed : fonts;
351
- refreshMemo.set(fonts, { state, result });
352
- return result;
353
- }
354
- var FONT_FETCH_TIMEOUT_MS = 1e4;
355
- async function resolveGoogleFonts(fonts) {
356
- if (!fonts.some((slot) => slot.kind === "google")) return fonts;
357
- try {
358
- await withTimeout(
359
- fetchGoogleFontList(),
360
- FONT_FETCH_TIMEOUT_MS,
361
- "[RI-1213] Google Fonts metadata fetch timed out"
362
- );
363
- } catch {
364
- console.warn(
365
- `[RI-1213] Could not fetch Google Fonts metadata within ${FONT_FETCH_TIMEOUT_MS / 1e3}s \u2014 proceeding with default font weights. Variable-weight fonts may use "400" instead of their full range.`
272
+ if (files.length === 0 && !(hasInlineClasses && !hasUserPositiveGlobs)) {
273
+ warnings.push(
274
+ `[RI-1401] No source files found matching ${allIncludes.map((p) => `"${p}"`).join(", ")} \u2014 check @source paths or project structure.`
275
+ );
276
+ }
277
+ return { files, warnings };
278
+ } catch (err) {
279
+ warnings.push(
280
+ `[RI-1402] Invalid glob pattern \u2014 skipping. Check @source syntax. (${err instanceof Error ? err.message : String(err)})`
366
281
  );
282
+ return { files: [], warnings };
367
283
  }
368
- return refreshFontWeightDefaults(fonts);
369
284
  }
370
-
371
- // src/integrations/font-providers/metrics-data.ts
372
- var FONT_METRICS_TABLE = {
373
- abel: [2006, -604, 0, 2048, 783, "sans-serif"],
374
- alegreya: [1016, -345, 0, 1e3, 410, "serif"],
375
- "anonymous pro": [1675, -373, 0, 2048, 1118, "monospace"],
376
- archivo: [878, -210, 0, 1e3, 440, "sans-serif"],
377
- arial: [1854, -434, 67, 2048, 913, "sans-serif"],
378
- asap: [934, -212, 0, 1e3, 442, "sans-serif"],
379
- barlow: [1e3, -200, 0, 1e3, 431, "sans-serif"],
380
- bitter: [935, -265, 0, 1e3, 465, "serif"],
381
- "bricolage grotesque": [930, -270, 0, 1e3, 470, "sans-serif"],
382
- cabin: [1930, -500, 0, 2e3, 844, "sans-serif"],
383
- catamaran: [1100, -540, 0, 1e3, 411, "sans-serif"],
384
- chivo: [940, -250, 0, 1e3, 478, "sans-serif"],
385
- "cormorant garamond": [924, -287, 0, 1e3, 394, "serif"],
386
- "courier new": [1705, -615, 0, 2048, 1229, "monospace"],
387
- "crimson pro": [918, -220, 0, 1024, 410, "serif"],
388
- "crimson text": [972, -359, 0, 1024, 405, "serif"],
389
- "dm sans": [992, -310, 0, 1e3, 466, "sans-serif"],
390
- "dm serif display": [1036, -335, 0, 1e3, 446, "serif"],
391
- dosis: [1027, -237, 0, 1e3, 377, "sans-serif"],
392
- "eb garamond": [1007, -298, 0, 1e3, 385, "serif"],
393
- epilogue: [1580, -470, 0, 2e3, 990, "sans-serif"],
394
- "exo 2": [999, -201, 0, 1e3, 455, "sans-serif"],
395
- figtree: [950, -250, 0, 1e3, 449, "sans-serif"],
396
- "fira code": [1980, -644, 0, 2e3, 1200, "monospace"],
397
- "fira sans": [935, -265, 0, 1e3, 458, "sans-serif"],
398
- fraunces: [1956, -510, 0, 2e3, 938, "serif"],
399
- gabarito: [940, -260, 0, 1e3, 442, "display"],
400
- "geist mono": [1005, -295, 0, 1e3, 600, "monospace"],
401
- geist: [1005, -295, 0, 1e3, 467, "sans-serif"],
402
- georgia: [1878, -449, 0, 2048, 913, "serif"],
403
- heebo: [2146, -862, 0, 2048, 912, "sans-serif"],
404
- "helvetica neue": [952, -213, 28, 1e3, 450, "sans-serif"],
405
- helvetica: [1577, -471, 0, 2048, 913, "sans-serif"],
406
- hind: [1055, -546, 0, 1e3, 429, "sans-serif"],
407
- "ibm plex mono": [1025, -275, 0, 1e3, 600, "monospace"],
408
- "ibm plex sans": [1025, -275, 0, 1e3, 451, "sans-serif"],
285
+ function collectInlineClasses(sources) {
286
+ const classes = /* @__PURE__ */ new Set();
287
+ const warnings = [];
288
+ for (const src of sources) {
289
+ if (!src.inline) continue;
290
+ const items = src.classes ?? [];
291
+ let contentLength = 0;
292
+ for (const cls of items) contentLength += cls.length;
293
+ if (contentLength > MAX_INLINE_SOURCE_SIZE) {
294
+ warnings.push(
295
+ `[RI-1406] Inline @source content exceeds ${MAX_INLINE_SOURCE_SIZE} byte limit (${contentLength} bytes) \u2014 skipping.`
296
+ );
297
+ continue;
298
+ }
299
+ for (const cls of items) {
300
+ if (cls) classes.add(cls);
301
+ }
302
+ }
303
+ return { classes, warnings };
304
+ }
305
+ var FILE_IO_TIMEOUT_MS = 1e4;
306
+ var SCAN_CACHE_MAX_ENTRIES = 2e4;
307
+ var scanCache = /* @__PURE__ */ new Map();
308
+ async function scanOneFile(file) {
309
+ const warnings = [];
310
+ try {
311
+ const stats = await withTimeout(stat(file), FILE_IO_TIMEOUT_MS, "stat() timed out");
312
+ const cached = scanCache.get(file);
313
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
314
+ return cached.result;
315
+ }
316
+ let result;
317
+ if (stats.size > MAX_FILE_SIZE) {
318
+ result = {
319
+ classes: null,
320
+ warnings,
321
+ failure: `[RI-1405] Skipping source file "${file}" (${stats.size} bytes) \u2014 exceeds ${MAX_FILE_SIZE} byte limit.`
322
+ };
323
+ } else {
324
+ const content = await withTimeout(
325
+ readFile(file, "utf-8"),
326
+ FILE_IO_TIMEOUT_MS,
327
+ "readFile() timed out"
328
+ );
329
+ result = {
330
+ classes: extractClassesFromSource({ path: file, content }, warnings),
331
+ warnings,
332
+ failure: null
333
+ };
334
+ }
335
+ if (scanCache.size >= SCAN_CACHE_MAX_ENTRIES) scanCache.clear();
336
+ scanCache.set(file, { mtimeMs: stats.mtimeMs, size: stats.size, result });
337
+ return result;
338
+ } catch (err) {
339
+ return {
340
+ classes: null,
341
+ warnings,
342
+ failure: `[RI-1403] Could not read source file "${file}" \u2014 skipping. (${err instanceof Error ? err.message : String(err)})`
343
+ };
344
+ }
345
+ }
346
+ async function scanSourceFilesAsync(sources, cwd) {
347
+ const { classes: allClasses, warnings: inlineWarnings } = collectInlineClasses(sources);
348
+ const authored = new Set(allClasses);
349
+ const allWarnings = [...inlineWarnings];
350
+ const { files, warnings: resolveWarnings } = await resolveSourceFilesAsync(
351
+ sources,
352
+ cwd,
353
+ allClasses.size > 0
354
+ );
355
+ allWarnings.push(...resolveWarnings);
356
+ const CONCURRENCY_LIMIT = 32;
357
+ const results = new Array(files.length);
358
+ let nextIndex = 0;
359
+ const worker = async () => {
360
+ while (nextIndex < files.length) {
361
+ const index = nextIndex++;
362
+ results[index] = await scanOneFile(files[index]);
363
+ }
364
+ };
365
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY_LIMIT, files.length) }, worker));
366
+ const seen = new Set(allWarnings);
367
+ for (const result of results) {
368
+ if (result.failure) {
369
+ allWarnings.push(result.failure);
370
+ seen.add(result.failure);
371
+ continue;
372
+ }
373
+ if (result.classes) {
374
+ for (const cls of result.classes) {
375
+ allClasses.add(cls);
376
+ }
377
+ }
378
+ pushWarningsDeduped(allWarnings, result.warnings, seen);
379
+ }
380
+ return { classes: allClasses, authored, warnings: allWarnings };
381
+ }
382
+ async function collectProjectClasses(themeSources, surfaceSources, cwd, warnings, warningSeen) {
383
+ const discovered = discoverPackageSafelistSources(cwd);
384
+ pushWarningsDeduped(warnings, discovered.warnings, warningSeen);
385
+ const allSources = [...themeSources, ...surfaceSources, ...discovered.sources];
386
+ const scanResult = await scanSourceFilesAsync(allSources, cwd);
387
+ pushWarningsDeduped(warnings, scanResult.warnings, warningSeen);
388
+ return { classes: scanResult.classes, authored: scanResult.authored };
389
+ }
390
+
391
+ // src/integrations/font-providers/google/state.ts
392
+ var googleFontInternals = {
393
+ googleFontState: { cache: /* @__PURE__ */ new Map(), fetched: false },
394
+ googleFontListPromise: null,
395
+ lastFetchFailureMs: 0,
396
+ validatedCacheDir: null,
397
+ resolvedCachePath: null
398
+ };
399
+
400
+ // src/integrations/font-providers/google/cache.ts
401
+ import { createHash, randomUUID } from "crypto";
402
+ import { open as fsOpen, writeFile, rename, unlink, mkdir } from "fs/promises";
403
+ import { resolve as resolve3, dirname as dirname2, join as join2, isAbsolute as isAbsolute2 } from "path";
404
+ import { isAbsolute as win32IsAbsolute } from "path/win32";
405
+ var MAX_FONT_CACHE_TTL_SECONDS = 30 * 24 * 60 * 60;
406
+ function getFontCacheDir() {
407
+ if (googleFontInternals.validatedCacheDir !== null) return googleFontInternals.validatedCacheDir;
408
+ const raw = process.env.RI_CACHE_DIR || "node_modules/.cache/rainbowindex";
409
+ if (isAbsolute2(raw) || win32IsAbsolute(raw)) {
410
+ throw new Error(
411
+ `[RI-1208] RI_CACHE_DIR must be a relative path, got absolute path: "${raw}". Use a relative path like "node_modules/.cache/rainbowindex".`
412
+ );
413
+ }
414
+ if (raw.split(/[\\/]/).some((s) => s === "..")) {
415
+ throw new Error(
416
+ `[RI-1209] RI_CACHE_DIR must not contain ".." segments: "${raw}". Use a direct relative path like "node_modules/.cache/rainbowindex".`
417
+ );
418
+ }
419
+ googleFontInternals.validatedCacheDir = raw;
420
+ return raw;
421
+ }
422
+ function getFontCacheFile() {
423
+ return `${getFontCacheDir()}/google.json`;
424
+ }
425
+ function getResolvedCachePath() {
426
+ if (googleFontInternals.resolvedCachePath !== null && googleFontInternals.validatedCacheDir !== null) {
427
+ return googleFontInternals.resolvedCachePath;
428
+ }
429
+ googleFontInternals.resolvedCachePath = resolve3(process.cwd(), getFontCacheFile());
430
+ return googleFontInternals.resolvedCachePath;
431
+ }
432
+ function getFontCacheTTL() {
433
+ const envVal = process.env.RI_FONT_CACHE_TTL;
434
+ if (envVal) {
435
+ const seconds = Number(envVal);
436
+ if (!Number.isNaN(seconds) && seconds >= 0) {
437
+ if (seconds > MAX_FONT_CACHE_TTL_SECONDS) {
438
+ console.warn(
439
+ `[RI-1211] RI_FONT_CACHE_TTL=${seconds} exceeds maximum of ${MAX_FONT_CACHE_TTL_SECONDS} seconds (30 days). Clamping to 30 days.`
440
+ );
441
+ return MAX_FONT_CACHE_TTL_SECONDS * 1e3;
442
+ }
443
+ return seconds * 1e3;
444
+ }
445
+ }
446
+ return 7 * 24 * 60 * 60 * 1e3;
447
+ }
448
+ function parseCachedMetaEntries(raw) {
449
+ const parsed = JSON.parse(raw);
450
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !("checksum" in parsed) || !("entries" in parsed)) {
451
+ return null;
452
+ }
453
+ if (!Array.isArray(parsed.entries)) return null;
454
+ const entriesJson = JSON.stringify(parsed.entries);
455
+ const expected = createHash("sha256").update(entriesJson).digest("hex");
456
+ if (typeof parsed.checksum !== "string" || parsed.checksum !== expected) return null;
457
+ const entries = parsed.entries;
458
+ const newCache = /* @__PURE__ */ new Map();
459
+ for (const rawItem of entries) {
460
+ if (!rawItem || typeof rawItem !== "object") continue;
461
+ const item = rawItem;
462
+ if (typeof item.family !== "string" || typeof item.variable !== "boolean" || typeof item.category !== "string" || item.axes !== void 0 && !Array.isArray(item.axes)) {
463
+ continue;
464
+ }
465
+ if (!SAFE_FONT_FAMILY_RE.test(item.family)) continue;
466
+ const axes = Array.isArray(item.axes) ? item.axes.filter((a) => {
467
+ if (!a || typeof a !== "object") return false;
468
+ const axis = a;
469
+ return typeof axis.tag === "string" && typeof axis.start === "number" && Number.isFinite(axis.start) && typeof axis.end === "number" && Number.isFinite(axis.end);
470
+ }).map((a) => {
471
+ const axis = { tag: a.tag, start: a.start, end: a.end };
472
+ Object.freeze(axis);
473
+ return axis;
474
+ }) : void 0;
475
+ if (axes) Object.freeze(axes);
476
+ const entry = {
477
+ family: item.family,
478
+ variable: item.variable,
479
+ axes,
480
+ category: item.category
481
+ };
482
+ Object.freeze(entry);
483
+ newCache.set(entry.family, entry);
484
+ }
485
+ return newCache.size > 0 ? newCache : null;
486
+ }
487
+ async function loadFontCache(ignoreExpiry = false) {
488
+ try {
489
+ const cachePath = getResolvedCachePath();
490
+ const fh = await fsOpen(cachePath, "r");
491
+ let raw;
492
+ try {
493
+ if (!ignoreExpiry) {
494
+ const st = await fh.stat();
495
+ if (Date.now() - st.mtimeMs > getFontCacheTTL()) return false;
496
+ }
497
+ raw = await fh.readFile("utf-8");
498
+ } finally {
499
+ await fh.close();
500
+ }
501
+ const newCache = parseCachedMetaEntries(raw);
502
+ if (!newCache) return false;
503
+ googleFontInternals.googleFontState = { cache: newCache, fetched: true };
504
+ return true;
505
+ } catch {
506
+ return false;
507
+ }
508
+ }
509
+ async function saveFontCache() {
510
+ try {
511
+ const cachePath = getResolvedCachePath();
512
+ await mkdir(dirname2(cachePath), { recursive: true });
513
+ const entries = Array.from(googleFontInternals.googleFontState.cache.values());
514
+ const entriesJson = JSON.stringify(entries);
515
+ const checksum = createHash("sha256").update(entriesJson).digest("hex");
516
+ const payload = `{"checksum":${JSON.stringify(checksum)},"entries":${entriesJson}}`;
517
+ const tmpPath = join2(dirname2(cachePath), `.google-${process.pid}-${randomUUID()}.tmp`);
518
+ try {
519
+ await writeFile(tmpPath, payload);
520
+ await rename(tmpPath, cachePath);
521
+ } finally {
522
+ await unlink(tmpPath).catch(() => {
523
+ });
524
+ }
525
+ } catch (err) {
526
+ const reason = err instanceof Error ? err.message : String(err);
527
+ console.warn(
528
+ `[RI-1210] Failed to write font cache to ${getFontCacheFile()}: ${reason}. Each build will fetch from Google Fonts. Set RI_CACHE_DIR to a writable path or use RI_OFFLINE=1 with a pre-populated cache.`
529
+ );
530
+ }
531
+ }
532
+
533
+ // src/integrations/font-providers/google/client.ts
534
+ var MAX_RESPONSE_SIZE = 10 * 1024 * 1024;
535
+ var MAX_RETRIES = 2;
536
+ var FETCH_TIMEOUT_MS = 5e3;
537
+ function wait(ms) {
538
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
539
+ }
540
+ function toGoogleFontMetaMap(data) {
541
+ const newCache = /* @__PURE__ */ new Map();
542
+ for (const font of data.familyMetadataList) {
543
+ const wghtAxis = font.axes.find((a) => a.tag === "wght");
544
+ const axes = font.axes.map((a) => {
545
+ const axis = { tag: a.tag, start: a.min, end: a.max };
546
+ Object.freeze(axis);
547
+ return axis;
548
+ });
549
+ Object.freeze(axes);
550
+ const entry = {
551
+ family: font.family,
552
+ variable: wghtAxis ? wghtAxis.min !== wghtAxis.max : false,
553
+ axes,
554
+ category: font.category
555
+ };
556
+ Object.freeze(entry);
557
+ newCache.set(font.family, entry);
558
+ }
559
+ return newCache;
560
+ }
561
+ async function readJsonResponse(res) {
562
+ const reader = res.body?.getReader();
563
+ if (!reader) {
564
+ throw new Error("[RI-1207] Google Fonts metadata response has no readable body.");
565
+ }
566
+ const chunks = [];
567
+ let totalBytes = 0;
568
+ for (; ; ) {
569
+ const { done, value } = await reader.read();
570
+ if (done) break;
571
+ totalBytes += value.byteLength;
572
+ if (totalBytes > MAX_RESPONSE_SIZE) {
573
+ reader.cancel();
574
+ throw new Error(
575
+ `[RI-1207] Google Fonts metadata response too large (>${MAX_RESPONSE_SIZE} bytes).`
576
+ );
577
+ }
578
+ chunks.push(value);
579
+ }
580
+ const text = new TextDecoder().decode(
581
+ chunks.length === 1 ? chunks[0] : await new Blob(chunks).arrayBuffer()
582
+ );
583
+ return JSON.parse(text);
584
+ }
585
+ async function fetchGoogleFontMetadata() {
586
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
587
+ const controller = new AbortController();
588
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
589
+ try {
590
+ const res = await fetch("https://fonts.google.com/metadata/fonts", {
591
+ signal: controller.signal
592
+ });
593
+ const contentLength = res.headers.get("content-length");
594
+ if (contentLength && Number(contentLength) > MAX_RESPONSE_SIZE) {
595
+ throw new Error(
596
+ `[RI-1207] Google Fonts metadata response too large (${contentLength} bytes).`
597
+ );
598
+ }
599
+ if (!res.ok) {
600
+ throw new Error(`[RI-1205] Google Fonts metadata request failed with HTTP ${res.status}.`);
601
+ }
602
+ const contentType = res.headers.get("content-type") ?? "";
603
+ if (contentType && !contentType.includes("json")) {
604
+ throw new Error(
605
+ `[RI-1207] Google Fonts metadata returned unexpected Content-Type "${contentType}" instead of JSON.`
606
+ );
607
+ }
608
+ const data = await readJsonResponse(res);
609
+ return toGoogleFontMetaMap(data);
610
+ } catch (err) {
611
+ if (attempt < MAX_RETRIES) {
612
+ await wait(1e3 * 2 ** attempt);
613
+ continue;
614
+ }
615
+ throw err;
616
+ } finally {
617
+ clearTimeout(timeout);
618
+ }
619
+ }
620
+ throw new Error("[RI-1205] Exhausted Google Fonts metadata fetch retries.");
621
+ }
622
+
623
+ // src/integrations/font-providers/google/index.ts
624
+ var FETCH_RETRY_COOLDOWN_MS = 3e4;
625
+ async function fetchGoogleFontList() {
626
+ if (googleFontInternals.googleFontState.fetched) return;
627
+ if (googleFontInternals.googleFontListPromise) return googleFontInternals.googleFontListPromise;
628
+ if (googleFontInternals.lastFetchFailureMs > 0 && Date.now() - googleFontInternals.lastFetchFailureMs < FETCH_RETRY_COOLDOWN_MS) {
629
+ return;
630
+ }
631
+ const localPromise = (async () => {
632
+ try {
633
+ const isOffline = process.env.RI_OFFLINE === "1" || process.env.RI_OFFLINE === "true";
634
+ if (isOffline) {
635
+ if (await loadFontCache(true)) return;
636
+ console.warn(
637
+ `[RI-1206] RI_OFFLINE is set but no local font cache found at ${getFontCacheFile()}. Run once with network access to populate it. Non-variable fonts will default to weight "100 900" and may produce broken Google Fonts URLs \u2014 set an explicit weight in the @font directive to avoid this.`
638
+ );
639
+ return;
640
+ }
641
+ if (await loadFontCache()) return;
642
+ const fetchDisabled = process.env.RI_FETCH_FONTS === "0" || process.env.RI_FETCH_FONTS === "false";
643
+ if (fetchDisabled) {
644
+ if (await loadFontCache(true)) return;
645
+ return;
646
+ }
647
+ if (typeof globalThis.fetch !== "function") {
648
+ console.warn(
649
+ "[RI-1212] Global fetch() is not available. Google Fonts metadata requires Node.js >= 18. Skipping font fetch."
650
+ );
651
+ return;
652
+ }
653
+ if (isRIDebug()) {
654
+ console.warn("[RI-DEBUG] Fetching Google Fonts metadata...");
655
+ }
656
+ try {
657
+ const newCache = await fetchGoogleFontMetadata();
658
+ googleFontInternals.googleFontState = { cache: newCache, fetched: true };
659
+ await saveFontCache();
660
+ return;
661
+ } catch (err) {
662
+ const message = err instanceof Error ? err.message : String(err);
663
+ if (message.startsWith("[RI-1207]")) {
664
+ console.warn(`${message} Skipping.`);
665
+ if (await loadFontCache(true)) return;
666
+ return;
667
+ }
668
+ if (await loadFontCache(true)) return;
669
+ console.warn(
670
+ `[RI-1205] Could not fetch Google Fonts metadata after 3 attempts (${message}). Fonts without explicit weight/style will default to "100 900" + "normal italic" \u2014 non-variable fonts may produce broken Google Fonts URLs. Run with network access to populate the metadata cache, or set an explicit weight/style in the @font directive.`
671
+ );
672
+ }
673
+ } finally {
674
+ if (!googleFontInternals.googleFontState.fetched) {
675
+ googleFontInternals.lastFetchFailureMs = Date.now();
676
+ }
677
+ googleFontInternals.googleFontListPromise = null;
678
+ }
679
+ })();
680
+ googleFontInternals.googleFontListPromise = localPromise;
681
+ return localPromise;
682
+ }
683
+ var refreshMemo = /* @__PURE__ */ new WeakMap();
684
+ function refreshFontWeightDefaults(fonts) {
685
+ const state = googleFontInternals.googleFontState;
686
+ const memo = refreshMemo.get(fonts);
687
+ if (memo && memo.state === state) return memo.result;
688
+ let anyChanged = false;
689
+ const refreshed = fonts.map((slot) => {
690
+ if (slot.kind !== "google") return slot;
691
+ const meta = googleFontInternals.googleFontState.cache.get(slot.family);
692
+ if (!meta) return slot;
693
+ let changed = false;
694
+ const faces = slot.faces.map((f) => {
695
+ let next = f;
696
+ if (!f._weightExplicit) {
697
+ const wghtAxis = meta.axes?.find((a) => a.tag === "wght");
698
+ const axisWeight = wghtAxis && wghtAxis.start !== wghtAxis.end ? `${wghtAxis.start} ${wghtAxis.end}` : "400";
699
+ if (next.weight !== axisWeight) next = { ...next, weight: axisWeight };
700
+ }
701
+ if (!f._styleExplicit) {
702
+ const italAxis = meta.axes?.find((a) => a.tag === "ital");
703
+ const axisStyle = italAxis ? "normal italic" : "normal";
704
+ if (next.style !== axisStyle) next = { ...next, style: axisStyle };
705
+ }
706
+ if (next !== f) changed = true;
707
+ return next;
708
+ });
709
+ if (changed) anyChanged = true;
710
+ return changed ? { ...slot, faces } : slot;
711
+ });
712
+ const result = anyChanged ? refreshed : fonts;
713
+ refreshMemo.set(fonts, { state, result });
714
+ return result;
715
+ }
716
+ var FONT_FETCH_TIMEOUT_MS = 1e4;
717
+ async function resolveGoogleFonts(fonts) {
718
+ if (!fonts.some((slot) => slot.kind === "google")) return fonts;
719
+ try {
720
+ await withTimeout(
721
+ fetchGoogleFontList(),
722
+ FONT_FETCH_TIMEOUT_MS,
723
+ "[RI-1213] Google Fonts metadata fetch timed out"
724
+ );
725
+ } catch {
726
+ console.warn(
727
+ `[RI-1213] Could not fetch Google Fonts metadata within ${FONT_FETCH_TIMEOUT_MS / 1e3}s \u2014 proceeding with default font weights. Variable-weight fonts may use "400" instead of their full range.`
728
+ );
729
+ }
730
+ return refreshFontWeightDefaults(fonts);
731
+ }
732
+
733
+ // src/integrations/font-providers/metrics-data.ts
734
+ var FONT_METRICS_TABLE = {
735
+ abel: [2006, -604, 0, 2048, 783, "sans-serif"],
736
+ alegreya: [1016, -345, 0, 1e3, 410, "serif"],
737
+ "anonymous pro": [1675, -373, 0, 2048, 1118, "monospace"],
738
+ archivo: [878, -210, 0, 1e3, 440, "sans-serif"],
739
+ arial: [1854, -434, 67, 2048, 913, "sans-serif"],
740
+ asap: [934, -212, 0, 1e3, 442, "sans-serif"],
741
+ barlow: [1e3, -200, 0, 1e3, 431, "sans-serif"],
742
+ bitter: [935, -265, 0, 1e3, 465, "serif"],
743
+ "bricolage grotesque": [930, -270, 0, 1e3, 470, "sans-serif"],
744
+ cabin: [1930, -500, 0, 2e3, 844, "sans-serif"],
745
+ catamaran: [1100, -540, 0, 1e3, 411, "sans-serif"],
746
+ chivo: [940, -250, 0, 1e3, 478, "sans-serif"],
747
+ "cormorant garamond": [924, -287, 0, 1e3, 394, "serif"],
748
+ "courier new": [1705, -615, 0, 2048, 1229, "monospace"],
749
+ "crimson pro": [918, -220, 0, 1024, 410, "serif"],
750
+ "crimson text": [972, -359, 0, 1024, 405, "serif"],
751
+ "dm sans": [992, -310, 0, 1e3, 466, "sans-serif"],
752
+ "dm serif display": [1036, -335, 0, 1e3, 446, "serif"],
753
+ dosis: [1027, -237, 0, 1e3, 377, "sans-serif"],
754
+ "eb garamond": [1007, -298, 0, 1e3, 385, "serif"],
755
+ epilogue: [1580, -470, 0, 2e3, 990, "sans-serif"],
756
+ "exo 2": [999, -201, 0, 1e3, 455, "sans-serif"],
757
+ figtree: [950, -250, 0, 1e3, 449, "sans-serif"],
758
+ "fira code": [1980, -644, 0, 2e3, 1200, "monospace"],
759
+ "fira sans": [935, -265, 0, 1e3, 458, "sans-serif"],
760
+ fraunces: [1956, -510, 0, 2e3, 938, "serif"],
761
+ gabarito: [940, -260, 0, 1e3, 442, "display"],
762
+ "geist mono": [1005, -295, 0, 1e3, 600, "monospace"],
763
+ geist: [1005, -295, 0, 1e3, 467, "sans-serif"],
764
+ georgia: [1878, -449, 0, 2048, 913, "serif"],
765
+ heebo: [2146, -862, 0, 2048, 912, "sans-serif"],
766
+ "helvetica neue": [952, -213, 28, 1e3, 450, "sans-serif"],
767
+ helvetica: [1577, -471, 0, 2048, 913, "sans-serif"],
768
+ hind: [1055, -546, 0, 1e3, 429, "sans-serif"],
769
+ "ibm plex mono": [1025, -275, 0, 1e3, 600, "monospace"],
770
+ "ibm plex sans": [1025, -275, 0, 1e3, 451, "sans-serif"],
409
771
  "ibm plex serif": [1025, -275, 0, 1e3, 473, "serif"],
410
772
  inconsolata: [859, -190, 0, 1e3, 500, "monospace"],
411
773
  "instrument sans": [970, -250, 0, 1e3, 458, "sans-serif"],
@@ -482,536 +844,201 @@ var CATEGORY_FALLBACK = {
482
844
  serif: "Times New Roman",
483
845
  monospace: "Courier New"
484
846
  };
485
- function lookupFontMetrics(family) {
486
- return FONT_METRICS_TABLE[family.trim().toLowerCase()];
487
- }
488
- var round4 = (n) => Math.round(n * 1e4) / 1e4;
489
- function computeFallbackMetrics(fallbackName, font, fallbackFont) {
490
- const [ascent, descent, lineGap, unitsPerEm, xWidthAvg] = font;
491
- const [, , , fbUnitsPerEm, fbXWidthAvg] = fallbackFont;
492
- const sizeAdjust = xWidthAvg / unitsPerEm / (fbXWidthAvg / fbUnitsPerEm);
493
- return {
494
- fallback: fallbackName,
495
- sizeAdjust: round4(sizeAdjust * 100),
496
- ascent: round4(ascent / unitsPerEm / sizeAdjust * 100),
497
- descent: round4(Math.abs(descent) / unitsPerEm / sizeAdjust * 100),
498
- lineGap: round4(lineGap / unitsPerEm / sizeAdjust * 100)
499
- };
500
- }
501
- function resolveAutoMetrics(family, fallbackStack, explicitFallback) {
502
- const font = lookupFontMetrics(family);
503
- if (!font) return null;
504
- const fallbackName = explicitFallback ?? fallbackStack.find((f) => lookupFontMetrics(f)) ?? CATEGORY_FALLBACK[font[5]] ?? "Arial";
505
- const fallbackFont = lookupFontMetrics(fallbackName);
506
- if (!fallbackFont) return null;
507
- return computeFallbackMetrics(fallbackName, font, fallbackFont);
508
- }
509
-
510
- // src/integrations/font-providers/index.ts
511
- var SYSTEM_STACKS = Object.freeze({
512
- sans: 'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
513
- serif: 'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
514
- mono: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'
515
- });
516
- function getFallbackStack(slot) {
517
- if (!SYSTEM_STACKS[slot] && isRIDebug()) {
518
- console.warn(`[RI-DEBUG] Unknown font slot "${slot}" \u2014 falling back to sans stack.`);
519
- }
520
- return SYSTEM_STACKS[slot] || SYSTEM_STACKS.sans;
521
- }
522
- function googleFontsUrl(family, face) {
523
- const encodedFamily = encodeURIComponent(family).replace(/%20/g, "+");
524
- let axisParam;
525
- if (face.weight.includes(",")) {
526
- const weights = face.weight.split(",").map((w) => w.trim());
527
- if (face.style.includes("italic")) {
528
- const tuples = weights.flatMap((w) => [`0,${w}`, `1,${w}`]);
529
- axisParam = `ital,wght@${tuples.join(";")}`;
530
- } else {
531
- axisParam = `wght@${weights.join(";")}`;
532
- }
533
- } else if (face.weight.includes(" ")) {
534
- const range = face.weight.replace(" ", "..");
535
- axisParam = face.style.includes("italic") ? `ital,wght@0,${range};1,${range}` : `wght@${range}`;
536
- } else {
537
- const w = face.weight || "400";
538
- axisParam = face.style.includes("italic") ? `ital,wght@0,${w};1,${w}` : `wght@${w}`;
539
- }
540
- const display = face.display || "swap";
541
- return `https://fonts.googleapis.com/css2?family=${encodedFamily}:${axisParam}&display=${display}`;
542
- }
543
- function escapeFontFamily(name) {
544
- return name.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\0/g, "\\0").replace(/\n/g, "\\a ").replace(/\r/g, "\\d ");
545
- }
546
- function generateFallbackFontFace(family, metrics) {
547
- const safeFamily = escapeFontFamily(family);
548
- return `@font-face {
549
- font-family: "${safeFamily} Fallback";
550
- src: local("${escapeFontFamily(metrics.fallback)}");
551
- size-adjust: ${metrics.sizeAdjust}%;
552
- ascent-override: ${metrics.ascent}%;
553
- descent-override: ${metrics.descent}%;
554
- line-gap-override: ${metrics.lineGap}%;
555
- }`;
556
- }
557
- var FONT_FORMAT_MIME = {
558
- woff2: "font/woff2",
559
- woff: "font/woff",
560
- truetype: "font/ttf",
561
- opentype: "font/otf"
562
- };
563
- function inferFontFormat(path) {
564
- if (path.endsWith(".woff2")) return "woff2";
565
- if (path.endsWith(".woff")) return "woff";
566
- if (path.endsWith(".ttf")) return "truetype";
567
- if (path.endsWith(".otf")) return "opentype";
568
- return "woff2";
569
- }
570
- function generateWebFontFace(family, face) {
571
- if (face.provider === "system" || !face.provider) return null;
572
- if (face.provider === "google") {
573
- return { type: "import", css: `@import url("${googleFontsUrl(family, face)}");` };
574
- }
575
- const safeProvider = escapeFontFamily(face.provider);
576
- const format = inferFontFormat(face.provider);
577
- const src = `url("${safeProvider}") format("${format}")`;
578
- const declarations = [` font-family: "${escapeFontFamily(family)}";`, ` src: ${src};`];
579
- if (face.weight) declarations.push(` font-weight: ${face.weight};`);
580
- if (face.style && face.style !== "normal") declarations.push(` font-style: ${face.style};`);
581
- if (face.display) declarations.push(` font-display: ${face.display};`);
582
- if (face.unicodeRange) declarations.push(` unicode-range: ${face.unicodeRange};`);
583
- return { type: "font-face", css: `@font-face {
584
- ${declarations.join("\n")}
585
- }` };
586
- }
587
- function normalizeLocalStyle(style, family, warnings) {
588
- if (style.includes(" ") && !style.startsWith("oblique")) {
589
- const first = style.split(/\s+/)[0];
590
- warnings.push(
591
- `[RI-1203] Local font "${family}" has a compound font-style "${style}" \u2014 a single @font-face takes one style. Split upright and italic into separate @face blocks (or use the italic: shorthand). Using "${first}".`
592
- );
593
- return first;
594
- }
595
- return style;
596
- }
597
- function resolveSlotMetrics(slot, warnings) {
598
- const cfg = slot.metrics;
599
- if (cfg === null) return null;
600
- if (cfg?.sizeAdjust !== void 0) {
601
- return {
602
- fallback: cfg.fallback || slot.fallback[0] || "Arial",
603
- sizeAdjust: cfg.sizeAdjust,
604
- ascent: cfg.ascent,
605
- descent: cfg.descent,
606
- lineGap: cfg.lineGap
607
- };
608
- }
609
- const resolved = resolveAutoMetrics(slot.family, slot.fallback, cfg?.fallback);
610
- if (!resolved && cfg?.fallback) {
611
- const missing = lookupFontMetrics(slot.family) ? cfg.fallback : slot.family;
612
- warnings.push(
613
- `[RI-1220] @font slot "${slot.slot}" requests metrics matching against "${cfg.fallback}", but "${missing}" is not in the built-in metrics table \u2014 no fallback @font-face was generated. Provide the four percentages explicitly (metrics: "${cfg.fallback}" <size-adjust> <ascent> <descent> <line-gap>) or use \`metrics: none\`.`
614
- );
615
- }
616
- return resolved;
847
+ function lookupFontMetrics(family) {
848
+ return FONT_METRICS_TABLE[family.trim().toLowerCase()];
617
849
  }
618
- function generateFontCSS(slot) {
619
- const imports = [];
620
- const fontFaces = [];
621
- const variables = [];
622
- const warnings = [];
623
- const pushFeatureVars = () => {
624
- if (slot.features) variables.push(`--font-${slot.slot}--features: ${slot.features};`);
625
- if (slot.variation) variables.push(`--font-${slot.slot}--variations: ${slot.variation};`);
850
+ var round4 = (n) => Math.round(n * 1e4) / 1e4;
851
+ function computeFallbackMetrics(fallbackName, font, fallbackFont) {
852
+ const [ascent, descent, lineGap, unitsPerEm, xWidthAvg] = font;
853
+ const [, , , fbUnitsPerEm, fbXWidthAvg] = fallbackFont;
854
+ const sizeAdjust = xWidthAvg / unitsPerEm / (fbXWidthAvg / fbUnitsPerEm);
855
+ return {
856
+ fallback: fallbackName,
857
+ sizeAdjust: round4(sizeAdjust * 100),
858
+ ascent: round4(ascent / unitsPerEm / sizeAdjust * 100),
859
+ descent: round4(Math.abs(descent) / unitsPerEm / sizeAdjust * 100),
860
+ lineGap: round4(lineGap / unitsPerEm / sizeAdjust * 100)
626
861
  };
627
- if (slot.kind === "system") {
628
- variables.push(`--font-${slot.slot}: ${getFallbackStack(slot.slot)};`);
629
- return { imports, fontFaces, variables, warnings };
630
- }
631
- if (slot.kind === "manual") {
632
- const stack = [`"${escapeFontFamily(slot.family)}"`, ...slot.fallback].join(", ");
633
- variables.push(`--font-${slot.slot}: ${stack};`);
634
- pushFeatureVars();
635
- return { imports, fontFaces, variables, warnings };
636
- }
637
- const metrics = resolveSlotMetrics(slot, warnings);
638
- if (metrics) fontFaces.push(generateFallbackFontFace(slot.family, metrics));
639
- for (const face of slot.faces) {
640
- if (face.provider !== "google" && !face.provider.startsWith("/") && !face.provider.startsWith("http") && !face.provider.startsWith(".")) {
641
- warnings.push(
642
- `[RI-1201] Unknown font provider "${face.provider}" for "${slot.family}" \u2014 supported: google, or a file path/URL.`
643
- );
644
- continue;
645
- }
646
- const emitFace = face.provider === "google" ? face : { ...face, style: normalizeLocalStyle(face.style, slot.family, warnings) };
647
- const webFont = generateWebFontFace(slot.family, emitFace);
648
- if (!webFont) continue;
649
- if (webFont.type === "import") imports.push(webFont.css);
650
- else fontFaces.push(webFont.css);
651
- }
652
- const fallbackStack = slot.fallback.length > 0 ? slot.fallback.join(", ") : getFallbackStack(slot.slot);
653
- const safeFamily = escapeFontFamily(slot.family);
654
- const stackParts = [`"${safeFamily}"`];
655
- if (metrics) stackParts.push(`"${safeFamily} Fallback"`);
656
- stackParts.push(fallbackStack);
657
- variables.push(`--font-${slot.slot}: ${stackParts.join(", ")};`);
658
- pushFeatureVars();
659
- return { imports, fontFaces, variables, warnings };
660
- }
661
- function getFontPreloadLinks(slots) {
662
- const links = [];
663
- const seen = /* @__PURE__ */ new Set();
664
- for (const slot of slots) {
665
- for (const face of slot.faces) {
666
- if (!face.preload) continue;
667
- if (face.provider === "system" || face.provider === "google" || !face.provider) continue;
668
- if (seen.has(face.provider)) continue;
669
- seen.add(face.provider);
670
- links.push({
671
- href: face.provider,
672
- as: "font",
673
- type: FONT_FORMAT_MIME[inferFontFormat(face.provider)],
674
- crossorigin: true
675
- });
676
- }
677
- }
678
- return links;
679
862
  }
680
-
681
- // src/scanner/sources.ts
682
- import { readFile, stat } from "fs/promises";
683
- import { resolve as resolve3 } from "path";
684
- import { glob } from "tinyglobby";
685
-
686
- // src/scanner/glob-utils.ts
687
- import { isAbsolute as isAbsolute2, win32 } from "path";
688
- function validateGlobPattern(pattern) {
689
- if (!pattern?.trim()) {
690
- return "Glob pattern is empty.";
691
- }
692
- if (pattern.includes("\0")) {
693
- return "Glob pattern contains a null byte, which is invalid in file paths.";
694
- }
695
- if (isAbsolute2(pattern) || win32.isAbsolute(pattern)) {
696
- return `Glob pattern "${pattern}" must be relative, not absolute.`;
697
- }
698
- const segments = pattern.split(/[\\/]+/);
699
- for (const seg of segments) {
700
- if (seg === "..") {
701
- return `Glob pattern "${pattern}" must not traverse parent directories (".."). Restructure your project layout so source files are within the project root, or use @source with a pattern rooted at the project directory.`;
702
- }
703
- }
704
- return null;
863
+ function resolveAutoMetrics(family, fallbackStack, explicitFallback) {
864
+ const font = lookupFontMetrics(family);
865
+ if (!font) return null;
866
+ const fallbackName = explicitFallback ?? fallbackStack.find((f) => lookupFontMetrics(f)) ?? CATEGORY_FALLBACK[font[5]] ?? "Arial";
867
+ const fallbackFont = lookupFontMetrics(fallbackName);
868
+ if (!fallbackFont) return null;
869
+ return computeFallbackMetrics(fallbackName, font, fallbackFont);
705
870
  }
706
871
 
707
- // src/scanner/package-discovery.ts
708
- import { existsSync, readFileSync, realpathSync, statSync } from "fs";
709
- import { dirname as dirname2, join as join2, posix, resolve as resolve2 } from "path";
710
- var EMPTY = Object.freeze({ sources: [], warnings: [] });
711
- var discoveryCache = /* @__PURE__ */ new Map();
712
- function discoverPackageSafelistSources(cwd) {
713
- const cwdAbs = resolve2(cwd);
714
- let mtimeMs;
715
- try {
716
- mtimeMs = statSync(join2(cwdAbs, "package.json")).mtimeMs;
717
- } catch {
718
- return EMPTY;
872
+ // src/integrations/font-providers/index.ts
873
+ var SYSTEM_STACKS = Object.freeze({
874
+ sans: 'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
875
+ serif: 'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
876
+ mono: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'
877
+ });
878
+ function getFallbackStack(slot) {
879
+ if (!SYSTEM_STACKS[slot] && isRIDebug()) {
880
+ console.warn(`[RI-DEBUG] Unknown font slot "${slot}" \u2014 falling back to sans stack.`);
719
881
  }
720
- const cached = discoveryCache.get(cwdAbs);
721
- if (cached && cached.mtimeMs === mtimeMs) return cached.result;
722
- const result = runDiscovery(cwdAbs);
723
- discoveryCache.set(cwdAbs, { mtimeMs, result });
724
- return result;
882
+ return SYSTEM_STACKS[slot] || SYSTEM_STACKS.sans;
725
883
  }
726
- function runDiscovery(cwdAbs) {
727
- let consumer;
728
- try {
729
- consumer = readPackageJson(join2(cwdAbs, "package.json"));
730
- } catch {
731
- return EMPTY;
732
- }
733
- const deps = [
734
- ...Object.keys(consumer.dependencies ?? {}),
735
- ...Object.keys(consumer.peerDependencies ?? {})
736
- ];
737
- if (deps.length === 0) return EMPTY;
738
- const sources = [];
739
- const warnings = [];
740
- for (const depName of deps) {
741
- const depPkgPath = findDepPackageJson(cwdAbs, depName);
742
- if (!depPkgPath) {
743
- continue;
744
- }
745
- let depPkg;
746
- try {
747
- depPkg = readPackageJson(depPkgPath);
748
- } catch (err) {
749
- warnings.push(
750
- `[RI-1410] Could not read ${depName}/package.json during safelist discovery: ${errMessage(err)}`
751
- );
752
- continue;
753
- }
754
- const patterns = depPkg.rainbowindex?.safelistSources;
755
- if (patterns == null) continue;
756
- if (!Array.isArray(patterns)) {
757
- warnings.push(
758
- `[RI-1410] Invalid rainbowindex.safelistSources in ${depName} \u2014 expected an array of glob strings.`
759
- );
760
- continue;
761
- }
762
- if (patterns.length === 0) continue;
763
- const depRoot = realpathOrFallback(dirname2(depPkgPath)).replace(/\\/g, "/");
764
- for (const pattern of patterns) {
765
- if (typeof pattern !== "string" || !pattern) {
766
- warnings.push(
767
- `[RI-1410] Invalid rainbowindex.safelistSources entry in ${depName} \u2014 expected a non-empty glob string.`
768
- );
769
- continue;
770
- }
771
- if (validateGlobPattern(pattern) !== null) {
772
- warnings.push(
773
- `[RI-1410] Invalid rainbowindex.safelistSources entry "${pattern}" in ${depName} \u2014 patterns must be relative to the package root and must not traverse parent directories.`
774
- );
775
- continue;
776
- }
777
- const absolute = posix.normalize(`${depRoot}/${pattern.replace(/^\.\//, "")}`);
778
- if (absolute !== depRoot && !absolute.startsWith(`${depRoot}/`)) {
779
- warnings.push(
780
- `[RI-1410] Invalid rainbowindex.safelistSources entry "${pattern}" in ${depName} \u2014 resolved outside the package root.`
781
- );
782
- continue;
783
- }
784
- sources.push({ pattern: absolute, negated: false, inline: false, absolute: true });
884
+ function googleFontsUrl(family, face) {
885
+ const encodedFamily = encodeURIComponent(family).replace(/%20/g, "+");
886
+ let axisParam;
887
+ if (face.weight.includes(",")) {
888
+ const weights = face.weight.split(",").map((w) => w.trim());
889
+ if (face.style.includes("italic")) {
890
+ const tuples = weights.flatMap((w) => [`0,${w}`, `1,${w}`]);
891
+ axisParam = `ital,wght@${tuples.join(";")}`;
892
+ } else {
893
+ axisParam = `wght@${weights.join(";")}`;
785
894
  }
895
+ } else if (face.weight.includes(" ")) {
896
+ const range = face.weight.replace(" ", "..");
897
+ axisParam = face.style.includes("italic") ? `ital,wght@0,${range};1,${range}` : `wght@${range}`;
898
+ } else {
899
+ const w = face.weight || "400";
900
+ axisParam = face.style.includes("italic") ? `ital,wght@0,${w};1,${w}` : `wght@${w}`;
786
901
  }
787
- return { sources, warnings };
788
- }
789
- function readPackageJson(path) {
790
- const raw = readFileSync(path, "utf8");
791
- return JSON.parse(raw);
792
- }
793
- function findDepPackageJson(cwd, depName) {
794
- let dir = cwd;
795
- while (true) {
796
- const candidate = join2(dir, "node_modules", depName, "package.json");
797
- if (existsSync(candidate)) return candidate;
798
- const parent = dirname2(dir);
799
- if (parent === dir) return null;
800
- dir = parent;
801
- }
802
- }
803
- function realpathOrFallback(path) {
804
- try {
805
- return realpathSync(path);
806
- } catch {
807
- return path;
808
- }
902
+ const display = face.display || "swap";
903
+ return `https://fonts.googleapis.com/css2?family=${encodedFamily}:${axisParam}&display=${display}`;
809
904
  }
810
- function errMessage(err) {
811
- return err instanceof Error ? err.message : String(err);
905
+ function escapeFontFamily(name) {
906
+ return name.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\0/g, "\\0").replace(/\n/g, "\\a ").replace(/\r/g, "\\d ");
812
907
  }
813
-
814
- // src/scanner/sources.ts
815
- var DEFAULT_PATTERNS = Object.freeze([
816
- "index.html",
817
- "src/**/*.{html,js,jsx,ts,tsx,mdx,vue,svelte}"
818
- ]);
819
- var DEFAULT_EXCLUDES = Object.freeze([
820
- "node_modules/**",
821
- "dist/**",
822
- "build/**",
823
- "coverage/**",
824
- "public/**",
825
- "**/*.config.*",
826
- "**/*.d.ts"
827
- ]);
828
- var MAX_FILE_SIZE = 1048576;
829
- var MAX_INLINE_SOURCE_SIZE = 102400;
830
- var GLOB_TIMEOUT_MS = 3e4;
831
- var GLOB_TIMEOUT_MESSAGE = `glob() timed out after ${GLOB_TIMEOUT_MS / 1e3}s \u2014 check for network filesystem issues or overly broad @source patterns`;
832
- function collectPatterns(sources) {
833
- const includePatterns = [];
834
- const nodeModulesIncludePatterns = [];
835
- const excludePatterns = [...DEFAULT_EXCLUDES];
836
- const hasUserPositiveGlobs = sources.some((s) => !s.inline && !s.negated && !s.absolute);
837
- if (!hasUserPositiveGlobs) {
838
- includePatterns.push(...DEFAULT_PATTERNS);
908
+ function generateFallbackFontFace(family, metrics) {
909
+ const safeFamily = escapeFontFamily(family);
910
+ return `@font-face {
911
+ font-family: "${safeFamily} Fallback";
912
+ src: local("${escapeFontFamily(metrics.fallback)}");
913
+ size-adjust: ${metrics.sizeAdjust}%;
914
+ ascent-override: ${metrics.ascent}%;
915
+ descent-override: ${metrics.descent}%;
916
+ line-gap-override: ${metrics.lineGap}%;
917
+ }`;
918
+ }
919
+ var FONT_FORMAT_MIME = {
920
+ woff2: "font/woff2",
921
+ woff: "font/woff",
922
+ truetype: "font/ttf",
923
+ opentype: "font/otf"
924
+ };
925
+ function inferFontFormat(path) {
926
+ if (path.endsWith(".woff2")) return "woff2";
927
+ if (path.endsWith(".woff")) return "woff";
928
+ if (path.endsWith(".ttf")) return "truetype";
929
+ if (path.endsWith(".otf")) return "opentype";
930
+ return "woff2";
931
+ }
932
+ function generateWebFontFace(family, face) {
933
+ if (face.provider === "system" || !face.provider) return null;
934
+ if (face.provider === "google") {
935
+ return { type: "import", css: `@import url("${googleFontsUrl(family, face)}");` };
839
936
  }
840
- const warnings = [];
841
- for (const src of sources) {
842
- if (src.inline) continue;
843
- if (!src.absolute) {
844
- const err = validateGlobPattern(src.pattern);
845
- if (err) {
846
- warnings.push(`[RI-1404] @source pattern rejected: ${err}`);
847
- continue;
848
- }
849
- }
850
- if (src.negated) {
851
- excludePatterns.push(src.pattern);
852
- } else if (src.absolute || src.pattern.replace(/^\.\//, "").startsWith("node_modules/")) {
853
- nodeModulesIncludePatterns.push(src.pattern);
854
- } else {
855
- includePatterns.push(src.pattern);
856
- }
937
+ const safeProvider = escapeFontFamily(face.provider);
938
+ const format = inferFontFormat(face.provider);
939
+ const src = `url("${safeProvider}") format("${format}")`;
940
+ const declarations = [` font-family: "${escapeFontFamily(family)}";`, ` src: ${src};`];
941
+ if (face.weight) declarations.push(` font-weight: ${face.weight};`);
942
+ if (face.style && face.style !== "normal") declarations.push(` font-style: ${face.style};`);
943
+ if (face.display) declarations.push(` font-display: ${face.display};`);
944
+ if (face.unicodeRange) declarations.push(` unicode-range: ${face.unicodeRange};`);
945
+ return { type: "font-face", css: `@font-face {
946
+ ${declarations.join("\n")}
947
+ }` };
948
+ }
949
+ function normalizeLocalStyle(style, family, warnings) {
950
+ if (style.includes(" ") && !style.startsWith("oblique")) {
951
+ const first = style.split(/\s+/)[0];
952
+ warnings.push(
953
+ `[RI-1203] Local font "${family}" has a compound font-style "${style}" \u2014 a single @font-face takes one style. Split upright and italic into separate @face blocks (or use the italic: shorthand). Using "${first}".`
954
+ );
955
+ return first;
857
956
  }
858
- return {
859
- includePatterns,
860
- nodeModulesIncludePatterns,
861
- excludePatterns,
862
- warnings,
863
- hasUserPositiveGlobs
864
- };
957
+ return style;
865
958
  }
866
- async function resolveSourceFilesAsync(sources, cwd, hasInlineClasses = false) {
867
- const {
868
- includePatterns,
869
- nodeModulesIncludePatterns,
870
- excludePatterns,
871
- warnings,
872
- hasUserPositiveGlobs
873
- } = collectPatterns(sources);
874
- const allIncludes = [...includePatterns, ...nodeModulesIncludePatterns];
875
- if (allIncludes.length === 0) return { files: [], warnings };
876
- try {
877
- const globPasses = [];
878
- if (includePatterns.length > 0) {
879
- globPasses.push(
880
- withTimeout(
881
- glob(includePatterns, { cwd, ignore: excludePatterns }),
882
- GLOB_TIMEOUT_MS,
883
- GLOB_TIMEOUT_MESSAGE
884
- )
885
- );
886
- }
887
- if (nodeModulesIncludePatterns.length > 0) {
888
- const relaxedExcludes = excludePatterns.filter((p) => p !== "node_modules/**");
889
- globPasses.push(
890
- withTimeout(
891
- glob(nodeModulesIncludePatterns, { cwd, ignore: relaxedExcludes }),
892
- GLOB_TIMEOUT_MS,
893
- GLOB_TIMEOUT_MESSAGE
894
- )
895
- );
896
- }
897
- const matched = (await Promise.all(globPasses)).flat();
898
- const files = [...new Set(matched.map((f) => resolve3(cwd, f)))].sort(codepointCompare);
899
- if (files.length === 0 && !(hasInlineClasses && !hasUserPositiveGlobs)) {
900
- warnings.push(
901
- `[RI-1401] No source files found matching ${allIncludes.map((p) => `"${p}"`).join(", ")} \u2014 check @source paths or project structure.`
902
- );
903
- }
904
- return { files, warnings };
905
- } catch (err) {
959
+ function resolveSlotMetrics(slot, warnings) {
960
+ const cfg = slot.metrics;
961
+ if (cfg === null) return null;
962
+ if (cfg?.sizeAdjust !== void 0) {
963
+ return {
964
+ fallback: cfg.fallback || slot.fallback[0] || "Arial",
965
+ sizeAdjust: cfg.sizeAdjust,
966
+ ascent: cfg.ascent,
967
+ descent: cfg.descent,
968
+ lineGap: cfg.lineGap
969
+ };
970
+ }
971
+ const resolved = resolveAutoMetrics(slot.family, slot.fallback, cfg?.fallback);
972
+ if (!resolved && cfg?.fallback) {
973
+ const missing = lookupFontMetrics(slot.family) ? cfg.fallback : slot.family;
906
974
  warnings.push(
907
- `[RI-1402] Invalid glob pattern \u2014 skipping. Check @source syntax. (${err instanceof Error ? err.message : String(err)})`
975
+ `[RI-1220] @font slot "${slot.slot}" requests metrics matching against "${cfg.fallback}", but "${missing}" is not in the built-in metrics table \u2014 no fallback @font-face was generated. Provide the four percentages explicitly (metrics: "${cfg.fallback}" <size-adjust> <ascent> <descent> <line-gap>) or use \`metrics: none\`.`
908
976
  );
909
- return { files: [], warnings };
910
977
  }
978
+ return resolved;
911
979
  }
912
- function collectInlineClasses(sources) {
913
- const classes = /* @__PURE__ */ new Set();
980
+ function generateFontCSS(slot) {
981
+ const imports = [];
982
+ const fontFaces = [];
983
+ const variables = [];
914
984
  const warnings = [];
915
- for (const src of sources) {
916
- if (!src.inline) continue;
917
- const items = src.classes ?? [];
918
- let contentLength = 0;
919
- for (const cls of items) contentLength += cls.length;
920
- if (contentLength > MAX_INLINE_SOURCE_SIZE) {
985
+ const pushFeatureVars = () => {
986
+ if (slot.features) variables.push(`--font-${slot.slot}--features: ${slot.features};`);
987
+ if (slot.variation) variables.push(`--font-${slot.slot}--variations: ${slot.variation};`);
988
+ };
989
+ if (slot.kind === "system") {
990
+ variables.push(`--font-${slot.slot}: ${getFallbackStack(slot.slot)};`);
991
+ return { imports, fontFaces, variables, warnings };
992
+ }
993
+ if (slot.kind === "manual") {
994
+ const fallback = slot.fallback.length > 0 ? slot.fallback.join(", ") : getFallbackStack(slot.slot);
995
+ const stack = [`"${escapeFontFamily(slot.family)}"`, fallback].join(", ");
996
+ variables.push(`--font-${slot.slot}: ${stack};`);
997
+ pushFeatureVars();
998
+ return { imports, fontFaces, variables, warnings };
999
+ }
1000
+ const metrics = resolveSlotMetrics(slot, warnings);
1001
+ if (metrics) fontFaces.push(generateFallbackFontFace(slot.family, metrics));
1002
+ for (const face of slot.faces) {
1003
+ if (face.provider !== "google" && !face.provider.startsWith("/") && !face.provider.startsWith("http") && !face.provider.startsWith(".")) {
921
1004
  warnings.push(
922
- `[RI-1406] Inline @source content exceeds ${MAX_INLINE_SOURCE_SIZE} byte limit (${contentLength} bytes) \u2014 skipping.`
1005
+ `[RI-1201] Unknown font provider "${face.provider}" for "${slot.family}" \u2014 supported: google, or a file path/URL.`
923
1006
  );
924
1007
  continue;
925
1008
  }
926
- for (const cls of items) {
927
- if (cls) classes.add(cls);
928
- }
929
- }
930
- return { classes, warnings };
931
- }
932
- var FILE_IO_TIMEOUT_MS = 1e4;
933
- var SCAN_CACHE_MAX_ENTRIES = 2e4;
934
- var scanCache = /* @__PURE__ */ new Map();
935
- async function scanOneFile(file) {
936
- const warnings = [];
937
- try {
938
- const stats = await withTimeout(stat(file), FILE_IO_TIMEOUT_MS, "stat() timed out");
939
- const cached = scanCache.get(file);
940
- if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
941
- return cached.result;
942
- }
943
- let result;
944
- if (stats.size > MAX_FILE_SIZE) {
945
- result = {
946
- classes: null,
947
- warnings,
948
- failure: `[RI-1405] Skipping source file "${file}" (${stats.size} bytes) \u2014 exceeds ${MAX_FILE_SIZE} byte limit.`
949
- };
950
- } else {
951
- const content = await withTimeout(
952
- readFile(file, "utf-8"),
953
- FILE_IO_TIMEOUT_MS,
954
- "readFile() timed out"
955
- );
956
- result = {
957
- classes: extractClassesFromSource({ path: file, content }, warnings),
958
- warnings,
959
- failure: null
960
- };
961
- }
962
- if (scanCache.size >= SCAN_CACHE_MAX_ENTRIES) scanCache.clear();
963
- scanCache.set(file, { mtimeMs: stats.mtimeMs, size: stats.size, result });
964
- return result;
965
- } catch (err) {
966
- return {
967
- classes: null,
968
- warnings,
969
- failure: `[RI-1403] Could not read source file "${file}" \u2014 skipping. (${err instanceof Error ? err.message : String(err)})`
970
- };
1009
+ const emitFace = face.provider === "google" ? face : { ...face, style: normalizeLocalStyle(face.style, slot.family, warnings) };
1010
+ const webFont = generateWebFontFace(slot.family, emitFace);
1011
+ if (!webFont) continue;
1012
+ if (webFont.type === "import") imports.push(webFont.css);
1013
+ else fontFaces.push(webFont.css);
971
1014
  }
1015
+ const fallbackStack = slot.fallback.length > 0 ? slot.fallback.join(", ") : getFallbackStack(slot.slot);
1016
+ const safeFamily = escapeFontFamily(slot.family);
1017
+ const stackParts = [`"${safeFamily}"`];
1018
+ if (metrics) stackParts.push(`"${safeFamily} Fallback"`);
1019
+ stackParts.push(fallbackStack);
1020
+ variables.push(`--font-${slot.slot}: ${stackParts.join(", ")};`);
1021
+ pushFeatureVars();
1022
+ return { imports, fontFaces, variables, warnings };
972
1023
  }
973
- async function scanSourceFilesAsync(sources, cwd) {
974
- const { classes: allClasses, warnings: inlineWarnings } = collectInlineClasses(sources);
975
- const allWarnings = [...inlineWarnings];
976
- const { files, warnings: resolveWarnings } = await resolveSourceFilesAsync(
977
- sources,
978
- cwd,
979
- allClasses.size > 0
980
- );
981
- allWarnings.push(...resolveWarnings);
982
- const CONCURRENCY_LIMIT = 32;
983
- const results = new Array(files.length);
984
- let nextIndex = 0;
985
- const worker = async () => {
986
- while (nextIndex < files.length) {
987
- const index = nextIndex++;
988
- results[index] = await scanOneFile(files[index]);
989
- }
990
- };
991
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY_LIMIT, files.length) }, worker));
992
- const seen = new Set(allWarnings);
993
- for (const result of results) {
994
- if (result.failure) {
995
- allWarnings.push(result.failure);
996
- seen.add(result.failure);
997
- continue;
998
- }
999
- if (result.classes) {
1000
- for (const cls of result.classes) {
1001
- allClasses.add(cls);
1002
- }
1024
+ function getFontPreloadLinks(slots) {
1025
+ const links = [];
1026
+ const seen = /* @__PURE__ */ new Set();
1027
+ for (const slot of slots) {
1028
+ for (const face of slot.faces) {
1029
+ if (!face.preload) continue;
1030
+ if (face.provider === "system" || face.provider === "google" || !face.provider) continue;
1031
+ if (seen.has(face.provider)) continue;
1032
+ seen.add(face.provider);
1033
+ links.push({
1034
+ href: face.provider,
1035
+ as: "font",
1036
+ type: FONT_FORMAT_MIME[inferFontFormat(face.provider)],
1037
+ crossorigin: true
1038
+ });
1003
1039
  }
1004
- pushWarningsDeduped(allWarnings, result.warnings, seen);
1005
1040
  }
1006
- return { classes: allClasses, warnings: allWarnings };
1007
- }
1008
- async function collectProjectClasses(themeSources, surfaceSources, cwd, warnings, warningSeen) {
1009
- const discovered = discoverPackageSafelistSources(cwd);
1010
- pushWarningsDeduped(warnings, discovered.warnings, warningSeen);
1011
- const allSources = [...themeSources, ...surfaceSources, ...discovered.sources];
1012
- const scanResult = await scanSourceFilesAsync(allSources, cwd);
1013
- pushWarningsDeduped(warnings, scanResult.warnings, warningSeen);
1014
- return scanResult.classes;
1041
+ return links;
1015
1042
  }
1016
1043
 
1017
1044
  // src/css/strip.ts
@@ -1209,7 +1236,7 @@ var modules = [
1209
1236
  {
1210
1237
  name: "margins",
1211
1238
  category: "core",
1212
- css: `body, h1, h2, h3, h4, h5, h6, p, figure, blockquote, dl, dd, pre {
1239
+ css: `body, h1, h2, h3, h4, h5, h6, p, figure, blockquote, dl, dd, pre, ol, ul, menu {
1213
1240
  margin: 0;
1214
1241
  }`
1215
1242
  },
@@ -1226,9 +1253,6 @@ var modules = [
1226
1253
  name: "root-defaults",
1227
1254
  category: "core",
1228
1255
  css: `:root {
1229
- --sans-fallback: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
1230
- --serif-fallback: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
1231
- --mono-fallback: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
1232
1256
  line-height: 1.5;
1233
1257
  -webkit-text-size-adjust: 100%;
1234
1258
  tab-size: 4;
@@ -1337,7 +1361,7 @@ button {
1337
1361
  category: "forms",
1338
1362
  css: `input::placeholder, textarea::placeholder {
1339
1363
  opacity: 1;
1340
- color: oklch(0.556 0 0);
1364
+ color: color-mix(in oklab, currentColor 48%, transparent);
1341
1365
  }
1342
1366
  input:where([type="button"], [type="reset"], [type="submit"]) {
1343
1367
  -webkit-appearance: button;
@@ -1352,16 +1376,14 @@ input:where([type="button"], [type="reset"], [type="submit"]) {
1352
1376
  }`
1353
1377
  },
1354
1378
  {
1355
- name: "select-reset",
1379
+ name: "fieldset-reset",
1356
1380
  category: "forms",
1357
- css: `select {
1358
- -webkit-appearance: none;
1359
- appearance: none;
1360
- background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='currentColor'%3e%3cpath fill-rule='evenodd' d='M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06z' clip-rule='evenodd'/%3e%3c/svg%3e");
1361
- background-position: right 0.5rem center;
1362
- background-repeat: no-repeat;
1363
- background-size: 1.5em 1.5em;
1364
- padding-inline-end: 2.5rem;
1381
+ css: `fieldset {
1382
+ margin: 0;
1383
+ padding: 0;
1384
+ }
1385
+ legend {
1386
+ padding: 0;
1365
1387
  }`
1366
1388
  },
1367
1389
  // ── Interactive ──────────────────────────────────────────
@@ -1369,13 +1391,10 @@ input:where([type="button"], [type="reset"], [type="submit"]) {
1369
1391
  name: "focus-visible",
1370
1392
  category: "interactive",
1371
1393
  css: `:focus-visible {
1372
- outline-width: var(--spacing);
1394
+ outline-width: 2px;
1373
1395
  outline-style: solid;
1374
- outline-offset: calc(var(--spacing) * 0.5);
1396
+ outline-offset: 2px;
1375
1397
  outline-color: currentColor;
1376
- }
1377
- :focus:not(:focus-visible) {
1378
- outline: none;
1379
1398
  }`
1380
1399
  },
1381
1400
  {
@@ -1512,15 +1531,6 @@ function generateTokenLayer(theme, usage, fontOutputCache) {
1512
1531
  vars.push(`--font-${slot}: ${stack};`);
1513
1532
  }
1514
1533
  }
1515
- if (usage.usedRounded.size > 0) {
1516
- vars.push(`--rounded-roof: ${theme.roundedRoof};`);
1517
- for (const [name, val] of Object.entries(theme.rounded).sort(
1518
- ([a], [b]) => codepointCompare(a, b)
1519
- )) {
1520
- if (!usage.usedRounded.has(name)) continue;
1521
- vars.push(`--rounded-${name}: ${val};`);
1522
- }
1523
- }
1524
1534
  const shadowsToEmit = resolveTransitiveShadowDeps(theme.shadows, usage.usedShadows);
1525
1535
  for (const [name, val] of Object.entries(theme.shadows).sort(
1526
1536
  ([a], [b]) => codepointCompare(a, b)
@@ -1755,13 +1765,15 @@ async function finalizeProjectCompilation(options) {
1755
1765
  }
1756
1766
  const expansionWarnings = [];
1757
1767
  const classNameSet = new Set(options.classNames);
1768
+ const authored = options.authoredClassNames && new Set(options.authoredClassNames);
1758
1769
  for (const cls of collectApplyClassNames(options.css, expansionWarnings)) {
1759
1770
  classNameSet.add(cls);
1771
+ authored?.add(cls);
1760
1772
  }
1761
1773
  const classNames = [...classNameSet];
1762
1774
  pushWarningsDeduped(analysis.warnings, expansionWarnings, analysis.warningSeen);
1763
1775
  const compiler = createCompiler();
1764
- const compilation = compiler.compile(classNames, effectiveTheme);
1776
+ const compilation = compiler.compile(classNames, effectiveTheme, authored);
1765
1777
  let userCSS = stripRIDirectives(options.css);
1766
1778
  if ((options.processCssFunctions ?? true) && userCSS && hasCSSFunctions(userCSS)) {
1767
1779
  userCSS = compileCSSFunctions(userCSS, effectiveTheme, analysis.warnings);
@@ -1825,7 +1837,7 @@ async function compileScannedProject(options) {
1825
1837
  }
1826
1838
  surfaceSources.push({ pattern, negated: false, inline: false });
1827
1839
  }
1828
- const classNames = await collectProjectClasses(
1840
+ const { classes: classNames, authored } = await collectProjectClasses(
1829
1841
  analysis.theme.sources,
1830
1842
  surfaceSources,
1831
1843
  options.cwd,
@@ -1835,6 +1847,7 @@ async function compileScannedProject(options) {
1835
1847
  const compiled = await finalizeProjectCompilation({
1836
1848
  css: options.css,
1837
1849
  classNames,
1850
+ authoredClassNames: authored,
1838
1851
  analysis,
1839
1852
  resolveFonts: () => fontsReady
1840
1853
  });
@@ -1846,6 +1859,8 @@ export {
1846
1859
  getFontPreloadLinks,
1847
1860
  DEFAULT_PATTERNS,
1848
1861
  DEFAULT_EXCLUDES,
1862
+ enableSourceFileListCache,
1863
+ invalidateSourceFileListCache,
1849
1864
  finalizeProjectCompilation,
1850
1865
  compileScannedProject
1851
1866
  };