@fluentic/style 0.1.0-beta.17 → 0.1.0-beta.18

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 (82) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/compiler/compiler/cache_identity.ts +115 -0
  3. package/compiler/compiler/compiler.ts +21 -1
  4. package/compiler/compiler/persistent_cache.ts +310 -0
  5. package/compiler/compiler/types.ts +12 -0
  6. package/compiler/extract/collector.ts +2 -2
  7. package/compiler/transform/evaluator/metadata_cache.ts +124 -0
  8. package/compiler/transform/evaluator/tracer.ts +71 -63
  9. package/compiler/transform/extract/plugin.ts +2 -0
  10. package/compiler/utils/check_diagnostics.ts +18 -0
  11. package/compiler/utils/file_resolver.ts +24 -0
  12. package/dist/combine-BpOQWCtM.js.map +1 -1
  13. package/dist/compiler/index.mjs +1 -1
  14. package/dist/{compiler-Cat8TmMk.mjs → compiler-Dpd41bCS.mjs} +552 -41
  15. package/dist/compiler-Dpd41bCS.mjs.map +1 -0
  16. package/dist/entry/rsc-dev.js.map +1 -1
  17. package/dist/{loader-Cvz2pKYV.mjs → loader-CR_NH6ub.mjs} +3 -3
  18. package/dist/{loader-Cvz2pKYV.mjs.map → loader-CR_NH6ub.mjs.map} +1 -1
  19. package/dist/{misc-BKaSZF14.mjs → misc-D5AjOWP-.mjs} +3 -3
  20. package/dist/misc-D5AjOWP-.mjs.map +1 -0
  21. package/dist/plugin/farm/index.mjs +4 -4
  22. package/dist/plugin/farm/index.mjs.map +1 -1
  23. package/dist/plugin/nextjs/index.mjs +5 -5
  24. package/dist/plugin/nextjs/index.mjs.map +1 -1
  25. package/dist/plugin/nextjs/loader.mjs +4 -4
  26. package/dist/plugin/parcel/index.cjs +1 -1
  27. package/dist/plugin/parcel/index.mjs +2 -2
  28. package/dist/plugin/parcel/optimizer.cjs +1 -1
  29. package/dist/plugin/parcel/optimizer.mjs +2 -2
  30. package/dist/plugin/parcel/resolver.cjs +1 -1
  31. package/dist/plugin/parcel/resolver.mjs +2 -2
  32. package/dist/plugin/parcel/runtime.cjs +1 -1
  33. package/dist/plugin/parcel/runtime.mjs +1 -1
  34. package/dist/plugin/parcel/transformer.cjs +1 -1
  35. package/dist/plugin/parcel/transformer.mjs +2 -2
  36. package/dist/plugin/rspack/index.mjs +2 -2
  37. package/dist/plugin/vite/index.mjs +6 -6
  38. package/dist/plugin/vite/index.mjs.map +1 -1
  39. package/dist/plugin/webpack/index.mjs +2 -2
  40. package/dist/plugin/webpack/loader.mjs +2 -2
  41. package/dist/{registry-Bbxm5X90.mjs → registry-CdSHrX-o.mjs} +2 -2
  42. package/dist/{registry-Bbxm5X90.mjs.map → registry-CdSHrX-o.mjs.map} +1 -1
  43. package/dist/{shared-L-63tURh.cjs → shared-CcB1KDFI.cjs} +557 -47
  44. package/dist/shared-CcB1KDFI.cjs.map +1 -0
  45. package/dist/{shared-BVciI9ew.mjs → shared-CobOEWzt.mjs} +5 -5
  46. package/dist/shared-CobOEWzt.mjs.map +1 -0
  47. package/dist/{sidecar-B7Q2P71F.mjs → sidecar-CHDVQqN_.mjs} +3 -3
  48. package/dist/{sidecar-B7Q2P71F.mjs.map → sidecar-CHDVQqN_.mjs.map} +1 -1
  49. package/dist/style-CRs-vfY1.js.map +1 -1
  50. package/dist/types/compiler/compiler/cache_identity.d.ts +4 -0
  51. package/dist/types/compiler/compiler/compiler.d.ts +12 -0
  52. package/dist/types/compiler/compiler/persistent_cache.d.ts +14 -0
  53. package/dist/types/compiler/compiler/types.d.ts +11 -0
  54. package/dist/types/compiler/extract/collector.d.ts +1 -1
  55. package/dist/types/compiler/transform/evaluator/metadata_cache.d.ts +13 -0
  56. package/dist/types/compiler/transform/evaluator/tracer.d.ts +6 -0
  57. package/dist/types/compiler/utils/check_diagnostics.d.ts +7 -0
  58. package/dist/types/compiler/utils/file_resolver.d.ts +4 -0
  59. package/dist/types/plugin/bundler/vite/state.d.ts +24 -0
  60. package/dist/types/plugin/utils/compiler.d.ts +12 -1
  61. package/dist/types/style/tokens.d.ts +1 -1
  62. package/dist/{utils-D2QdzQkX.mjs → utils-CICsXGqS.mjs} +5 -5
  63. package/dist/utils-CICsXGqS.mjs.map +1 -0
  64. package/dist/{utils-D3KR1ht8.mjs → utils-XfsnoteV.mjs} +3 -3
  65. package/dist/{utils-D3KR1ht8.mjs.map → utils-XfsnoteV.mjs.map} +1 -1
  66. package/dist/{webpack-DRegoWgj.mjs → webpack-BAflvDbq.mjs} +6 -6
  67. package/dist/webpack-BAflvDbq.mjs.map +1 -0
  68. package/package.json +1 -1
  69. package/plugin/bundler/farm/plugin.ts +1 -1
  70. package/plugin/bundler/parcel/shared.ts +1 -1
  71. package/plugin/bundler/vite/state.ts +5 -6
  72. package/plugin/bundler/webpack/plugin.ts +1 -1
  73. package/plugin/nextjs/plugin.ts +1 -1
  74. package/plugin/nextjs/utils.ts +1 -1
  75. package/plugin/utils/compiler.ts +1 -2
  76. package/style/tokens.ts +2 -1
  77. package/dist/compiler-Cat8TmMk.mjs.map +0 -1
  78. package/dist/misc-BKaSZF14.mjs.map +0 -1
  79. package/dist/shared-BVciI9ew.mjs.map +0 -1
  80. package/dist/shared-L-63tURh.cjs.map +0 -1
  81. package/dist/utils-D2QdzQkX.mjs.map +0 -1
  82. package/dist/webpack-DRegoWgj.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @fluentic/style
