rainbowindex 0.5.1 → 0.7.0

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +876 -0
  2. package/LICENSE +16 -17
  3. package/NOTICE.md +106 -0
  4. package/README.md +225 -69
  5. package/dist/browser.d.ts +4 -2
  6. package/dist/browser.mjs +12 -6
  7. package/dist/chunk-2T7V5XLK.mjs +912 -0
  8. package/dist/chunk-6OORICWF.mjs +16 -0
  9. package/dist/{chunk-PDORZSQX.mjs → chunk-FJOZJIKB.mjs} +7814 -5174
  10. package/dist/chunk-L56IRO7A.mjs +491 -0
  11. package/dist/chunk-PZDVDEZJ.mjs +196 -0
  12. package/dist/{chunk-4CTJLMYM.mjs → chunk-RC6DDE4L.mjs} +37 -23
  13. package/dist/chunk-TQJYVQPE.mjs +217 -0
  14. package/dist/chunk-W756NVYI.mjs +33 -0
  15. package/dist/chunk-WBESS2ZD.mjs +598 -0
  16. package/dist/{chunk-3HRMFZGE.mjs → chunk-X66Z2YHT.mjs} +2 -1
  17. package/dist/{chunk-4UKFK2GE.mjs → chunk-XQGSG2HK.mjs} +213 -756
  18. package/dist/cli.mjs +1101 -125
  19. package/dist/{context-B9yhJxd5.d.ts → context-DcBtnnan.d.ts} +55 -108
  20. package/dist/editor.d.ts +82 -421
  21. package/dist/editor.mjs +68 -363
  22. package/dist/eslint.d.ts +16 -0
  23. package/dist/eslint.mjs +32 -0
  24. package/dist/{index-Dx-NpFFx.d.ts → imports-C9esHd5Q.d.ts} +98 -81
  25. package/dist/index-CNqdL5U0.d.ts +56 -0
  26. package/dist/index-Czx-EUwh.d.ts +138 -0
  27. package/dist/index-DW8YSxTz.d.ts +104 -0
  28. package/dist/index.d.ts +49 -5
  29. package/dist/index.mjs +40 -13
  30. package/dist/oxlint.d.ts +21 -3
  31. package/dist/oxlint.mjs +19 -1
  32. package/dist/recipe.d.ts +111 -0
  33. package/dist/recipe.mjs +71 -0
  34. package/dist/safelist-CH3_PywB.d.ts +43 -0
  35. package/dist/session-CMaskdB7.d.ts +543 -0
  36. package/dist/tailwind.css +644 -0
  37. package/dist/theme-CIZiGlce.d.ts +115 -0
  38. package/dist/vite.d.ts +10 -1
  39. package/dist/vite.mjs +273 -113
  40. package/package.json +27 -5
  41. package/dist/chunk-F4VCBISU.mjs +0 -1866
  42. package/dist/chunk-RU4756NG.mjs +0 -243
  43. package/dist/safelist-DAkKuxCk.d.ts +0 -96
