@ngrs/vite 0.2.0 → 0.2.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.
Files changed (2) hide show
  1. package/package.json +2 -2
  2. package/src/index.mjs +264 -26
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngrs/vite",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Native Rust Angular compiler & Ivy linker plugins for Vite, powered by @ngrs/compiler",
5
5
  "type": "module",
6
6
  "main": "./src/index.cjs",
@@ -23,7 +23,7 @@
23
23
  "src"
24
24
  ],
25
25
  "dependencies": {
26
- "@ngrs/compiler": "0.2.0"
26
+ "@ngrs/compiler": "0.2.1"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "happy-dom": ">=15.0.0 || ^20.0.0",
package/src/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
+ import crypto from 'node:crypto';
1
2
  import fs from 'node:fs';
2
- import { readFile } from 'node:fs/promises';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
4
  import { createRequire } from 'node:module';
4
5
  import path from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
@@ -14,8 +15,12 @@ const {
14
15
  linkFile,
15
16
  linkFileAsync,
16
17
  compileSassWithDeps,
18
+ version: getCompilerVersion,
17
19
  } = napi;
18
20
 
21
+ const COMPILER_CACHE_VERSION =
22
+ typeof getCompilerVersion === 'function' ? getCompilerVersion() : '0.2.0';
23
+
19
24
  const linkFileAsyncFn =
20
25
  typeof linkFileAsync === 'function'
21
26
  ? linkFileAsync
@@ -199,6 +204,86 @@ function resolveViaTsconfigPaths(source, mappings) {
199
204
  return null;
200
205
  }
201
206
 
207
+ function loadEmittedModuleFromCompiler(compilerInstance, cleanId, wantSourceMap) {
208
+ if (typeof compilerInstance.getEmittedModule === 'function') {
209
+ const mod = compilerInstance.getEmittedModule(cleanId);
210
+ if (!mod) {
211
+ return null;
212
+ }
213
+ if (!wantSourceMap || !mod.map) {
214
+ return { code: mod.code, map: null };
215
+ }
216
+ try {
217
+ return { code: mod.code, map: JSON.parse(mod.map) };
218
+ } catch {
219
+ return { code: mod.code, map: null };
220
+ }
221
+ }
222
+ const emittedJs = compilerInstance.getEmittedJs(cleanId);
223
+ if (emittedJs === null || emittedJs === undefined) {
224
+ return null;
225
+ }
226
+ return wantSourceMap ? extractInlineSourceMap(emittedJs) : { code: emittedJs, map: null };
227
+ }
228
+
229
+ /** @type {Map<string, { code: string, sourceMap: string | null }>} */
230
+ const linkerMemoryCache = new Map();
231
+
232
+ function computeLinkerCacheKey(source, { sourceMapping, linkerJitMode, unknownDeclarationVersionHandling, optimizeForBundling }) {
233
+ return crypto
234
+ .createHash('md5')
235
+ .update(
236
+ `${COMPILER_CACHE_VERSION}|${sourceMapping ? 1 : 0}|${linkerJitMode ? 1 : 0}|${unknownDeclarationVersionHandling || 'error'}|${optimizeForBundling ? 1 : 0}|`,
237
+ )
238
+ .update(source)
239
+ .digest('hex');
240
+ }
241
+
242
+ async function readLinkerCache(cacheDir, cacheDirExistsOnDisk, key, sourceMapping) {
243
+ const mem = linkerMemoryCache.get(key);
244
+ if (mem) {
245
+ return mem;
246
+ }
247
+ if (!cacheDir || !cacheDirExistsOnDisk) {
248
+ return null;
249
+ }
250
+ try {
251
+ if (!sourceMapping) {
252
+ const code = await readFile(path.join(cacheDir, `${key}.js`), 'utf8');
253
+ const entry = { code, sourceMap: null };
254
+ linkerMemoryCache.set(key, entry);
255
+ return entry;
256
+ }
257
+ const raw = await readFile(path.join(cacheDir, `${key}.json`), 'utf8');
258
+ const parsed = JSON.parse(raw);
259
+ if (parsed && typeof parsed.code === 'string') {
260
+ linkerMemoryCache.set(key, parsed);
261
+ return parsed;
262
+ }
263
+ } catch {
264
+ // Cache miss
265
+ }
266
+ return null;
267
+ }
268
+
269
+ async function flushLinkerCacheWrites(cacheDir, pendingWrites) {
270
+ if (!cacheDir || pendingWrites.length === 0) {
271
+ return;
272
+ }
273
+ try {
274
+ await mkdir(cacheDir, { recursive: true });
275
+ await Promise.all(
276
+ pendingWrites.map(({ key, entry, sourceMapping }) =>
277
+ sourceMapping
278
+ ? writeFile(path.join(cacheDir, `${key}.json`), JSON.stringify(entry), 'utf8')
279
+ : writeFile(path.join(cacheDir, `${key}.js`), entry.code, 'utf8'),
280
+ ),
281
+ );
282
+ } catch {
283
+ // Ignore disk cache write errors on read-only filesystems
284
+ }
285
+ }
286
+
202
287
  function extractInlineSourceMap(jsCode) {
203
288
  const match = INLINE_SOURCEMAP_RE.exec(jsCode);
204
289
  if (!match) {
@@ -458,6 +543,27 @@ export function angularCompilerPlugin(options = {}) {
458
543
  let includePaths = [];
459
544
  let normalizedReplacements = [];
460
545
  let tsconfigPathMappings = [];
546
+ /** @type {Set<string>} */
547
+ let tsconfigExactPatterns = new Set();
548
+ /** @type {string[]} */
549
+ let tsconfigWildcardPrefixes = [];
550
+ /** @type {Map<string, string | null>} */
551
+ const tsconfigResolveCache = new Map();
552
+
553
+ function refreshTsconfigMappings(cfgPath) {
554
+ tsconfigPathMappings = loadTsconfigPathMappings(cfgPath);
555
+ tsconfigResolveCache.clear();
556
+ tsconfigExactPatterns = new Set();
557
+ const prefixes = new Set();
558
+ for (const m of tsconfigPathMappings) {
559
+ if (m.hasWildcard) {
560
+ prefixes.add(m.prefix);
561
+ } else {
562
+ tsconfigExactPatterns.add(m.pattern);
563
+ }
564
+ }
565
+ tsconfigWildcardPrefixes = [...prefixes];
566
+ }
461
567
 
462
568
  /** @type {Map<string, Set<string>>} partialPath -> Set<componentScssPath> */
463
569
  const partialToComponentStyles = new Map();
@@ -857,7 +963,7 @@ export function angularCompilerPlugin(options = {}) {
857
963
  options.test || process.env.VITEST || config.mode === 'test' || config.test,
858
964
  );
859
965
  tsconfigPath = resolveDefaultTsconfig(workspaceRoot, options.tsconfig, isTestMode);
860
- tsconfigPathMappings = loadTsconfigPathMappings(tsconfigPath);
966
+ refreshTsconfigMappings(tsconfigPath);
861
967
  includePaths = resolveIncludePaths(workspaceRoot);
862
968
  normalizedReplacements = resolveFileReplacements(workspaceRoot);
863
969
  enableHmr = isTestMode
@@ -940,6 +1046,14 @@ export function angularCompilerPlugin(options = {}) {
940
1046
  (options.deferTypecheck ?? true) &&
941
1047
  typeof NapiProjectCompiler.prototype.finishDeferredTypecheckAsync === 'function';
942
1048
 
1049
+ const hasCustomJsSass = Boolean(
1050
+ options.stylePreprocessorOptions?.sass?.functions !== undefined ||
1051
+ options.stylePreprocessorOptions?.sass?.importers !== undefined,
1052
+ );
1053
+ const canUseNativeExternalSass =
1054
+ !hasCustomJsSass &&
1055
+ typeof NapiProjectCompiler.prototype.getUncompiledExternalSassFiles === 'function';
1056
+
943
1057
  compiler = NapiProjectCompiler.open(tsconfigPath, {
944
1058
  fileReplacements: normalizedReplacements,
945
1059
  hmr: enableHmr,
@@ -949,17 +1063,18 @@ export function angularCompilerPlugin(options = {}) {
949
1063
  deferTypecheck: useDeferredTypecheck,
950
1064
  inlineStyleLanguage: options.inlineStyleLanguage,
951
1065
  styleIncludePaths: includePaths,
1066
+ disableNativeExternalSass: hasCustomJsSass,
952
1067
  ...(isTestMode
953
1068
  ? {
954
1069
  supportTestBed: options.supportTestBed ?? true,
955
1070
  supportJitMode: options.supportJitMode ?? true,
956
1071
  }
957
1072
  : isProdOptimized
958
- ? {
959
- supportTestBed: options.supportTestBed ?? false,
960
- supportJitMode: options.supportJitMode ?? Boolean(options.jit),
961
- }
962
- : {}),
1073
+ ? {
1074
+ supportTestBed: options.supportTestBed ?? false,
1075
+ supportJitMode: options.supportJitMode ?? Boolean(options.jit),
1076
+ }
1077
+ : {}),
963
1078
  });
964
1079
 
965
1080
  const allResources = compiler.getAllResources();
@@ -968,10 +1083,50 @@ export function angularCompilerPlugin(options = {}) {
968
1083
  recordSnapshot(res);
969
1084
  }
970
1085
  }
971
- const sassOverrides = await preprocessComponentStyles(allResources);
972
- if (sassOverrides.length > 0) {
973
- compiler.setResourceOverrides(sassOverrides);
974
- compiler.rebuild(sassOverrides.map((o) => o.path));
1086
+
1087
+ if (canUseNativeExternalSass) {
1088
+ for (const rawRes of allResources) {
1089
+ if (!SASS_FILE_RE.test(rawRes)) continue;
1090
+ const absRes = path.resolve(workspaceRoot, rawRes);
1091
+ const normStylePath = toPosixPath(absRes);
1092
+ const compiledCss = compiler.getCompiledStyleCss(absRes);
1093
+ if (compiledCss !== null && compiledCss !== undefined) {
1094
+ compiledComponentStyleCss.set(normStylePath, compiledCss);
1095
+ }
1096
+ const partials = compiler.getSassPartialsForStyle(absRes) || [];
1097
+ const nextPartials = new Set();
1098
+ for (const loaded of partials) {
1099
+ const normLoaded = toPosixPath(loaded);
1100
+ if (normLoaded !== normStylePath) {
1101
+ nextPartials.add(normLoaded);
1102
+ if (!oneShot) {
1103
+ recordSnapshot(normLoaded);
1104
+ }
1105
+ let dependents = partialToComponentStyles.get(normLoaded);
1106
+ if (!dependents) {
1107
+ dependents = new Set();
1108
+ partialToComponentStyles.set(normLoaded, dependents);
1109
+ }
1110
+ dependents.add(normStylePath);
1111
+ }
1112
+ }
1113
+ componentStyleToPartials.set(normStylePath, nextPartials);
1114
+ }
1115
+
1116
+ const fallbackScss = compiler.getUncompiledExternalSassFiles();
1117
+ if (fallbackScss.length > 0) {
1118
+ const sassOverrides = await preprocessComponentStyles(fallbackScss);
1119
+ if (sassOverrides.length > 0) {
1120
+ compiler.setResourceOverrides(sassOverrides);
1121
+ compiler.rebuild(sassOverrides.map((o) => o.path));
1122
+ }
1123
+ }
1124
+ } else {
1125
+ const sassOverrides = await preprocessComponentStyles(allResources);
1126
+ if (sassOverrides.length > 0) {
1127
+ compiler.setResourceOverrides(sassOverrides);
1128
+ compiler.rebuild(sassOverrides.map((o) => o.path));
1129
+ }
975
1130
  }
976
1131
 
977
1132
  collectComponentStylesForBudgets();
@@ -1009,7 +1164,25 @@ export function angularCompilerPlugin(options = {}) {
1009
1164
  ) {
1010
1165
  return null;
1011
1166
  }
1012
- return resolveViaTsconfigPaths(source, tsconfigPathMappings);
1167
+ if (tsconfigResolveCache.has(source)) {
1168
+ return tsconfigResolveCache.get(source);
1169
+ }
1170
+ let mayMatch = tsconfigExactPatterns.has(source);
1171
+ if (!mayMatch) {
1172
+ for (let i = 0; i < tsconfigWildcardPrefixes.length; i++) {
1173
+ if (source.startsWith(tsconfigWildcardPrefixes[i])) {
1174
+ mayMatch = true;
1175
+ break;
1176
+ }
1177
+ }
1178
+ }
1179
+ if (!mayMatch) {
1180
+ tsconfigResolveCache.set(source, null);
1181
+ return null;
1182
+ }
1183
+ const resolved = resolveViaTsconfigPaths(source, tsconfigPathMappings);
1184
+ tsconfigResolveCache.set(source, resolved);
1185
+ return resolved;
1013
1186
  },
1014
1187
 
1015
1188
  load: {
@@ -1036,14 +1209,11 @@ export function angularCompilerPlugin(options = {}) {
1036
1209
  ) {
1037
1210
  return null;
1038
1211
  }
1039
- const emittedJs = compiler.getEmittedJs(cleanId);
1040
- if (emittedJs === null || emittedJs === undefined) {
1212
+ const out = loadEmittedModuleFromCompiler(compiler, cleanId, enableSourceMap);
1213
+ if (!out) {
1041
1214
  return null;
1042
1215
  }
1043
1216
  servedViaLoad.add(cleanId);
1044
- const out = enableSourceMap
1045
- ? extractInlineSourceMap(emittedJs)
1046
- : { code: emittedJs, map: null };
1047
1217
  return isRolldownVite ? { ...out, moduleType: 'js' } : out;
1048
1218
  },
1049
1219
  },
@@ -1080,8 +1250,8 @@ export function angularCompilerPlugin(options = {}) {
1080
1250
  await syncOnDiskChangesForTs(cleanId, null);
1081
1251
  }
1082
1252
 
1083
- const emittedJs = compiler.getEmittedJs(cleanId);
1084
- if (emittedJs === null || emittedJs === undefined) {
1253
+ const modOut = loadEmittedModuleFromCompiler(compiler, cleanId, enableSourceMap);
1254
+ if (!modOut) {
1085
1255
  return null;
1086
1256
  }
1087
1257
 
@@ -1102,10 +1272,7 @@ export function angularCompilerPlugin(options = {}) {
1102
1272
  }
1103
1273
  }
1104
1274
 
1105
- if (enableSourceMap) {
1106
- return extractInlineSourceMap(emittedJs);
1107
- }
1108
- return { code: emittedJs, map: null };
1275
+ return modOut;
1109
1276
  },
1110
1277
  },
1111
1278
 
@@ -1137,7 +1304,16 @@ export function angularCompilerPlugin(options = {}) {
1137
1304
  if (directOwners.length > 0) {
1138
1305
  affectedStylePaths.add(normFile);
1139
1306
  }
1140
- const dependentStyles = partialToComponentStyles.get(normFile);
1307
+ let dependentStyles = partialToComponentStyles.get(normFile);
1308
+ if (!dependentStyles) {
1309
+ try {
1310
+ dependentStyles = partialToComponentStyles.get(
1311
+ toPosixPath(fs.realpathSync(cleanFile)),
1312
+ );
1313
+ } catch {
1314
+ // Ignore missing realpath
1315
+ }
1316
+ }
1141
1317
  if (dependentStyles) {
1142
1318
  for (const depStyle of dependentStyles) {
1143
1319
  affectedStylePaths.add(depStyle);
@@ -1245,6 +1421,9 @@ export function angularCompilerPlugin(options = {}) {
1245
1421
  }
1246
1422
 
1247
1423
  // 2. Handle .ts / fileReplacements / tsconfig.json changes
1424
+ if (isTsconfigChange) {
1425
+ refreshTsconfigMappings(tsconfigPath);
1426
+ }
1248
1427
  const tsRebuildStart = performance.now();
1249
1428
  compiler.rebuild([cleanFile]);
1250
1429
  recordSnapshot(cleanFile);
@@ -1312,6 +1491,10 @@ export function angularCompilerPlugin(options = {}) {
1312
1491
  export function angularLinkerPlugin(options = {}) {
1313
1492
  let resolvedConfig;
1314
1493
  let sourceMapping = true;
1494
+ let linkerCacheDir = '';
1495
+ let linkerCacheDirExists = false;
1496
+ /** @type {Array<{ key: string, entry: { code: string, sourceMap: string | null }, sourceMapping: boolean }>} */
1497
+ let pendingLinkerCacheWrites = [];
1315
1498
  const linkerJitMode = options.jit ?? false;
1316
1499
  const unknownDeclarationVersionHandling =
1317
1500
  options.unknownDeclarationVersionHandling ?? 'error';
@@ -1367,6 +1550,16 @@ export function angularLinkerPlugin(options = {}) {
1367
1550
  sourceMapping =
1368
1551
  options.sourceMap ??
1369
1552
  (config.command === 'serve' ? true : Boolean(config.build?.sourcemap));
1553
+ const rootDir = path.resolve(options.workspaceRoot || config.root || process.cwd());
1554
+ linkerCacheDir =
1555
+ options.linkerCache === false
1556
+ ? ''
1557
+ : path.join(rootDir, '.angular', 'cache', 'ngrs-linker');
1558
+ linkerCacheDirExists = Boolean(linkerCacheDir && fs.existsSync(linkerCacheDir));
1559
+ },
1560
+
1561
+ buildStart() {
1562
+ linkerCacheDirExists = Boolean(linkerCacheDir && fs.existsSync(linkerCacheDir));
1370
1563
  },
1371
1564
 
1372
1565
  transform: {
@@ -1404,12 +1597,34 @@ export function angularLinkerPlugin(options = {}) {
1404
1597
  return null;
1405
1598
  }
1406
1599
 
1407
- const result = await linkFileAsyncFn(cleanId, code, {
1600
+ const linkOpts = {
1408
1601
  sourceMapping,
1409
1602
  linkerJitMode,
1410
1603
  unknownDeclarationVersionHandling,
1411
1604
  optimizeForBundling,
1412
- });
1605
+ };
1606
+ const cacheKey = isNodeModules ? computeLinkerCacheKey(code, linkOpts) : '';
1607
+ if (cacheKey) {
1608
+ const cached = await readLinkerCache(
1609
+ linkerCacheDir,
1610
+ linkerCacheDirExists,
1611
+ cacheKey,
1612
+ sourceMapping,
1613
+ );
1614
+ if (cached) {
1615
+ let map = null;
1616
+ if (sourceMapping && cached.sourceMap) {
1617
+ try {
1618
+ map = JSON.parse(cached.sourceMap);
1619
+ } catch {
1620
+ map = null;
1621
+ }
1622
+ }
1623
+ return { code: cached.code, map };
1624
+ }
1625
+ }
1626
+
1627
+ const result = await linkFileAsyncFn(cleanId, code, linkOpts);
1413
1628
 
1414
1629
  if (result.diagnostics?.length) {
1415
1630
  const { warnings, errors } = formatDiagnostics(
@@ -1434,6 +1649,21 @@ export function angularLinkerPlugin(options = {}) {
1434
1649
  return null;
1435
1650
  }
1436
1651
 
1652
+ if (cacheKey && (!result.diagnostics || result.diagnostics.length === 0)) {
1653
+ const entry = {
1654
+ code: result.code,
1655
+ sourceMap: sourceMapping ? (result.sourceMap ?? null) : null,
1656
+ };
1657
+ linkerMemoryCache.set(cacheKey, entry);
1658
+ if (linkerCacheDir) {
1659
+ if (resolvedConfig?.command === 'build') {
1660
+ pendingLinkerCacheWrites.push({ key: cacheKey, entry, sourceMapping });
1661
+ } else {
1662
+ flushLinkerCacheWrites(linkerCacheDir, [{ key: cacheKey, entry, sourceMapping }]);
1663
+ }
1664
+ }
1665
+ }
1666
+
1437
1667
  let map = null;
1438
1668
  if (sourceMapping && result.sourceMap) {
1439
1669
  try {
@@ -1449,6 +1679,14 @@ export function angularLinkerPlugin(options = {}) {
1449
1679
  };
1450
1680
  },
1451
1681
  },
1682
+
1683
+ async closeBundle() {
1684
+ if (pendingLinkerCacheWrites.length > 0) {
1685
+ const batch = pendingLinkerCacheWrites;
1686
+ pendingLinkerCacheWrites = [];
1687
+ await flushLinkerCacheWrites(linkerCacheDir, batch);
1688
+ }
1689
+ },
1452
1690
  };
1453
1691
  }
1454
1692