2
2
 
3
+ ## 0.1.0-beta.18
4
+
5
+ ### Patch Changes
6
+
7
+ - Enable persistent production transform caching by default, with content and resolution validation across dependency chains, compiler versions, and configuration changes. Restore immutable tracer syntax metadata across builds and safely reuse evaluated imports within a build. Configure caching with `cache: { persistent, dynamicConfig, version, location }`. Persistence and callback source fingerprinting default to enabled; change `cache.version` when captured or external callback inputs change. The former `persistentCache` and plugin `cacheDir` options are removed.
8
+
9
+ Cache and replay check warnings and failures, including code frames, with dependency and severity invalidation. Preserve collected CSS when restoring transforms and avoid unnecessary production source-map callbacks in the Vite adapter. Add regression coverage for stale dependencies, changed resolution, corrupt caches, process restarts, lazy exports, and circular imports.
10
+
11
+ Preserve callable token types when existing tokens are passed to `createTokens`.
12
+
3
13
  ## 0.1.0-beta.17
4
14
 
5
15
  ### Patch Changes
@@ -0,0 +1,115 @@
1
+ import { createHash } from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ let identity: string | null | undefined;
8
+
9
+ /** Fingerprint actual compiler and dependency bytes, including locally patched packages.
10
+ * Computed once per process: replacing loaded compiler code requires restarting Node.
11
+ */
12
+ export function getCompilerCacheIdentity(): string | null {
13
+ if (identity !== undefined) return identity;
14
+ try {
15
+ const filename = typeof __filename === 'string' ? __filename : fileURLToPath(import.meta.url);
16
+ const root = findPackageRoot(filename, '@fluentic/style');
17
+ const hash = createHash('sha256');
18
+ hash.update(JSON.stringify([
19
+ process.versions,
20
+ process.platform,
21
+ process.arch,
22
+ process.execArgv,
23
+ process.env.NODE_OPTIONS,
24
+ process.env.NODE_ENV,
25
+ process.env.BABEL_ENV,
26
+ ]));
27
+ const visited = new Set<string>();
28
+ const hashTree = (directory: string, source = false) => {
29
+ for (
30
+ const item of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))
31
+ ) {
32
+ if (item.name === 'node_modules' || item.name === '.git') continue;
33
+ const file = path.join(directory, item.name);
34
+ if (item.isDirectory()) hashTree(file, source);
35
+ else if (item.isFile()) {
36
+ // Declarations, source maps and documentation are not executable compiler inputs.
37
+ if (!(source ? /\.(?:[cm]?[jt]sx?|json|node|wasm)$/ : /\.(?:[cm]?js|json|node|wasm)$/).test(item.name)) {
38
+ continue;
39
+ }
40
+ hash.update(file).update('\0').update(fs.readFileSync(file)).update('\0');
41
+ } else {
42
+ // Unusual package layouts should rebuild, not silently omit inputs.
43
+ throw new Error('Unsupported package entry');
44
+ }
45
+ }
46
+ };
47
+ const visit = (directory: string) => {
48
+ directory = fs.realpathSync(directory);
49
+ if (visited.has(directory)) return;
50
+ visited.add(directory);
51
+ hashTree(directory);
52
+ const manifest = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf8'));
53
+ const require = createRequire(path.join(directory, 'package.json'));
54
+ const optional = manifest.optionalDependencies ?? {};
55
+ for (const name of Object.keys({ ...manifest.dependencies, ...optional }).sort()) {
56
+ let dependency: string;
57
+ try {
58
+ dependency = resolvePackageRoot(require, name);
59
+ } catch (error) {
60
+ if (name in optional) {
61
+ hash.update('absent:' + name);
62
+ continue;
63
+ }
64
+ throw error;
65
+ }
66
+ visit(dependency);
67
+ }
68
+ };
69
+ const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
70
+ hash.update(fs.readFileSync(path.join(root, 'package.json')));
71
+ // Hash the implementation actually loaded. Packed builds execute dist, not shipped TS.
72
+ if (filename.startsWith(path.join(root, 'dist') + path.sep)) {
73
+ hashTree(path.join(root, 'dist'));
74
+ } else {
75
+ for (const item of manifest.files as string[]) {
76
+ if (item === 'dist') continue;
77
+ const file = path.join(root, item);
78
+ if (!fs.existsSync(file)) continue;
79
+ if (fs.statSync(file).isDirectory()) hashTree(file, true);
80
+ else if (/\.[cm]?[jt]sx?$/.test(item)) hash.update(item).update(fs.readFileSync(file));
81
+ }
82
+ }
83
+ const require = createRequire(path.join(root, 'package.json'));
84
+ for (const name of ['@babel/core', '@jridgewell/trace-mapping', 'css-what', 'oxc-resolver', 'picomatch']) {
85
+ visit(resolvePackageRoot(require, name));
86
+ }
87
+ identity = hash.digest('hex');
88
+ } catch {
89
+ identity = null;
90
+ }
91
+ return identity;
92
+ }
93
+
94
+ function resolvePackageRoot(require: NodeRequire, name: string): string {
95
+ for (const directory of require.resolve.paths(name) ?? []) {
96
+ const root = path.join(directory, name);
97
+ if (fs.existsSync(path.join(root, 'package.json'))) return fs.realpathSync(root);
98
+ }
99
+ try {
100
+ return path.dirname(require.resolve(name + '/package.json'));
101
+ } catch {
102
+ return findPackageRoot(require.resolve(name), name);
103
+ }
104
+ }
105
+
106
+ function findPackageRoot(filename: string, name: string): string {
107
+ let directory = path.dirname(filename);
108
+ while (true) {
109
+ const manifest = path.join(directory, 'package.json');
110
+ if (fs.existsSync(manifest) && JSON.parse(fs.readFileSync(manifest, 'utf8')).name === name) return directory;
111
+ const parent = path.dirname(directory);
112
+ if (parent === directory) throw new Error('Package root not found');
113
+ directory = parent;
114
+ }
115
+ }
@@ -1,3 +1,4 @@
1
+ import path from 'node:path';
1
2
  import { createCssCollector, extractCss } from '../extract';