@@ -0,0 +1,912 @@
1
+ import {
2
+ createNodeImportResolver
3
+ } from "./chunk-W756NVYI.mjs";
4
+ import {
5
+ APPLY_LIKE_MATCH_RE,
6
+ SAFE_FONT_FAMILY_RE,
7
+ analyzeProjectCSSMemo,
8
+ assembleSections,
9
+ codepointCompare,
10
+ compileCSSFunctions,
11
+ createCompiler,
12
+ expandApplyBodyGroups,
13
+ extractClassesFromSource,
14
+ hasCSSFunctions,
15
+ inlineDirectiveImports,
16
+ isRIDebug,
17
+ pushWarningsDeduped,
18
+ scanCSSForTokenUsage,
19
+ stripRIDirectives,
20
+ withTimeout
21
+ } from "./chunk-FJOZJIKB.mjs";
22
+
23
+ // src/scanner/sources.ts
24
+ import { readFile, stat } from "fs/promises";
25
+ import { resolve as resolve2 } from "path";
26
+ import { glob } from "tinyglobby";
27
+
28
+ // src/scanner/glob-utils.ts
29
+ import { isAbsolute, win32 } from "path";
30
+ function validateGlobPattern(pattern) {
31
+ if (!pattern?.trim()) {
32
+ return "Glob pattern is empty.";
33
+ }
34
+ if (pattern.includes("\0")) {
35
+ return "Glob pattern contains a null byte, which is invalid in file paths.";
36
+ }
37
+ if (isAbsolute(pattern) || win32.isAbsolute(pattern)) {
38
+ return `Glob pattern "${pattern}" must be relative, not absolute.`;
39
+ }
40
+ const segments = pattern.split(/[\\/]+/);
41
+ for (const seg of segments) {
42
+ if (seg === "..") {
43
+ 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.`;
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+
49
+ // src/scanner/package-discovery.ts
50
+ import { existsSync, readFileSync, realpathSync, statSync } from "fs";
51
+ import { dirname, join, posix, resolve } from "path";
52
+ var EMPTY = Object.freeze({ sources: [], warnings: [] });
53
+ var discoveryCache = /* @__PURE__ */ new Map();
54
+ function discoverPackageSafelistSources(cwd) {
55
+ const cwdAbs = resolve(cwd);
56
+ let mtimeMs;
57
+ try {
58
+ mtimeMs = statSync(join(cwdAbs, "package.json")).mtimeMs;
59
+ } catch {
60
+ return EMPTY;
61
+ }
62
+ const cached = discoveryCache.get(cwdAbs);
63
+ if (cached && cached.mtimeMs === mtimeMs) return cached.result;
64
+ const result = runDiscovery(cwdAbs);
65
+ discoveryCache.set(cwdAbs, { mtimeMs, result });
66
+ return result;
67
+ }
68
+ function runDiscovery(cwdAbs) {
69
+ let consumer;
70
+ try {
71
+ consumer = readPackageJson(join(cwdAbs, "package.json"));
72
+ } catch {
73
+ return EMPTY;
74
+ }
75
+ const deps = [
76
+ ...Object.keys(consumer.dependencies ?? {}),
77
+ ...Object.keys(consumer.peerDependencies ?? {})
78
+ ];
79
+ if (deps.length === 0) return EMPTY;
80
+ const sources = [];
81
+ const warnings = [];
82
+ for (const depName of deps) {
83
+ const depPkgPath = findDepPackageJson(cwdAbs, depName);
84
+ if (!depPkgPath) {
85
+ continue;
86
+ }
87
+ let depPkg;
88
+ try {
89
+ depPkg = readPackageJson(depPkgPath);
90
+ } catch (err) {
91
+ warnings.push(
92
+ `[RI-1410] Could not read ${depName}/package.json during safelist discovery: ${errMessage(err)}`
93
+ );
94
+ continue;
95
+ }
96
+ const patterns = depPkg.rainbowindex?.safelistSources;
97
+ if (patterns == null) continue;
98
+ if (!Array.isArray(patterns)) {
99
+ warnings.push(
100
+ `[RI-1410] Invalid rainbowindex.safelistSources in ${depName} \u2014 expected an array of glob strings.`
101
+ );
102
+ continue;
103
+ }
104
+ if (patterns.length === 0) continue;
105
+ const depRoot = realpathOrFallback(dirname(depPkgPath)).replace(/\\/g, "/");
106
+ for (const pattern of patterns) {
107
+ if (typeof pattern !== "string" || !pattern) {
108
+ warnings.push(
109
+ `[RI-1410] Invalid rainbowindex.safelistSources entry in ${depName} \u2014 expected a non-empty glob string.`
110
+ );
111
+ continue;
112
+ }
113
+ if (validateGlobPattern(pattern) !== null) {
114
+ warnings.push(
115
+ `[RI-1410] Invalid rainbowindex.safelistSources entry "${pattern}" in ${depName} \u2014 patterns must be relative to the package root and must not traverse parent directories.`
116
+ );
117
+ continue;
118
+ }
119
+ const absolute = posix.normalize(`${depRoot}/${pattern.replace(/^\.\//, "")}`);
120
+ if (absolute !== depRoot && !absolute.startsWith(`${depRoot}/`)) {
121
+ warnings.push(
122
+ `[RI-1410] Invalid rainbowindex.safelistSources entry "${pattern}" in ${depName} \u2014 resolved outside the package root.`
123
+ );
124
+ continue;
125
+ }
126
+ sources.push({ pattern: absolute, negated: false, inline: false, absolute: true });
127
+ }
128
+ }
129
+ return { sources, warnings };
130
+ }
131
+ function readPackageJson(path) {
132
+ const raw = readFileSync(path, "utf8");
133
+ return JSON.parse(raw);
134
+ }
135
+ function findDepPackageJson(cwd, depName) {
136
+ let dir = cwd;
137
+ while (true) {
138
+ const candidate = join(dir, "node_modules", depName, "package.json");
139
+ if (existsSync(candidate)) return candidate;
140
+ const parent = dirname(dir);
141
+ if (parent === dir) return null;
142
+ dir = parent;
143
+ }
144
+ }
145
+ function realpathOrFallback(path) {
146
+ try {
147
+ return realpathSync(path);
148
+ } catch {
149
+ return path;
150
+ }
151
+ }
152
+ function errMessage(err) {
153
+ return err instanceof Error ? err.message : String(err);
154
+ }
155
+
156
+ // src/scanner/sources.ts
157
+ var DEFAULT_PATTERNS = Object.freeze([
158
+ "*.html",
159
+ "src/**/*.{html,js,jsx,ts,tsx,mdx,vue,svelte,astro}"
160
+ ]);
161
+ var DEFAULT_EXCLUDES = Object.freeze([
162
+ "node_modules/**",
163
+ "dist/**",
164
+ "build/**",
165
+ "coverage/**",
166
+ "public/**",
167
+ "**/*.config.*",
168
+ "**/*.d.ts"
169
+ ]);
170
+ var MAX_FILE_SIZE = 1048576;
171
+ var MAX_INLINE_SOURCE_SIZE = 102400;
172
+ var GLOB_TIMEOUT_MS = 3e4;
173
+ var GLOB_TIMEOUT_MESSAGE = `glob() timed out after ${GLOB_TIMEOUT_MS / 1e3}s \u2014 check for network filesystem issues or overly broad @source patterns`;
174
+ var SOURCE_LIST_CACHE_MAX_ENTRIES = 50;
175
+ var sourceListCacheEnabled = false;
176
+ var sourceListCache = /* @__PURE__ */ new Map();
177
+ var sourceListCacheGeneration = 0;
178
+ function enableSourceFileListCache() {
179
+ sourceListCacheEnabled = true;
180
+ }
181
+ function invalidateSourceFileListCache() {
182
+ sourceListCacheGeneration++;
183
+ sourceListCache.clear();
184
+ }
185
+ function collectPatterns(sources) {
186
+ const includePatterns = [];
187
+ const nodeModulesIncludePatterns = [];
188
+ const excludePatterns = [...DEFAULT_EXCLUDES];
189
+ const hasUserPositiveGlobs = sources.some((s) => !s.inline && !s.negated && !s.absolute);
190
+ if (!hasUserPositiveGlobs) {
191
+ includePatterns.push(...DEFAULT_PATTERNS);
192
+ }
193
+ const warnings = [];
194
+ for (const src of sources) {
195
+ if (src.inline) continue;
196
+ if (!src.absolute) {
197
+ const err = validateGlobPattern(src.pattern);
198
+ if (err) {
199
+ warnings.push(`[RI-1404] @source pattern rejected: ${err}`);
200
+ continue;
201
+ }
202
+ }
203
+ if (src.negated) {
204
+ excludePatterns.push(src.pattern);
205
+ } else if (src.absolute || src.pattern.replace(/^\.\//, "").startsWith("node_modules/")) {
206
+ nodeModulesIncludePatterns.push(src.pattern);
207
+ } else {
208
+ includePatterns.push(src.pattern);
209
+ }
210
+ }
211
+ return {
212
+ includePatterns,
213
+ nodeModulesIncludePatterns,
214
+ excludePatterns,
215
+ warnings,
216
+ hasUserPositiveGlobs
217
+ };
218
+ }
219
+ async function resolveSourceFilesAsync(sources, cwd, hasInlineClasses = false) {
220
+ const {
221
+ includePatterns,
222
+ nodeModulesIncludePatterns,
223
+ excludePatterns,
224
+ warnings,
225
+ hasUserPositiveGlobs
226
+ } = collectPatterns(sources);
227
+ const allIncludes = [...includePatterns, ...nodeModulesIncludePatterns];
228
+ if (allIncludes.length === 0) return { files: [], warnings };
229
+ const cacheKey = sourceListCacheEnabled ? [
230
+ cwd,
231
+ includePatterns.join("\0"),
232
+ nodeModulesIncludePatterns.join("\0"),
233
+ excludePatterns.join("\0")
234
+ ].join("") : null;
235
+ try {
236
+ const generationAtStart = sourceListCacheGeneration;
237
+ let files = cacheKey !== null ? sourceListCache.get(cacheKey) : void 0;
238
+ if (files === void 0) {
239
+ const globPasses = [];
240
+ if (includePatterns.length > 0) {
241
+ globPasses.push(
242
+ withTimeout(
243
+ glob(includePatterns, { cwd, ignore: excludePatterns }),
244
+ GLOB_TIMEOUT_MS,
245
+ GLOB_TIMEOUT_MESSAGE
246
+ )
247
+ );
248
+ }
249
+ if (nodeModulesIncludePatterns.length > 0) {
250
+ const relaxedExcludes = excludePatterns.filter((p) => p !== "node_modules/**");
251
+ globPasses.push(
252
+ withTimeout(
253
+ glob(nodeModulesIncludePatterns, { cwd, ignore: relaxedExcludes }),
254
+ GLOB_TIMEOUT_MS,
255
+ GLOB_TIMEOUT_MESSAGE
256
+ )
257
+ );
258
+ }
259
+ const matched = (await Promise.all(globPasses)).flat();
260
+ files = [...new Set(matched.map((f) => resolve2(cwd, f)))].sort(codepointCompare);
261
+ if (cacheKey !== null && sourceListCacheGeneration === generationAtStart) {
262
+ if (sourceListCache.size >= SOURCE_LIST_CACHE_MAX_ENTRIES) sourceListCache.clear();
263
+ sourceListCache.set(cacheKey, files);
264
+ }
265
+ }
266
+ if (files.length === 0 && !(hasInlineClasses && !hasUserPositiveGlobs)) {
267
+ warnings.push(
268
+ `[RI-1401] No source files found matching ${allIncludes.map((p) => `"${p}"`).join(", ")} \u2014 check @source paths or project structure.`
269
+ );
270
+ }
271
+ return { files, warnings };
272
+ } catch (err) {
273
+ warnings.push(
274
+ `[RI-1402] Invalid glob pattern \u2014 skipping. Check @source syntax. (${err instanceof Error ? err.message : String(err)})`
275
+ );
276
+ return { files: [], warnings };
277
+ }
278
+ }
279
+ function collectInlineClasses(sources) {
280
+ const classes = /* @__PURE__ */ new Set();
281
+ const warnings = [];
282
+ for (const src of sources) {
283
+ if (!src.inline) continue;
284
+ const items = src.classes ?? [];
285
+ let contentLength = 0;
286
+ for (const cls of items) contentLength += cls.length;
287
+ if (contentLength > MAX_INLINE_SOURCE_SIZE) {
288
+ warnings.push(
289
+ `[RI-1406] Inline @source content exceeds ${MAX_INLINE_SOURCE_SIZE} byte limit (${contentLength} bytes) \u2014 skipping.`
290
+ );
291
+ continue;
292
+ }
293
+ for (const cls of items) {
294
+ if (cls) classes.add(cls);
295
+ }
296
+ }
297
+ return { classes, warnings };
298
+ }
299
+ var FILE_IO_TIMEOUT_MS = 1e4;
300
+ var SCAN_CACHE_MAX_ENTRIES = 2e4;
301
+ var scanCache = /* @__PURE__ */ new Map();
302
+ var scanChangeTrackingEnabled = false;
303
+ function enableScanChangeTracking() {
304
+ scanChangeTrackingEnabled = true;
305
+ }
306
+ function markSourceFileChanged(file, cwd) {
307
+ scanCache.delete(cwd === void 0 ? file : resolve2(cwd, file));
308
+ }
309
+ function disableScanChangeTracking() {
310
+ scanChangeTrackingEnabled = false;
311
+ scanCache.clear();
312
+ }
313
+ var fileUnion = null;
314
+ function applyToUnion(union, result, delta) {
315
+ if (!result?.classes) return;
316
+ for (const cls of result.classes) {
317
+ const next = (union.counts.get(cls) ?? 0) + delta;
318
+ if (next > 0) {
319
+ union.counts.set(cls, next);
320
+ if (delta === 1) union.classes.add(cls);
321
+ } else {
322
+ union.counts.delete(cls);
323
+ union.classes.delete(cls);
324
+ }
325
+ }
326
+ }
327
+ async function scanOneFile(file) {
328
+ const warnings = [];
329
+ if (scanChangeTrackingEnabled) {
330
+ const tracked = scanCache.get(file);
331
+ if (tracked) return tracked.result;
332
+ }
333
+ try {
334
+ const stats = await withTimeout(stat(file), FILE_IO_TIMEOUT_MS, "stat() timed out");
335
+ const cached = scanCache.get(file);
336
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
337
+ return cached.result;
338
+ }
339
+ let result;
340
+ if (stats.size > MAX_FILE_SIZE) {
341
+ result = {
342
+ classes: null,
343
+ warnings,
344
+ failure: `[RI-1405] Skipping source file "${file}" (${stats.size} bytes) \u2014 exceeds ${MAX_FILE_SIZE} byte limit.`
345
+ };
346
+ } else {
347
+ const content = await withTimeout(
348
+ readFile(file, "utf-8"),
349
+ FILE_IO_TIMEOUT_MS,
350
+ "readFile() timed out"
351
+ );
352
+ result = {
353
+ classes: extractClassesFromSource({ path: file, content }, warnings),
354
+ warnings,
355
+ failure: null
356
+ };
357
+ }
358
+ if (scanCache.size >= SCAN_CACHE_MAX_ENTRIES) scanCache.clear();
359
+ scanCache.set(file, { mtimeMs: stats.mtimeMs, size: stats.size, result });
360
+ return result;
361
+ } catch (err) {
362
+ return {
363
+ classes: null,
364
+ warnings,
365
+ failure: `[RI-1403] Could not read source file "${file}" \u2014 skipping. (${err instanceof Error ? err.message : String(err)})`
366
+ };
367
+ }
368
+ }
369
+ async function scanSourceFilesAsync(sources, cwd) {
370
+ const { classes: allClasses, warnings: inlineWarnings } = collectInlineClasses(sources);
371
+ const authored = new Set(allClasses);
372
+ const allWarnings = [...inlineWarnings];
373
+ const { files, warnings: resolveWarnings } = await resolveSourceFilesAsync(
374
+ sources,
375
+ cwd,
376
+ allClasses.size > 0
377
+ );
378
+ allWarnings.push(...resolveWarnings);
379
+ const CONCURRENCY_LIMIT = 32;
380
+ const results = new Array(files.length);
381
+ let nextIndex = 0;
382
+ const worker = async () => {
383
+ while (nextIndex < files.length) {
384
+ const index = nextIndex++;
385
+ results[index] = await scanOneFile(files[index]);
386
+ }
387
+ };
388
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY_LIMIT, files.length) }, worker));
389
+ const seen = new Set(allWarnings);
390
+ for (const result of results) {
391
+ if (result.failure) {
392
+ allWarnings.push(result.failure);
393
+ seen.add(result.failure);
394
+ continue;
395
+ }
396
+ pushWarningsDeduped(allWarnings, result.warnings, seen);
397
+ }
398
+ if (fileUnion === null || fileUnion.results.length !== results.length) {
399
+ fileUnion = { results, counts: /* @__PURE__ */ new Map(), classes: /* @__PURE__ */ new Set() };
400
+ for (const result of results) applyToUnion(fileUnion, result, 1);
401
+ } else {
402
+ const previous = fileUnion.results;
403
+ for (let i = 0; i < results.length; i++) {
404
+ if (previous[i] === results[i]) continue;
405
+ applyToUnion(fileUnion, previous[i], -1);
406
+ applyToUnion(fileUnion, results[i], 1);
407
+ }
408
+ fileUnion.results = results;
409
+ }
410
+ for (const cls of fileUnion.classes) allClasses.add(cls);
411
+ return { classes: allClasses, authored, warnings: allWarnings };
412
+ }
413
+ async function collectProjectClasses(themeSources, surfaceSources, cwd, warnings, warningSeen, suppressed) {
414
+ const discovered = discoverPackageSafelistSources(cwd);
415
+ pushWarningsDeduped(warnings, discovered.warnings, warningSeen, suppressed);
416
+ const allSources = [...themeSources, ...surfaceSources, ...discovered.sources];
417
+ const scanResult = await scanSourceFilesAsync(allSources, cwd);
418
+ pushWarningsDeduped(warnings, scanResult.warnings, warningSeen, suppressed);
419
+ return { classes: scanResult.classes, authored: scanResult.authored };
420
+ }
421
+
422
+ // src/integrations/font-providers/google/state.ts
423
+ var googleFontInternals = {
424
+ googleFontState: { cache: /* @__PURE__ */ new Map(), fetched: false },
425
+ googleFontListPromise: null,
426
+ lastFetchFailureMs: 0,
427
+ validatedCacheDir: null,
428
+ resolvedCachePath: null
429
+ };
430
+
431
+ // src/integrations/font-providers/google/cache.ts
432
+ import { createHash, randomUUID } from "crypto";
433
+ import { open as fsOpen, writeFile, rename, unlink, mkdir } from "fs/promises";
434
+ import { resolve as resolve3, dirname as dirname2, join as join2, isAbsolute as isAbsolute2 } from "path";
435
+ import { isAbsolute as win32IsAbsolute } from "path/win32";
436
+ var MAX_FONT_CACHE_TTL_SECONDS = 30 * 24 * 60 * 60;
437
+ function getFontCacheDir() {
438
+ if (googleFontInternals.validatedCacheDir !== null) return googleFontInternals.validatedCacheDir;
439
+ const raw = process.env.RI_CACHE_DIR || "node_modules/.cache/rainbowindex";
440
+ if (isAbsolute2(raw) || win32IsAbsolute(raw)) {
441
+ throw new Error(
442
+ `[RI-1208] RI_CACHE_DIR must be a relative path, got absolute path: "${raw}". Use a relative path like "node_modules/.cache/rainbowindex".`
443
+ );
444
+ }
445
+ if (raw.split(/[\\/]/).some((s) => s === "..")) {
446
+ throw new Error(
447
+ `[RI-1209] RI_CACHE_DIR must not contain ".." segments: "${raw}". Use a direct relative path like "node_modules/.cache/rainbowindex".`
448
+ );
449
+ }
450
+ googleFontInternals.validatedCacheDir = raw;
451
+ return raw;
452
+ }
453
+ function getFontCacheFile() {
454
+ return `${getFontCacheDir()}/google.json`;
455
+ }
456
+ function getResolvedCachePath() {
457
+ if (googleFontInternals.resolvedCachePath !== null && googleFontInternals.validatedCacheDir !== null) {
458
+ return googleFontInternals.resolvedCachePath;
459
+ }
460
+ googleFontInternals.resolvedCachePath = resolve3(process.cwd(), getFontCacheFile());
461
+ return googleFontInternals.resolvedCachePath;
462
+ }
463
+ function getFontCacheTTL() {
464
+ const envVal = process.env.RI_FONT_CACHE_TTL;
465
+ if (envVal) {
466
+ const seconds = Number(envVal);
467
+ if (!Number.isNaN(seconds) && seconds >= 0) {
468
+ if (seconds > MAX_FONT_CACHE_TTL_SECONDS) {
469
+ console.warn(
470
+ `[RI-1211] RI_FONT_CACHE_TTL=${seconds} exceeds maximum of ${MAX_FONT_CACHE_TTL_SECONDS} seconds (30 days). Clamping to 30 days.`
471
+ );
472
+ return MAX_FONT_CACHE_TTL_SECONDS * 1e3;
473
+ }
474
+ return seconds * 1e3;
475
+ }
476
+ }
477
+ return 7 * 24 * 60 * 60 * 1e3;
478
+ }
479
+ function parseCachedMetaEntries(raw) {
480
+ const parsed = JSON.parse(raw);
481
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !("checksum" in parsed) || !("entries" in parsed)) {
482
+ return null;
483
+ }
484
+ if (!Array.isArray(parsed.entries)) return null;
485
+ const entriesJson = JSON.stringify(parsed.entries);
486
+ const expected = createHash("sha256").update(entriesJson).digest("hex");
487
+ if (typeof parsed.checksum !== "string" || parsed.checksum !== expected) return null;
488
+ const entries = parsed.entries;
489
+ const newCache = /* @__PURE__ */ new Map();
490
+ for (const rawItem of entries) {
491
+ if (!rawItem || typeof rawItem !== "object") continue;
492
+ const item = rawItem;
493
+ if (typeof item.family !== "string" || typeof item.variable !== "boolean" || typeof item.category !== "string" || item.axes !== void 0 && !Array.isArray(item.axes)) {
494
+ continue;
495
+ }
496
+ if (!SAFE_FONT_FAMILY_RE.test(item.family)) continue;
497
+ const axes = Array.isArray(item.axes) ? item.axes.filter((a) => {
498
+ if (!a || typeof a !== "object") return false;
499
+ const axis = a;
500
+ return typeof axis.tag === "string" && typeof axis.start === "number" && Number.isFinite(axis.start) && typeof axis.end === "number" && Number.isFinite(axis.end);
501
+ }).map((a) => {
502
+ const axis = { tag: a.tag, start: a.start, end: a.end };
503
+ Object.freeze(axis);
504
+ return axis;
505
+ }) : void 0;
506
+ if (axes) Object.freeze(axes);
507
+ const entry = {
508
+ family: item.family,
509
+ variable: item.variable,
510
+ axes,
511
+ category: item.category
512
+ };
513
+ Object.freeze(entry);
514
+ newCache.set(entry.family, entry);
515
+ }
516
+ return newCache.size > 0 ? newCache : null;
517
+ }
518
+ async function loadFontCache(ignoreExpiry = false) {
519
+ try {
520
+ const cachePath = getResolvedCachePath();
521
+ const fh = await fsOpen(cachePath, "r");
522
+ let raw;
523
+ try {
524
+ if (!ignoreExpiry) {
525
+ const st = await fh.stat();
526
+ if (Date.now() - st.mtimeMs > getFontCacheTTL()) return false;
527
+ }
528
+ raw = await fh.readFile("utf-8");
529
+ } finally {
530
+ await fh.close();
531
+ }
532
+ const newCache = parseCachedMetaEntries(raw);
533
+ if (!newCache) return false;
534
+ googleFontInternals.googleFontState = { cache: newCache, fetched: true };
535
+ return true;
536
+ } catch {
537
+ return false;
538
+ }
539
+ }
540
+ async function saveFontCache() {
541
+ try {
542
+ const cachePath = getResolvedCachePath();
543
+ await mkdir(dirname2(cachePath), { recursive: true });
544
+ const entries = Array.from(googleFontInternals.googleFontState.cache.values());
545
+ const entriesJson = JSON.stringify(entries);
546
+ const checksum = createHash("sha256").update(entriesJson).digest("hex");
547
+ const payload = `{"checksum":${JSON.stringify(checksum)},"entries":${entriesJson}}`;
548
+ const tmpPath = join2(dirname2(cachePath), `.google-${process.pid}-${randomUUID()}.tmp`);
549
+ try {
550
+ await writeFile(tmpPath, payload);
551
+ await rename(tmpPath, cachePath);
552
+ } finally {
553
+ await unlink(tmpPath).catch(() => {
554
+ });
555
+ }
556
+ } catch (err) {
557
+ const reason = err instanceof Error ? err.message : String(err);
558
+ console.warn(
559
+ `[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.`
560
+ );
561
+ }
562
+ }
563
+
564
+ // src/integrations/font-providers/google/client.ts
565
+ var MAX_RESPONSE_SIZE = 10 * 1024 * 1024;
566
+ var MAX_RETRIES = 2;
567
+ var FETCH_TIMEOUT_MS = 5e3;
568
+ function wait(ms) {
569
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
570
+ }
571
+ function toGoogleFontMetaMap(data) {
572
+ const newCache = /* @__PURE__ */ new Map();
573
+ for (const font of data.familyMetadataList) {
574
+ const wghtAxis = font.axes.find((a) => a.tag === "wght");
575
+ const axes = font.axes.map((a) => {
576
+ const axis = { tag: a.tag, start: a.min, end: a.max };
577
+ Object.freeze(axis);
578
+ return axis;
579
+ });
580
+ Object.freeze(axes);
581
+ const entry = {
582
+ family: font.family,
583
+ variable: wghtAxis ? wghtAxis.min !== wghtAxis.max : false,
584
+ axes,
585
+ category: font.category
586
+ };
587
+ Object.freeze(entry);
588
+ newCache.set(font.family, entry);
589
+ }
590
+ return newCache;
591
+ }
592
+ async function readJsonResponse(res) {
593
+ const reader = res.body?.getReader();
594
+ if (!reader) {
595
+ throw new Error("[RI-1207] Google Fonts metadata response has no readable body.");
596
+ }
597
+ const chunks = [];
598
+ let totalBytes = 0;
599
+ for (; ; ) {
600
+ const { done, value } = await reader.read();
601
+ if (done) break;
602
+ totalBytes += value.byteLength;
603
+ if (totalBytes > MAX_RESPONSE_SIZE) {
604
+ reader.cancel();
605
+ throw new Error(
606
+ `[RI-1207] Google Fonts metadata response too large (>${MAX_RESPONSE_SIZE} bytes).`
607
+ );
608
+ }
609
+ chunks.push(value);
610
+ }
611
+ const text = new TextDecoder().decode(
612
+ chunks.length === 1 ? chunks[0] : await new Blob(chunks).arrayBuffer()
613
+ );
614
+ return JSON.parse(text);
615
+ }
616
+ async function fetchGoogleFontMetadata() {
617
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
618
+ const controller = new AbortController();
619
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
620
+ try {
621
+ const res = await fetch("https://fonts.google.com/metadata/fonts", {
622
+ signal: controller.signal
623
+ });
624
+ const contentLength = res.headers.get("content-length");
625
+ if (contentLength && Number(contentLength) > MAX_RESPONSE_SIZE) {
626
+ throw new Error(
627
+ `[RI-1207] Google Fonts metadata response too large (${contentLength} bytes).`
628
+ );
629
+ }
630
+ if (!res.ok) {
631
+ throw new Error(`[RI-1205] Google Fonts metadata request failed with HTTP ${res.status}.`);
632
+ }
633
+ const contentType = res.headers.get("content-type") ?? "";
634
+ if (contentType && !contentType.includes("json")) {
635
+ throw new Error(
636
+ `[RI-1207] Google Fonts metadata returned unexpected Content-Type "${contentType}" instead of JSON.`
637
+ );
638
+ }
639
+ const data = await readJsonResponse(res);
640
+ return toGoogleFontMetaMap(data);
641
+ } catch (err) {
642
+ if (attempt < MAX_RETRIES) {
643
+ await wait(1e3 * 2 ** attempt);
644
+ continue;
645
+ }
646
+ throw err;
647
+ } finally {
648
+ clearTimeout(timeout);
649
+ }
650
+ }
651
+ throw new Error("[RI-1205] Exhausted Google Fonts metadata fetch retries.");
652
+ }
653
+
654
+ // src/integrations/font-providers/google/index.ts
655
+ var FETCH_RETRY_COOLDOWN_MS = 3e4;
656
+ async function fetchGoogleFontList() {
657
+ if (googleFontInternals.googleFontState.fetched) return;
658
+ if (googleFontInternals.googleFontListPromise) return googleFontInternals.googleFontListPromise;
659
+ if (googleFontInternals.lastFetchFailureMs > 0 && Date.now() - googleFontInternals.lastFetchFailureMs < FETCH_RETRY_COOLDOWN_MS) {
660
+ return;
661
+ }
662
+ const localPromise = (async () => {
663
+ try {
664
+ const isOffline = process.env.RI_OFFLINE === "1" || process.env.RI_OFFLINE === "true";
665
+ if (isOffline) {
666
+ if (await loadFontCache(true)) return;
667
+ console.warn(
668
+ `[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.`
669
+ );
670
+ return;
671
+ }
672
+ if (await loadFontCache()) return;
673
+ const fetchDisabled = process.env.RI_FETCH_FONTS === "0" || process.env.RI_FETCH_FONTS === "false";
674
+ if (fetchDisabled) {
675
+ if (await loadFontCache(true)) return;
676
+ return;
677
+ }
678
+ if (typeof globalThis.fetch !== "function") {
679
+ console.warn(
680
+ "[RI-1212] Global fetch() is not available. Google Fonts metadata requires Node.js >= 18. Skipping font fetch."
681
+ );
682
+ return;
683
+ }
684
+ if (isRIDebug()) {
685
+ console.warn("[RI-DEBUG] Fetching Google Fonts metadata...");
686
+ }
687
+ try {
688
+ const newCache = await fetchGoogleFontMetadata();
689
+ googleFontInternals.googleFontState = { cache: newCache, fetched: true };
690
+ await saveFontCache();
691
+ return;
692
+ } catch (err) {
693
+ const message = err instanceof Error ? err.message : String(err);
694
+ if (message.startsWith("[RI-1207]")) {
695
+ console.warn(`${message} Skipping.`);
696
+ if (await loadFontCache(true)) return;
697
+ return;
698
+ }
699
+ if (await loadFontCache(true)) return;
700
+ console.warn(
701
+ `[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.`
702
+ );
703
+ }
704
+ } finally {
705
+ if (!googleFontInternals.googleFontState.fetched) {
706
+ googleFontInternals.lastFetchFailureMs = Date.now();
707
+ }
708
+ googleFontInternals.googleFontListPromise = null;
709
+ }
710
+ })();
711
+ googleFontInternals.googleFontListPromise = localPromise;
712
+ return localPromise;
713
+ }
714
+ var refreshMemo = /* @__PURE__ */ new WeakMap();
715
+ function refreshFontWeightDefaults(fonts) {
716
+ const state = googleFontInternals.googleFontState;
717
+ const memo = refreshMemo.get(fonts);
718
+ if (memo && memo.state === state) return memo.result;
719
+ let anyChanged = false;
720
+ const refreshed = fonts.map((slot) => {
721
+ if (slot.kind !== "google") return slot;
722
+ const meta = googleFontInternals.googleFontState.cache.get(slot.family);
723
+ if (!meta) return slot;
724
+ let changed = false;
725
+ const faces = slot.faces.map((f) => {
726
+ let next = f;
727
+ if (!f._weightExplicit) {
728
+ const wghtAxis = meta.axes?.find((a) => a.tag === "wght");
729
+ const axisWeight = wghtAxis && wghtAxis.start !== wghtAxis.end ? `${wghtAxis.start} ${wghtAxis.end}` : "400";
730
+ if (next.weight !== axisWeight) next = { ...next, weight: axisWeight };
731
+ }
732
+ if (!f._styleExplicit) {
733
+ const italAxis = meta.axes?.find((a) => a.tag === "ital");
734
+ const axisStyle = italAxis ? "normal italic" : "normal";
735
+ if (next.style !== axisStyle) next = { ...next, style: axisStyle };
736
+ }
737
+ if (next !== f) changed = true;
738
+ return next;
739
+ });
740
+ if (changed) anyChanged = true;
741
+ return changed ? { ...slot, faces } : slot;
742
+ });
743
+ const result = anyChanged ? refreshed : fonts;
744
+ refreshMemo.set(fonts, { state, result });
745
+ return result;
746
+ }
747
+ var FONT_FETCH_TIMEOUT_MS = 1e4;
748
+ async function resolveGoogleFonts(fonts) {
749
+ if (!fonts.some((slot) => slot.kind === "google")) return fonts;
750
+ try {
751
+ await withTimeout(
752
+ fetchGoogleFontList(),
753
+ FONT_FETCH_TIMEOUT_MS,
754
+ "[RI-1213] Google Fonts metadata fetch timed out"
755
+ );
756
+ } catch {
757
+ console.warn(
758
+ `[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.`
759
+ );
760
+ }
761
+ return refreshFontWeightDefaults(fonts);
762
+ }
763
+
764
+ // src/project/pipeline.ts
765
+ function collectApplyClassNames(css, warnings, cssPath) {
766
+ const classes = [];
767
+ for (const match of css.matchAll(APPLY_LIKE_MATCH_RE)) {
768
+ const params = expandApplyBodyGroups(match[1], warnings, cssPath);
769
+ for (const className of params.trim().split(/\s+/)) {
770
+ if (className) classes.push(className);
771
+ }
772
+ }
773
+ return classes;
774
+ }
775
+ var effectiveThemeMemo = /* @__PURE__ */ new WeakMap();
776
+ async function finalizeProjectCompilation(options) {
777
+ const { analysis } = options;
778
+ let effectiveTheme = analysis.theme;
779
+ if (options.resolveFonts) {
780
+ const resolvedFonts = await options.resolveFonts(analysis.theme.fonts);
781
+ if (resolvedFonts !== analysis.theme.fonts) {
782
+ const memo = effectiveThemeMemo.get(analysis.theme);
783
+ if (memo && memo.fonts === resolvedFonts) {
784
+ effectiveTheme = memo.theme;
785
+ } else {
786
+ effectiveTheme = { ...analysis.theme, fonts: [...resolvedFonts] };
787
+ effectiveThemeMemo.set(analysis.theme, { fonts: resolvedFonts, theme: effectiveTheme });
788
+ }
789
+ }
790
+ }
791
+ const expansionWarnings = [];
792
+ const classNameSet = new Set(options.classNames);
793
+ const authored = options.authoredClassNames && new Set(options.authoredClassNames);
794
+ for (const cls of collectApplyClassNames(options.css, expansionWarnings, options.cssPath)) {
795
+ classNameSet.add(cls);
796
+ authored?.add(cls);
797
+ }
798
+ const classNames = [...classNameSet];
799
+ pushWarningsDeduped(
800
+ analysis.warnings,
801
+ expansionWarnings,
802
+ analysis.warningSeen,
803
+ analysis.suppressed
804
+ );
805
+ const compiler = createCompiler();
806
+ const compilation = compiler.compile(classNames, effectiveTheme, authored);
807
+ let userCSS = stripRIDirectives(options.css);
808
+ if ((options.processCssFunctions ?? true) && userCSS && hasCSSFunctions(userCSS)) {
809
+ userCSS = compileCSSFunctions(userCSS, effectiveTheme, analysis.warnings);
810
+ }
811
+ if (userCSS) {
812
+ scanCSSForTokenUsage(userCSS, compilation);
813
+ }
814
+ const { sections, warnings: assemblyWarnings } = assembleSections(
815
+ compilation,
816
+ effectiveTheme,
817
+ compiler.fontOutputCache
818
+ );
819
+ pushWarningsDeduped(
820
+ analysis.warnings,
821
+ assemblyWarnings,
822
+ analysis.warningSeen,
823
+ analysis.suppressed
824
+ );
825
+ pushWarningsDeduped(
826
+ analysis.warnings,
827
+ compilation.warnings,
828
+ analysis.warningSeen,
829
+ analysis.suppressed
830
+ );
831
+ let joinedCSS = null;
832
+ return {
833
+ get css() {
834
+ if (joinedCSS === null) {
835
+ joinedCSS = userCSS ? [...sections, userCSS].join("\n\n") : sections.join("\n\n");
836
+ }
837
+ return joinedCSS;
838
+ },
839
+ sections,
840
+ userCSS,
841
+ classNames,
842
+ theme: effectiveTheme,
843
+ directives: analysis.directives,
844
+ warnings: analysis.warnings,
845
+ suppressed: analysis.suppressed
846
+ };
847
+ }
848
+
849
+ // src/project/scan.ts
850
+ async function compileScannedProject(options) {
851
+ const resolveImport = options.resolveImport === void 0 ? createNodeImportResolver({ cwd: options.cwd }) : options.resolveImport;
852
+ const inlined = resolveImport === null ? { css: options.css, warnings: [] } : inlineDirectiveImports(options.css, { resolve: resolveImport, from: options.cssPath });
853
+ const analysis = analyzeProjectCSSMemo(inlined.css);
854
+ pushWarningsDeduped(
855
+ analysis.warnings,
856
+ inlined.warnings,
857
+ analysis.warningSeen,
858
+ analysis.suppressed
859
+ );
860
+ const resolveFonts = options.resolveFonts ?? resolveGoogleFonts;
861
+ const fontsReady = Promise.resolve(resolveFonts(analysis.theme.fonts));
862
+ fontsReady.catch(() => {
863
+ });
864
+ const surfaceSources = [];
865
+ for (const pattern of options.surfacePatterns ?? []) {
866
+ const error = validateGlobPattern(pattern);
867
+ if (error) {
868
+ const warning = options.onInvalidPattern(error);
869
+ if (warning !== void 0) {
870
+ pushWarningsDeduped(
871
+ analysis.warnings,
872
+ [warning],
873
+ analysis.warningSeen,
874
+ analysis.suppressed
875
+ );
876
+ }
877
+ continue;
878
+ }
879
+ surfaceSources.push({ pattern, negated: false, inline: false });
880
+ }
881
+ const { classes: classNames, authored } = await collectProjectClasses(
882
+ analysis.theme.sources,
883
+ surfaceSources,
884
+ options.cwd,
885
+ analysis.warnings,
886
+ analysis.warningSeen,
887
+ analysis.suppressed
888
+ );
889
+ const compiled = await finalizeProjectCompilation({
890
+ css: inlined.css,
891
+ cssPath: options.cssPath,
892
+ classNames,
893
+ authoredClassNames: authored,
894
+ analysis,
895
+ resolveFonts: () => fontsReady
896
+ });
897
+ return { compiled, warningSeen: analysis.warningSeen };
898
+ }
899
+
900
+ export {
901
+ resolveGoogleFonts,
902
+ DEFAULT_PATTERNS,
903
+ DEFAULT_EXCLUDES,
904
+ enableSourceFileListCache,
905
+ invalidateSourceFileListCache,
906
+ resolveSourceFilesAsync,
907
+ enableScanChangeTracking,
908
+ markSourceFileChanged,
909
+ disableScanChangeTracking,
910
+ finalizeProjectCompilation,
911
+ compileScannedProject
912
+ };