2
3
  import { createTracer, transformDebug, transformExtract } from '../transform';
3
4
  import { getDebugSourceUrl } from '../transform/debug/utils/source_url';
@@ -18,6 +19,7 @@ import {
18
19
  } from '../utils/imports';
19
20
  import { createCompilerCache } from './cache';
20
21
  import { CompilerRuntimeMode } from './constants';
22
+ import { createPersistentTransformCache } from './persistent_cache';
21
23
  import type {
22
24
  CompilerInvalidateFileInfo,
23
25
  CompilerOptions,
@@ -43,6 +45,7 @@ export function createCompiler(args: CompilerArgs, options: CompilerOptions) {
43
45
 
44
46
  const tracer = createTracer(internal);
45
47
  const collector = createCssCollector();
48
+ const persistentCache = createPersistentTransformCache(internal);
46
49
 
47
50
  const compileDebug = (args: TransformDebugArgs): TransformDebugResult | null => {
48
51
  tracer.beginCompilation();
@@ -91,6 +94,18 @@ export function createCompiler(args: CompilerArgs, options: CompilerOptions) {
91
94
  };
92
95
 
93
96
  const compileExtract = (args: TransformExtractArgs): TransformExtractResult | null => {
97
+ const startIndex = collector.getItems().length;
98
+ try {
99
+ const cached = persistentCache.run(args, () => compileExtractUncached(args));
100
+ if (cached.hit && cached.result) collector.addMany(cached.result.rules);
101
+ return cached.result;
102
+ } catch (error) {
103
+ collector.getItems().splice(startIndex);
104
+ throw error;
105
+ }
106
+ };
107
+
108
+ const compileExtractUncached = (args: TransformExtractArgs): TransformExtractResult | null => {
94
109
  tracer.beginCompilation();
95
110
  const startIndex = collector.getItems().length;
96
111
 
@@ -129,11 +144,16 @@ export function createCompiler(args: CompilerArgs, options: CompilerOptions) {
129
144
  compileExtract,
130
145
  getExtractedCss,
131
146
  invalidateFile,
147
+ getPersistentCacheStats: persistentCache.getStats,
148
+ getTraceMetadataCacheStats: tracer.getMetadataCacheStats,
132
149
  };
133
150
  }
134
151
 
135
152
  function createCompilerInternal(args: CompilerArgs, options: CompilerOptions) {
136
- const { projectDir, cacheDir, runtimeMode } = args;
153
+ const { projectDir, runtimeMode } = args;
154
+ const cacheDir = options.cache?.location === undefined
155
+ ? args.cacheDir
156
+ : path.resolve(projectDir, options.cache.location);
137
157
 
138
158
  const cache = createCompilerCache({ cacheDir });
139
159
 
@@ -0,0 +1,310 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { types } from 'node:util';
5
+ import { deserialize, serialize } from 'node:v8';
6
+ import { CHECK_CONFIG } from '../../config/config/check';
7
+ import { CSS_CONFIG } from '../../config/config/css';
8
+ import { CSS_EXTRA_CONFIG } from '../../config/config/css_extra';
9
+ import { DEBUG_CONFIG } from '../../config/config/debug';
10
+ import { DEV_CONFIG, IS_DEV } from '../../config/config/dev';
11
+ import { RUNTIME_CONFIG } from '../../config/config/runtime';
12
+ import { PrioritySelectors } from '../../selector/presets';
13
+ import { getStyleFnMeta } from '../../style/style';
14
+ import { symbol } from '../../utils/symbol';
15
+ import { type CheckDiagnostic, observeCheckDiagnostics } from '../utils/check_diagnostics';
16
+ import { DEFAULT_CONFIG } from '../utils/constants';
17
+ import { clearResolverCache, observeFileResolutions, resolveFile } from '../utils/file_resolver';
18
+ import { getCompilerCacheIdentity } from './cache_identity';
19
+ import type { CompilerInternal } from './compiler';
20
+ import type { TransformExtractArgs, TransformExtractResult } from './types';
21
+
22
+ type Dependency = { source: string; fromFile: string; filePath: string | null; hash: string | null; };
23
+ type CachedError = { name: string; message: string; stack?: string; };
24
+ type RecordData = {
25
+ key: string;
26
+ dependencies: Dependency[];
27
+ result: TransformExtractResult | null;
28
+ diagnostics: CheckDiagnostic[];
29
+ error: CachedError | null;
30
+ };
31
+
32
+ export function createPersistentTransformCache(internal: CompilerInternal) {
33
+ const stats = { hits: 0, misses: 0, bypasses: 0, writes: 0 };
34
+ const directory = path.join(internal.cacheDir, 'extract-v1');
35
+ let previousContext: string | null = null;
36
+ const contextFor = (): string | null => {
37
+ if (internal.options.cache?.persistent === false || DEV_CONFIG.isDev) return null;
38
+ try {
39
+ const identity = getCompilerCacheIdentity();
40
+ if (!identity) return null;
41
+ const options = internal.options;
42
+ // Reject accessors/proxies before inspecting or normalizing configuration.
43
+ assertDataProperties(options);
44
+ if (Object.getPrototypeOf(options) !== Object.prototype && Object.getPrototypeOf(options) !== null) {
45
+ throw new Error('Non-plain compiler options');
46
+ }
47
+ if (options.importSources) assertPlainArray(options.importSources);
48
+ const importSources = options.importSources?.map((entry) => {
49
+ assertDataProperties(entry);
50
+ if (Object.getPrototypeOf(entry) !== Object.prototype && Object.getPrototypeOf(entry) !== null) {
51
+ throw new Error('Non-plain import source');
52
+ }
53
+ if (entry.styleFn && types.isProxy(entry.styleFn)) throw new Error('Proxy style function');
54
+ if (!entry.meta && entry.styleFn) {
55
+ const metadata = Object.getOwnPropertyDescriptor(entry.styleFn, symbol('style.fn:meta'));
56
+ if (!metadata || !('value' in metadata)) throw new Error('Dynamic style metadata');
57
+ }
58
+ return {
59
+ ...entry,
60
+ styleFn: undefined,
61
+ meta: entry.meta ?? (entry.styleFn ? getStyleFnMeta(entry.styleFn) : null),
62
+ };
63
+ });
64
+ return digest(encode({
65
+ schema: 1,
66
+ identity,
67
+ cwd: process.cwd(),
68
+ projectDir: internal.projectDir,
69
+ runtimeMode: internal.runtimeMode,
70
+ options: { ...options, importSources },
71
+ globals: {
72
+ CSS_CONFIG,
73
+ CSS_EXTRA_CONFIG,
74
+ DEBUG_CONFIG,
75
+ DEV_CONFIG,
76
+ IS_DEV,
77
+ RUNTIME_CONFIG,
78
+ CHECK_CONFIG,
79
+ DEFAULT_CONFIG,
80
+ PrioritySelectors,
81
+ },
82
+ }, options.cache?.dynamicConfig !== false));
83
+ } catch {
84
+ return null;
85
+ }
86
+ };
87
+ const run = (args: TransformExtractArgs, compile: () => TransformExtractResult | null) => {
88
+ const context = contextFor();
89
+ let key: string | null = null;
90
+ try {
91
+ if (context) key = digest(encode({ context, args }));
92
+ } catch { /* Unsupported input. */ }
93
+ if (!key) {
94
+ stats.bypasses++;
95
+ previousContext = null;
96
+ internal.cache.clear();
97
+ clearResolverCache();
98
+ return { result: compile(), hit: false };
99
+ }
100
+ // Different Node/compiler versions may build the same project concurrently.
101
+ // Keep their records separate instead of repeatedly displacing each other.
102
+ const filename = path.join(
103
+ directory,
104
+ getCompilerCacheIdentity()!,
105
+ digest(encode(internal.options.cache?.version)),
106
+ digest(args.filePath) + '.bin',
107
+ );
108
+ // A new snapshot for each compilation: never trust resolver or mtime caches across calls.
109
+ clearResolverCache();
110
+ let hit: RecordData | undefined;
111
+ try {
112
+ const buffer = fs.readFileSync(filename);
113
+ const body = buffer.subarray(65);
114
+ if (buffer.subarray(0, 64).toString() === digest(body)) {
115
+ const record = deserialize(body) as RecordData;
116
+ if (
117
+ record.key === key && Array.isArray(record.dependencies) && validRecord(record) &&
118
+ record.dependencies.every(isFresh)
119
+ ) {
120
+ hit = record;
121
+ }
122
+ }
123
+ } catch {
124
+ // Missing, truncated, incompatible, or otherwise unreadable cache: compile normally.
125
+ }
126
+ // Replay outside the read/recovery catch: cached errors must still fail builds.
127
+ if (hit) {
128
+ stats.hits++;
129
+ for (const diagnostic of hit.diagnostics) {
130
+ if (diagnostic.level === 'warn') console.warn('[fluentic-style] ' + diagnostic.message);
131
+ }
132
+ if (hit.error) {
133
+ const error = new Error(hit.error.message);
134
+ error.name = hit.error.name;
135
+ error.stack = hit.error.stack;
136
+ throw error;
137
+ }
138
+ return { result: hit.result, hit: true };
139
+ }
140
+ stats.misses++;
141
+ clearResolverCache();
142
+ // Tracer hits revalidate/replay their lookup graph into the active observer.
143
+ // Evaluated bindings are reusable only under the same compiler configuration.
144
+ if (context !== previousContext) internal.cache.clear();
145
+ previousContext = context;
146
+ const dependencies = new Map<string, Dependency>();
147
+ const diagnostics: CheckDiagnostic[] = [];
148
+ let result: TransformExtractResult | null = null;
149
+ let failure: Error | null = null;
150
+ try {
151
+ result = observeCheckDiagnostics(
152
+ (diagnostic) => diagnostics.push(diagnostic),
153
+ () =>
154
+ observeFileResolutions((source, fromFile, resolved) => {
155
+ dependencies.set(JSON.stringify([source, fromFile]), {
156
+ source,
157
+ fromFile,
158
+ filePath: resolved?.filePath ?? null,
159
+ hash: resolved ? digest(resolved.content) : null,
160
+ });
161
+ }, compile),
162
+ );
163
+ } catch (error) {
164
+ // Cache deliberate check failures only, not arbitrary compiler/I/O errors.
165
+ if (!(error instanceof Error) || diagnostics[diagnostics.length - 1]?.level !== 'error') throw error;
166
+ failure = error;
167
+ }
168
+ const cachedError = failure ? { name: failure.name, message: failure.message, stack: failure.stack } : null;
169
+ if (result || failure) {
170
+ let temporary: string | undefined;
171
+ try {
172
+ encode(result); // Only persist plain data; never evaluator functions/symbols.
173
+ const records = [...dependencies.values()];
174
+ clearResolverCache();
175
+ // Do not save a mixed snapshot if inputs/configuration changed during extraction.
176
+ if (!records.every(isFresh) || contextFor() !== context) throw new Error('Cache snapshot changed');
177
+ const body = serialize(
178
+ { key, dependencies: records, result, diagnostics, error: cachedError } satisfies RecordData,
179
+ );
180
+ fs.mkdirSync(path.dirname(filename), { recursive: true });
181
+ temporary = filename + '.' + randomUUID() + '.tmp';
182
+ fs.writeFileSync(temporary, Buffer.concat([Buffer.from(digest(body) + '\n'), body]));
183
+ fs.renameSync(temporary, filename);
184
+ stats.writes++;
185
+ } catch {
186
+ // Caching is optional; permission/disk/serialization failures cannot fail a build.
187
+ } finally {
188
+ if (temporary) {
189
+ try {
190
+ fs.unlinkSync(temporary);
191
+ } catch { /* Already renamed or unavailable. */ }
192
+ }
193
+ }
194
+ }
195
+ if (failure) throw failure;
196
+ return { result, hit: false };
197
+ };
198
+ return { run, getStats: () => ({ ...stats }) };
199
+ }
200
+
201
+ function isFresh(dependency: Dependency): boolean {
202
+ if (typeof dependency.source !== 'string' || typeof dependency.fromFile !== 'string') return false;
203
+ const resolved = resolveFile(dependency.source, dependency.fromFile);
204
+ return (resolved?.filePath ?? null) === dependency.filePath &&
205
+ (resolved ? digest(resolved.content) : null) === dependency.hash;
206
+ }
207
+
208
+ function validRecord(record: RecordData): boolean {
209
+ if (
210
+ !Array.isArray(record.diagnostics) ||
211
+ !record.diagnostics.every((item) =>
212
+ item && (item.level === 'warn' || item.level === 'error') && typeof item.message === 'string'
213
+ )
214
+ ) return false;
215
+ if (record.error) {
216
+ return record.result === null && record.diagnostics[record.diagnostics.length - 1]?.level === 'error' &&
217
+ typeof record.error.name === 'string' && typeof record.error.message === 'string' &&
218
+ (record.error.stack === undefined || typeof record.error.stack === 'string');
219
+ }
220
+ return record.error === null && record.diagnostics.every((item) => item.level === 'warn') &&
221
+ validResult(record.result);
222
+ }
223
+
224
+ function validResult(result: TransformExtractResult | null): boolean {
225
+ return !!result && typeof result.code === 'string' &&
226
+ (result.sourcemap === null || typeof result.sourcemap === 'string') && Array.isArray(result.rules) &&
227
+ result.rules.every((rule) =>
228
+ typeof rule.css === 'string' && typeof rule.dedupe === 'string' &&
229
+ typeof rule.className === 'string' && Array.isArray(rule.priority)
230
+ );
231
+ }
232
+
233
+ function digest(value: string | Buffer): string {
234
+ return createHash('sha256').update(value).digest('hex');
235
+ }
236
+
237
+ function assertDataProperties(value: object) {
238
+ if (types.isProxy(value)) throw new Error('Proxy configuration');
239
+ for (const key of Reflect.ownKeys(value)) {
240
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
241
+ if (
242
+ typeof key === 'symbol' || !('value' in descriptor) ||
243
+ (!descriptor.enumerable && !(Array.isArray(value) && key === 'length') &&
244
+ !(value instanceof RegExp && key === 'lastIndex'))
245
+ ) {
246
+ throw new Error('Dynamic configuration');
247
+ }
248
+ }
249
+ }
250
+
251
+ function assertPlainArray(value: unknown[]) {
252
+ assertDataProperties(value);
253
+ if (
254
+ Object.getPrototypeOf(value) !== Array.prototype ||
255
+ Object.keys(value).some((key) => !/^(0|[1-9][0-9]*)$/.test(key))
256
+ ) {
257
+ throw new Error('Non-plain array');
258
+ }
259
+ }
260
+
261
+ /** Tagged, order-preserving encoding: property order can affect generated CSS. */
262
+ function encode(value: unknown, dynamicConfig = false): string {
263
+ return JSON.stringify(encodeValue(value, new Set(), dynamicConfig));
264
+ }
265
+
266
+ function encodeValue(value: unknown, seen = new Set<object>(), dynamicConfig = false): unknown {
267
+ if (typeof value === 'function' && dynamicConfig) {
268
+ if (types.isProxy(value)) throw new Error('Proxy callback');
269
+ for (const key of Reflect.ownKeys(value)) {
270
+ if (typeof key !== 'string' || !['length', 'name', 'prototype', 'arguments', 'caller'].includes(key)) {
271
+ throw new Error('Callback with custom properties');
272
+ }
273
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
274
+ if (!('value' in descriptor)) throw new Error('Callback accessor');
275
+ }
276
+ const source = Function.prototype.toString.call(value);
277
+ if (source.includes('[native code]')) throw new Error('Opaque callback');
278
+ return ['function', source];
279
+ }
280
+ if (value === undefined) return ['undefined'];
281
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
282
+ if (typeof value === 'number' && Number.isFinite(value)) {
283
+ return ['number', Object.is(value, -0) ? '-0' : value];
284
+ }
285
+ if (typeof value !== 'object' || value === null || seen.has(value)) throw new Error('Unsupported cache input');
286
+ assertDataProperties(value);
287
+ if (value instanceof RegExp) {
288
+ if (
289
+ value.global || value.sticky || Object.getPrototypeOf(value) !== RegExp.prototype || Object.keys(value).length
290
+ ) {
291
+ throw new Error('Dynamic pattern');
292
+ }
293
+ return ['regexp', value.source, value.flags];
294
+ }
295
+ if (Array.isArray(value)) assertPlainArray(value);
296
+ if (
297
+ !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null
298
+ ) {
299
+ throw new Error('Non-plain cache input');
300
+ }
301
+ seen.add(value);
302
+ try {
303
+ return [
304
+ Array.isArray(value) ? ['array', value.length] : 'object',
305
+ Object.keys(value).map((key) => [key, encodeValue((value as Record<string, unknown>)[key], seen, dynamicConfig)]),
306
+ ];
307
+ } finally {
308
+ seen.delete(value);
309
+ }
310
+ }
@@ -19,7 +19,19 @@ export type CompilerDevOptions = ReplaceProps<DevRuntimeOptions, {
19
19
 
20
20
  export type DevSourcemapMode = 'sourceUrl' | 'sourceContent' | 'sidecarServer';
21
21
 
22
+ export type CompilerCacheOptions = {
23
+ /** Persist transform results and tracer syntax. Defaults to true. */
24
+ persistent?: boolean;
25
+ /** Cache callbacks by source. Defaults to true; bump version when captured/external inputs change. */
26
+ dynamicConfig?: boolean;
27
+ /** Manual invalidation namespace for external inputs. */
28
+ version?: string | number;
29
+ /** Cache directory; relative paths resolve from the project root. */
30
+ location?: string;
31
+ };
32
+
22
33
  export type CompilerOptions = {
34
+ cache?: CompilerCacheOptions;
23
35
  hoist?: boolean;
24
36
  check?: StyleCheckOptions;
25
37
  css?: CompilerCssOptions;
@@ -10,8 +10,8 @@ export function createCssCollector() {
10
10
  items.push(item);
11
11
  },
12
12
 
13
- addMany(items: CssExtractRule[]) {
14
- items.push(...items);
13
+ addMany(rules: CssExtractRule[]) {
14
+ items.push(...rules);
15
15
  },
16
16
 
17
17
  getItems() {
@@ -0,0 +1,124 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import type { CompilerInternal } from '../../compiler';
5
+ import { getCompilerCacheIdentity } from '../../compiler/cache_identity';
6
+ import { BabelCore, babelTransformOptions } from '../utils/babel';
7
+ import type { BabelTypes } from '../utils/babel';
8
+
9
+ const defaultParser = BabelCore.parseSync;
10
+ const MAX_MEMORY_BYTES = 32 * 1024 * 1024;
11
+ type MemoryEntry = { contentHash: string; json: string; };
12
+ type DiskEntry = { version: 1; filePath: string; contentHash: string; checksum: string; ast: BabelTypes.File; };
13
+
14
+ /** Immutable syntax only. Every consumer gets fresh nodes before annotations/evaluation. */
15
+ export function createTraceMetadataCache(internal: CompilerInternal) {
16
+ const memory = new Map<string, MemoryEntry>();
17
+ let memoryBytes = 0;
18
+ let memoryVersion = internal.options.cache?.version;
19
+ const stats = { parses: 0, memoryHits: 0, diskHits: 0, writes: 0 };
20
+ const remember = (filePath: string, contentHash: string, json: string) => {
21
+ const previous = memory.get(filePath);
22
+ if (previous) memoryBytes -= previous.json.length * 2;
23
+ memory.delete(filePath);
24
+ if (json.length * 2 > MAX_MEMORY_BYTES) return;
25
+ while (memoryBytes + json.length * 2 > MAX_MEMORY_BYTES) {
26
+ const oldest = memory.keys().next().value!;
27
+ memoryBytes -= memory.get(oldest)!.json.length * 2;
28
+ memory.delete(oldest);
29
+ }
30
+ memory.set(filePath, { contentHash, json });
31
+ memoryBytes += json.length * 2;
32
+ };
33
+ const parse = (babel: typeof BabelCore, filePath: string, content: string): BabelTypes.File | null => {
34
+ if (!Object.is(memoryVersion, internal.options.cache?.version)) {
35
+ memory.clear();
36
+ memoryBytes = 0;
37
+ memoryVersion = internal.options.cache?.version;
38
+ }
39
+ const supportedParser = babel.parseSync === defaultParser;
40
+ const contentHash = hash(content);
41
+ const cached = supportedParser ? memory.get(filePath) : undefined;
42
+ if (cached?.contentHash === contentHash) {
43
+ stats.memoryHits++;
44
+ memory.delete(filePath);
45
+ memory.set(filePath, cached);
46
+ return JSON.parse(cached.json) as BabelTypes.File;
47
+ }
48
+ const identity = supportedParser && internal.options.cache?.persistent !== false
49
+ ? getCompilerCacheIdentity()
50
+ : null;
51
+ const filename = identity
52
+ ? path.join(
53
+ internal.cacheDir,
54
+ 'trace-metadata-v1',
55
+ identity,
56
+ hash(JSON.stringify(internal.options.cache?.version ?? null)),
57
+ hash(filePath) + '.json',
58
+ )
59
+ : null;
60
+ if (filename) {
61
+ try {
62
+ const record = JSON.parse(fs.readFileSync(filename, 'utf8')) as DiskEntry;
63
+ if (
64
+ record.version === 1 && record.filePath === filePath && record.contentHash === contentHash &&
65
+ record.ast?.type === 'File' && record.ast.program?.type === 'Program' &&
66
+ Array.isArray(record.ast.program.body)
67
+ ) {
68
+ const json = JSON.stringify(record.ast);
69
+ if (record.checksum === hash(json)) {
70
+ remember(filePath, contentHash, json);
71
+ stats.diskHits++;
72
+ return record.ast;
73
+ }
74
+ }
75
+ } catch {
76
+ // Unreadable/corrupt metadata is a cache miss, never a compiler error.
77
+ }
78
+ }
79
+ let ast: BabelTypes.File | null;
80
+ try {
81
+ stats.parses++;
82
+ ast = babel.parseSync(content, { ...babelTransformOptions(), filename: filePath }) as BabelTypes.File | null;
83
+ } catch {
84
+ return null;
85
+ }
86
+ if (!ast || !supportedParser) return ast;
87
+ let temporary: string | undefined;
88
+ try {
89
+ // JSON cannot preserve non-finite literal values or runtime objects.
90
+ const json = JSON.stringify(ast, (_key, value: unknown) => {
91
+ if (
92
+ typeof value === 'number' && (!Number.isFinite(value) || Object.is(value, -0)) ||
93
+ typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol'
94
+ ) {
95
+ throw new Error('Non-JSON syntax data');
96
+ }
97
+ return value;
98
+ });
99
+ remember(filePath, contentHash, json);
100
+ if (filename) {
101
+ const record: DiskEntry = { version: 1, filePath, contentHash, checksum: hash(json), ast };
102
+ fs.mkdirSync(path.dirname(filename), { recursive: true });
103
+ temporary = filename + '.' + randomUUID() + '.tmp';
104
+ fs.writeFileSync(temporary, JSON.stringify(record), 'utf8');
105
+ fs.renameSync(temporary, filename);
106
+ stats.writes++;
107
+ }
108
+ } catch {
109
+ // Metadata reuse is optional. Parsing/evaluation still proceeds normally.
110
+ } finally {
111
+ if (temporary) {
112
+ try {
113
+ fs.unlinkSync(temporary);
114
+ } catch { /* Already renamed or unavailable. */ }
115
+ }
116
+ }
117
+ return ast;
118
+ };
119
+ return { parse, getStats: () => ({ ...stats }) };
120
+ }
121
+
122
+ function hash(content: string): string {
123
+ return createHash('sha256').update(content).digest('hex');
124
+ }