@ngrs/vite 0.2.1 → 0.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngrs/vite",
3
- "version": "0.2.1",
3
+ "version": "0.3.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.1"
26
+ "@ngrs/compiler": "0.3.1"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "happy-dom": ">=15.0.0 || ^20.0.0",
package/src/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { NapiDiagnostic, NapiFileReplacement } from '@ngrs/compiler';
1
+ import type { FileReplacement, NgrsDiagnostic } from '@ngrs/compiler';
2
2
  import type { Plugin } from 'vite';
3
3
 
4
4
  export interface AngularStylePreprocessorOptions {
@@ -32,7 +32,7 @@ export interface AngularVitePluginOptions {
32
32
  /**
33
33
  * File replacements (`angular.json` `fileReplacements` array).
34
34
  */
35
- fileReplacements?: NapiFileReplacement[];
35
+ fileReplacements?: FileReplacement[];
36
36
  /**
37
37
  * Enable Angular Hot Module Replacement (defaults to `true` in `serve`, `false` in `build`).
38
38
  */
@@ -72,13 +72,13 @@ export interface AngularVitePluginOptions {
72
72
  /**
73
73
  * Optional observer callback receiving compiler diagnostics after each build/rebuild.
74
74
  */
75
- onDiagnostics?: (diagnostics: NapiDiagnostic[]) => void;
75
+ onDiagnostics?: (diagnostics: NgrsDiagnostic[]) => void;
76
76
  /**
77
77
  * Optional observer callback receiving component stylesheet byte sizes (used for budget checks).
78
78
  */
79
79
  onComponentStylesCollected?: (styles: CollectedComponentStyle[]) => void;
80
80
  /**
81
- * Emit `.d.ts` declaration files in `NapiProjectCompiler` (defaults to `false` for bundler builds).
81
+ * Emit `.d.ts` declaration files in `NgrsProgram` (defaults to `false` for bundler builds).
82
82
  */
83
83
  emitDts?: boolean;
84
84
  /**
@@ -108,12 +108,12 @@ export interface AngularVitePluginOptions {
108
108
  export declare const isRolldownVite: boolean;
109
109
 
110
110
  export declare function formatDiagnostics(
111
- diagnostics: NapiDiagnostic[],
111
+ diagnostics: NgrsDiagnostic[],
112
112
  rootDir?: string,
113
113
  ): {
114
114
  warnings: string[];
115
115
  errors: string[];
116
- firstError?: NapiDiagnostic;
116
+ firstError?: NgrsDiagnostic;
117
117
  };
118
118
 
119
119
  export declare function createRolldownLinkerPlugin(options?: AngularLinkerOptions): {
package/src/index.mjs CHANGED
@@ -10,10 +10,11 @@ const require = createRequire(import.meta.url);
10
10
  const napi = require('@ngrs/compiler');
11
11
 
12
12
  const {
13
- NapiProjectCompiler,
13
+ NgrsProgram,
14
14
  needsLinking,
15
15
  linkFile,
16
16
  linkFileAsync,
17
+ linkFilesAsync,
17
18
  compileSassWithDeps,
18
19
  version: getCompilerVersion,
19
20
  } = napi;
@@ -21,10 +22,59 @@ const {
21
22
  const COMPILER_CACHE_VERSION =
22
23
  typeof getCompilerVersion === 'function' ? getCompilerVersion() : '0.2.0';
23
24
 
24
- const linkFileAsyncFn =
25
- typeof linkFileAsync === 'function'
26
- ? linkFileAsync
27
- : (filePath, source, opts) => Promise.resolve(linkFile(filePath, source, opts));
25
+ /**
26
+ * Coalesces concurrent `transform()` calls arriving within the same JS microtask tick into a single
27
+ * multi-core Rayon `linkFilesAsync` batch so all CPU cores link `@angular/*` bundles in parallel
28
+ * without being throttled by Node's 4-thread libuv pool.
29
+ */
30
+ const pendingLinkerBatches = new Map();
31
+
32
+ function enqueueLinkFileRayon(filePath, source, opts) {
33
+ if (typeof linkFilesAsync !== 'function') {
34
+ return typeof linkFileAsync === 'function'
35
+ ? linkFileAsync(filePath, source, opts)
36
+ : Promise.resolve(linkFile(filePath, source, opts));
37
+ }
38
+ const optsKey = `${opts?.sourceMapping ? 1 : 0}:${opts?.linkerJitMode ? 1 : 0}:${opts?.unknownDeclarationVersionHandling ?? ''}:${opts?.optimizeForBundling ? 1 : 0}`;
39
+ let batch = pendingLinkerBatches.get(optsKey);
40
+ if (!batch) {
41
+ batch = { opts, items: [] };
42
+ pendingLinkerBatches.set(optsKey, batch);
43
+ queueMicrotask(() => {
44
+ pendingLinkerBatches.delete(optsKey);
45
+ const items = batch.items;
46
+ if (items.length === 1) {
47
+ const single = items[0];
48
+ const p =
49
+ typeof linkFileAsync === 'function'
50
+ ? linkFileAsync(single.path, single.content, batch.opts)
51
+ : Promise.resolve(linkFile(single.path, single.content, batch.opts));
52
+ p.then(single.resolve, single.reject);
53
+ return;
54
+ }
55
+ linkFilesAsync(
56
+ items.map((it) => ({ path: it.path, content: it.content })),
57
+ batch.opts,
58
+ ).then(
59
+ (results) => {
60
+ for (let i = 0; i < items.length; i++) {
61
+ items[i].resolve(results[i]);
62
+ }
63
+ },
64
+ (err) => {
65
+ for (const it of items) {
66
+ it.reject(err);
67
+ }
68
+ },
69
+ );
70
+ });
71
+ }
72
+ return new Promise((resolve, reject) => {
73
+ batch.items.push({ path: filePath, content: source, resolve, reject });
74
+ });
75
+ }
76
+
77
+ const linkFileAsyncFn = enqueueLinkFileRayon;
28
78
 
29
79
  /**
30
80
  * True when running under Vite 8+ powered by native Rust Rolldown (`'rolldownVersion' in vite`).
@@ -34,6 +84,7 @@ export const isRolldownVite =
34
84
 
35
85
  const INLINE_SOURCEMAP_RE =
36
86
  /\n?\/\/# sourceMappingURL=data:application\/json;(?:charset=utf-8;)?base64,([A-Za-z0-9+/=]+)\s*$/;
87
+ const supportsEnvironmentHotUpdate = 'DevEnvironment' in viteNamespace;
37
88
  const TS_FILE_RE = /\.[cm]?tsx?$/;
38
89
  const DTS_FILE_RE = /\.d\.[cm]?ts$/;
39
90
  const JS_MODULE_RE = /\.[cm]?js$/;
@@ -380,9 +431,9 @@ async function compileSassResource(filePath, includePaths, sassOptions, workspac
380
431
  /**
381
432
  * Formats an array of `@ngrs/compiler` diagnostics into human-readable compiler messages.
382
433
  *
383
- * @param {import('@ngrs/compiler').NapiDiagnostic[]} diagnostics
434
+ * @param {import('@ngrs/compiler').NgrsDiagnostic[]} diagnostics
384
435
  * @param {string} [rootDir]
385
- * @returns {{ warnings: string[], errors: string[], firstError?: import('@ngrs/compiler').NapiDiagnostic }}
436
+ * @returns {{ warnings: string[], errors: string[], firstError?: import('@ngrs/compiler').NgrsDiagnostic }}
386
437
  */
387
438
  export function formatDiagnostics(diagnostics, rootDir = process.cwd()) {
388
439
  const warnings = [];
@@ -528,7 +579,7 @@ export function createEsbuildLinkerPlugin(options = {}) {
528
579
  * Plugin 1: `ngrs:angular-compiler`
529
580
  *
530
581
  * Stateful incremental Angular TypeScript + Ivy template/style compiler backed by
531
- * `NapiProjectCompiler` (`@ngrs/compiler`).
582
+ * `NgrsProgram` (`@ngrs/compiler`).
532
583
  *
533
584
  * @param {import('./index.js').AngularVitePluginOptions} [options]
534
585
  * @returns {import('vite').Plugin}
@@ -576,9 +627,45 @@ export function angularCompilerPlugin(options = {}) {
576
627
  /** @type {Map<string, string>} normalizedAbsFilePath -> last compiled disk contents */
577
628
  const fileContentSnapshots = new Map();
578
629
 
630
+ const initialIsTestMode = Boolean(options.test || process.env.VITEST);
631
+ const initialSkipResolveId =
632
+ Boolean(options._skipBuildTransform) &&
633
+ loadTsconfigPathMappings(
634
+ resolveDefaultTsconfig(workspaceRoot, options.tsconfig, initialIsTestMode),
635
+ ).length === 0;
636
+
579
637
  /** @type {Set<string>} clean paths already served via `load` during one-shot build */
580
638
  const servedViaLoad = new Set();
581
639
  let pendingDeferredTypecheck = false;
640
+ let pendingHandledComponentHtmlCount = 0;
641
+
642
+ function resolveWorkspaceFileCandidates(rawFilePath) {
643
+ const abs = path.resolve(rawFilePath);
644
+ const out = [abs, toPosixPath(abs)];
645
+ try {
646
+ const realAbs = fs.realpathSync(abs);
647
+ if (!out.includes(realAbs)) out.push(realAbs);
648
+ const realPosix = toPosixPath(realAbs);
649
+ if (!out.includes(realPosix)) out.push(realPosix);
650
+ const realRoot = fs.realpathSync(workspaceRoot);
651
+ if (realRoot !== workspaceRoot) {
652
+ if (realAbs.startsWith(realRoot + path.sep)) {
653
+ const mapped = path.join(workspaceRoot, realAbs.slice(realRoot.length));
654
+ if (!out.includes(mapped)) out.push(mapped);
655
+ const mappedPosix = toPosixPath(mapped);
656
+ if (!out.includes(mappedPosix)) out.push(mappedPosix);
657
+ } else if (abs.startsWith(workspaceRoot + path.sep)) {
658
+ const mappedReal = path.join(realRoot, abs.slice(workspaceRoot.length));
659
+ if (!out.includes(mappedReal)) out.push(mappedReal);
660
+ const mappedRealPosix = toPosixPath(mappedReal);
661
+ if (!out.includes(mappedRealPosix)) out.push(mappedRealPosix);
662
+ }
663
+ }
664
+ } catch {
665
+ // Ignore missing realpath
666
+ }
667
+ return out;
668
+ }
582
669
 
583
670
  function isOneShotBuild() {
584
671
  return resolvedConfig?.command === 'build' && !resolvedConfig?.build?.watch;
@@ -755,19 +842,26 @@ export function angularCompilerPlugin(options = {}) {
755
842
  continue;
756
843
  }
757
844
  const norm = toPosixPath(path.resolve(workspaceRoot, resPath));
758
- let cssText = compiledComponentStyleCss.get(norm);
759
- if (cssText === undefined) {
845
+ const cssText = compiledComponentStyleCss.get(norm);
846
+ if (cssText !== undefined) {
847
+ collected.push({
848
+ file: norm,
849
+ css: cssText,
850
+ size: Buffer.byteLength(cssText, 'utf8'),
851
+ });
852
+ } else {
853
+ let size = 0;
760
854
  try {
761
- cssText = fs.readFileSync(norm, 'utf8');
855
+ size = fs.statSync(norm).size;
762
856
  } catch {
763
- cssText = '';
857
+ size = 0;
764
858
  }
859
+ collected.push({
860
+ file: norm,
861
+ css: '',
862
+ size,
863
+ });
765
864
  }
766
- collected.push({
767
- file: norm,
768
- css: cssText,
769
- size: Buffer.byteLength(cssText, 'utf8'),
770
- });
771
865
  }
772
866
  options.onComponentStylesCollected(collected);
773
867
  }
@@ -931,10 +1025,29 @@ export function angularCompilerPlugin(options = {}) {
931
1025
  // Ignore missing realpath
932
1026
  }
933
1027
  }
1028
+ const existingHotUpdateEnvs = userConfig?.server?.hotUpdateEnvironments;
934
1029
  patch.server = {
935
1030
  fs: {
936
1031
  allow: [...allowDirs],
937
1032
  },
1033
+ ...(supportsEnvironmentHotUpdate
1034
+ ? {
1035
+ async hotUpdateEnvironments(srv, hmr) {
1036
+ if (pendingHandledComponentHtmlCount > 0) {
1037
+ pendingHandledComponentHtmlCount--;
1038
+ const nonClientEnvs = Object.values(srv.environments).filter(
1039
+ (e) => e.name !== 'client',
1040
+ );
1041
+ await Promise.all(nonClientEnvs.map((e) => hmr(e)));
1042
+ return;
1043
+ }
1044
+ if (typeof existingHotUpdateEnvs === 'function') {
1045
+ return existingHotUpdateEnvs(srv, hmr);
1046
+ }
1047
+ await Promise.all(Object.values(srv.environments).map((e) => hmr(e)));
1048
+ },
1049
+ }
1050
+ : {}),
938
1051
  };
939
1052
  }
940
1053
 
@@ -1032,6 +1145,7 @@ export function angularCompilerPlugin(options = {}) {
1032
1145
  fileContentSnapshots.clear();
1033
1146
  servedViaLoad.clear();
1034
1147
  pendingDeferredTypecheck = false;
1148
+ pendingHandledComponentHtmlCount = 0;
1035
1149
 
1036
1150
  const oneShot = isOneShotBuild();
1037
1151
  const isTestMode = Boolean(
@@ -1044,7 +1158,7 @@ export function angularCompilerPlugin(options = {}) {
1044
1158
  !isTestMode &&
1045
1159
  modeName !== 'experimental-local' &&
1046
1160
  (options.deferTypecheck ?? true) &&
1047
- typeof NapiProjectCompiler.prototype.finishDeferredTypecheckAsync === 'function';
1161
+ typeof NgrsProgram.prototype.finishDeferredTypecheckAsync === 'function';
1048
1162
 
1049
1163
  const hasCustomJsSass = Boolean(
1050
1164
  options.stylePreprocessorOptions?.sass?.functions !== undefined ||
@@ -1052,9 +1166,9 @@ export function angularCompilerPlugin(options = {}) {
1052
1166
  );
1053
1167
  const canUseNativeExternalSass =
1054
1168
  !hasCustomJsSass &&
1055
- typeof NapiProjectCompiler.prototype.getUncompiledExternalSassFiles === 'function';
1169
+ typeof NgrsProgram.prototype.getUncompiledExternalSassFiles === 'function';
1056
1170
 
1057
- compiler = NapiProjectCompiler.open(tsconfigPath, {
1171
+ compiler = NgrsProgram.open(tsconfigPath, {
1058
1172
  fileReplacements: normalizedReplacements,
1059
1173
  hmr: enableHmr,
1060
1174
  sourceMap: enableSourceMap,
@@ -1085,32 +1199,34 @@ export function angularCompilerPlugin(options = {}) {
1085
1199
  }
1086
1200
 
1087
1201
  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);
1202
+ if (!oneShot || typeof options.onComponentStylesCollected === 'function') {
1203
+ for (const rawRes of allResources) {
1204
+ if (!SASS_FILE_RE.test(rawRes)) continue;
1205
+ const absRes = path.resolve(workspaceRoot, rawRes);
1206
+ const normStylePath = toPosixPath(absRes);
1207
+ const compiledCss = compiler.getCompiledStyleCss(absRes);
1208
+ if (compiledCss !== null && compiledCss !== undefined) {
1209
+ compiledComponentStyleCss.set(normStylePath, compiledCss);
1210
+ }
1211
+ if (!oneShot) {
1212
+ const partials = compiler.getSassPartialsForStyle(absRes) || [];
1213
+ const nextPartials = new Set();
1214
+ for (const loaded of partials) {
1215
+ const normLoaded = toPosixPath(loaded);
1216
+ if (normLoaded !== normStylePath) {
1217
+ nextPartials.add(normLoaded);
1218
+ recordSnapshot(normLoaded);
1219
+ let dependents = partialToComponentStyles.get(normLoaded);
1220
+ if (!dependents) {
1221
+ dependents = new Set();
1222
+ partialToComponentStyles.set(normLoaded, dependents);
1223
+ }
1224
+ dependents.add(normStylePath);
1225
+ }
1109
1226
  }
1110
- dependents.add(normStylePath);
1227
+ componentStyleToPartials.set(normStylePath, nextPartials);
1111
1228
  }
1112
1229
  }
1113
- componentStyleToPartials.set(normStylePath, nextPartials);
1114
1230
  }
1115
1231
 
1116
1232
  const fallbackScss = compiler.getUncompiledExternalSassFiles();
@@ -1154,36 +1270,47 @@ export function angularCompilerPlugin(options = {}) {
1154
1270
  }
1155
1271
  },
1156
1272
 
1157
- resolveId(source) {
1158
- if (
1159
- !tsconfigPathMappings.length ||
1160
- !source ||
1161
- source.startsWith('.') ||
1162
- source.startsWith('/') ||
1163
- source.startsWith('\0')
1164
- ) {
1165
- return null;
1166
- }
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;
1186
- },
1273
+ ...(initialSkipResolveId
1274
+ ? {}
1275
+ : {
1276
+ resolveId: {
1277
+ filter: {
1278
+ id: {
1279
+ exclude: /^(?:\.\.?\/|\/|\0)/,
1280
+ },
1281
+ },
1282
+ handler(source) {
1283
+ if (
1284
+ !tsconfigPathMappings.length ||
1285
+ !source ||
1286
+ source.startsWith('.') ||
1287
+ source.startsWith('/') ||
1288
+ source.startsWith('\0')
1289
+ ) {
1290
+ return null;
1291
+ }
1292
+ if (tsconfigResolveCache.has(source)) {
1293
+ return tsconfigResolveCache.get(source);
1294
+ }
1295
+ let mayMatch = tsconfigExactPatterns.has(source);
1296
+ if (!mayMatch) {
1297
+ for (let i = 0; i < tsconfigWildcardPrefixes.length; i++) {
1298
+ if (source.startsWith(tsconfigWildcardPrefixes[i])) {
1299
+ mayMatch = true;
1300
+ break;
1301
+ }
1302
+ }
1303
+ }
1304
+ if (!mayMatch) {
1305
+ tsconfigResolveCache.set(source, null);
1306
+ return null;
1307
+ }
1308
+ const resolved = resolveViaTsconfigPaths(source, tsconfigPathMappings);
1309
+ tsconfigResolveCache.set(source, resolved);
1310
+ return resolved;
1311
+ },
1312
+ },
1313
+ }),
1187
1314
 
1188
1315
  load: {
1189
1316
  filter: {
@@ -1218,263 +1345,336 @@ export function angularCompilerPlugin(options = {}) {
1218
1345
  },
1219
1346
  },
1220
1347
 
1221
- transform: {
1222
- filter: {
1223
- id: {
1224
- include: TS_FILE_RE,
1225
- exclude: [/\/node_modules\//, DTS_FILE_RE],
1226
- },
1227
- },
1228
- async handler(_code, id) {
1229
- if (!compiler || id.startsWith('\0')) {
1230
- return null;
1231
- }
1232
- const query = getQueryString(id);
1233
- if (query && VITE_SPECIAL_QUERY_RE.test(query)) {
1234
- return null;
1235
- }
1236
- const cleanId = stripQueryAndHash(id);
1237
- if (servedViaLoad.has(cleanId)) {
1238
- return null;
1239
- }
1240
- const posixId = toPosixPath(cleanId);
1241
- if (
1242
- posixId.includes('/node_modules/') ||
1243
- DTS_FILE_RE.test(posixId) ||
1244
- !TS_FILE_RE.test(posixId)
1245
- ) {
1246
- return null;
1247
- }
1348
+ ...(options._skipBuildTransform
1349
+ ? {}
1350
+ : {
1351
+ transform: {
1352
+ filter: {
1353
+ id: {
1354
+ include: TS_FILE_RE,
1355
+ exclude: [/\/node_modules\//, DTS_FILE_RE],
1356
+ },
1357
+ },
1358
+ async handler(_code, id) {
1359
+ if (!compiler || id.startsWith('\0')) {
1360
+ return null;
1361
+ }
1362
+ const query = getQueryString(id);
1363
+ if (query && VITE_SPECIAL_QUERY_RE.test(query)) {
1364
+ return null;
1365
+ }
1366
+ const cleanId = stripQueryAndHash(id);
1367
+ if (servedViaLoad.has(cleanId)) {
1368
+ return null;
1369
+ }
1370
+ const posixId = toPosixPath(cleanId);
1371
+ if (
1372
+ posixId.includes('/node_modules/') ||
1373
+ DTS_FILE_RE.test(posixId) ||
1374
+ !TS_FILE_RE.test(posixId)
1375
+ ) {
1376
+ return null;
1377
+ }
1248
1378
 
1249
- if (resolvedConfig?.command === 'serve') {
1250
- await syncOnDiskChangesForTs(cleanId, null);
1251
- }
1379
+ if (resolvedConfig?.command === 'serve') {
1380
+ await syncOnDiskChangesForTs(cleanId, null);
1381
+ }
1252
1382
 
1253
- const modOut = loadEmittedModuleFromCompiler(compiler, cleanId, enableSourceMap);
1254
- if (!modOut) {
1255
- return null;
1256
- }
1383
+ const modOut = loadEmittedModuleFromCompiler(compiler, cleanId, enableSourceMap);
1384
+ if (!modOut) {
1385
+ return null;
1386
+ }
1257
1387
 
1258
- if (!isOneShotBuild()) {
1259
- recordSnapshot(cleanId);
1260
- const resourceDeps = compiler.getResourceDependencies(cleanId);
1261
- for (const dep of resourceDeps) {
1262
- recordSnapshot(dep);
1263
- this.addWatchFile(dep);
1264
- const normDep = toPosixPath(path.resolve(workspaceRoot, dep));
1265
- const partials = componentStyleToPartials.get(normDep);
1266
- if (partials) {
1267
- for (const partialPath of partials) {
1268
- recordSnapshot(partialPath);
1269
- this.addWatchFile(partialPath);
1388
+ if (!isOneShotBuild()) {
1389
+ recordSnapshot(cleanId);
1390
+ const resourceDeps = compiler.getResourceDependencies(cleanId);
1391
+ for (const dep of resourceDeps) {
1392
+ recordSnapshot(dep);
1393
+ this.addWatchFile(dep);
1394
+ const normDep = toPosixPath(path.resolve(workspaceRoot, dep));
1395
+ const partials = componentStyleToPartials.get(normDep);
1396
+ if (partials) {
1397
+ for (const partialPath of partials) {
1398
+ recordSnapshot(partialPath);
1399
+ this.addWatchFile(partialPath);
1400
+ }
1401
+ }
1402
+ }
1270
1403
  }
1404
+
1405
+ return modOut;
1406
+ },
1407
+ },
1408
+ }),
1409
+
1410
+ ...(supportsEnvironmentHotUpdate
1411
+ ? {
1412
+ async hotUpdate(ctx) {
1413
+ if (this.environment && this.environment.name !== 'client') {
1414
+ return undefined;
1271
1415
  }
1272
- }
1416
+ return processHotUpdate(ctx);
1417
+ },
1273
1418
  }
1419
+ : {
1420
+ async handleHotUpdate(ctx) {
1421
+ return processHotUpdate(ctx);
1422
+ },
1423
+ }),
1424
+ };
1274
1425
 
1275
- return modOut;
1276
- },
1277
- },
1426
+ async function processHotUpdate(ctx) {
1427
+ if (!compiler || ctx.type === 'delete') {
1428
+ return undefined;
1429
+ }
1430
+ const cleanFile = stripQueryAndHash(ctx.file);
1431
+ const candidates = resolveWorkspaceFileCandidates(cleanFile);
1432
+ const normFile = toPosixPath(path.resolve(cleanFile));
1433
+ if (normFile.includes('/node_modules/') || DTS_FILE_RE.test(normFile)) {
1434
+ return undefined;
1435
+ }
1278
1436
 
1279
- async handleHotUpdate(ctx) {
1280
- if (!compiler) {
1281
- return undefined;
1282
- }
1283
- const cleanFile = stripQueryAndHash(ctx.file);
1284
- const normFile = toPosixPath(path.resolve(cleanFile));
1285
- if (normFile.includes('/node_modules/') || DTS_FILE_RE.test(normFile)) {
1286
- return undefined;
1287
- }
1437
+ const isTsChange = TS_FILE_RE.test(normFile);
1438
+ const isResourceChange = RESOURCE_FILE_RE.test(normFile);
1439
+ const isTsconfigChange =
1440
+ normFile.endsWith('/tsconfig.json') || /tsconfig.*\.json$/i.test(path.basename(normFile));
1288
1441
 
1289
- const isTsChange = TS_FILE_RE.test(normFile);
1290
- const isResourceChange = RESOURCE_FILE_RE.test(normFile);
1291
- const isTsconfigChange =
1292
- normFile.endsWith('/tsconfig.json') || /tsconfig.*\.json$/i.test(path.basename(normFile));
1442
+ if (!isTsChange && !isResourceChange && !isTsconfigChange) {
1443
+ return undefined;
1444
+ }
1293
1445
 
1294
- if (!isTsChange && !isResourceChange && !isTsconfigChange) {
1295
- return undefined;
1446
+ // 1. Handle external component resource (.html / .css / .scss / .sass + SCSS partials)
1447
+ if (isResourceChange && !isTsChange) {
1448
+ let matchedResourceFile = cleanFile;
1449
+ let directOwners = [];
1450
+ for (const cand of candidates) {
1451
+ const owners = compiler.getAffectedComponentsForResource(cand);
1452
+ if (owners.length > 0) {
1453
+ directOwners = owners;
1454
+ matchedResourceFile = cand;
1455
+ break;
1456
+ }
1296
1457
  }
1458
+ const matchedNormFile = toPosixPath(path.resolve(workspaceRoot, matchedResourceFile));
1459
+ const affectedStylePaths = new Set();
1297
1460
 
1298
- // 1. Handle external component resource (.html / .css / .scss / .sass + SCSS partials)
1299
- if (isResourceChange && !isTsChange) {
1300
- const directOwners = compiler.getAffectedComponentsForResource(cleanFile);
1301
- const affectedStylePaths = new Set();
1302
-
1303
- if (SASS_FILE_RE.test(normFile)) {
1304
- if (directOwners.length > 0) {
1305
- affectedStylePaths.add(normFile);
1306
- }
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
- }
1461
+ if (SASS_FILE_RE.test(normFile)) {
1462
+ if (directOwners.length > 0) {
1463
+ affectedStylePaths.add(matchedNormFile);
1464
+ }
1465
+ for (const cand of candidates) {
1466
+ const dependentStyles = partialToComponentStyles.get(toPosixPath(cand));
1317
1467
  if (dependentStyles) {
1318
1468
  for (const depStyle of dependentStyles) {
1319
1469
  affectedStylePaths.add(depStyle);
1320
1470
  }
1321
1471
  }
1322
1472
  }
1473
+ }
1323
1474
 
1324
- const rebuildTargets =
1325
- affectedStylePaths.size > 0 ? [...affectedStylePaths] : directOwners.length > 0 ? [cleanFile] : [];
1475
+ const rebuildTargets =
1476
+ affectedStylePaths.size > 0
1477
+ ? [...affectedStylePaths]
1478
+ : directOwners.length > 0
1479
+ ? [matchedResourceFile]
1480
+ : [];
1326
1481
 
1327
- if (rebuildTargets.length === 0) {
1328
- // Global stylesheet or unrelated static HTML file — let Vite handle natively
1329
- if (/\.(?:css|scss|sass|less)$/i.test(normFile)) {
1330
- options.onDevServerUpdate?.({ kind: 'style-update', file: cleanFile });
1331
- }
1332
- return undefined;
1482
+ if (rebuildTargets.length === 0) {
1483
+ // Global stylesheet or unrelated static HTML file — let Vite handle natively
1484
+ if (/\.(?:css|scss|sass|less)$/i.test(normFile)) {
1485
+ options.onDevServerUpdate?.({ kind: 'style-update', file: cleanFile });
1333
1486
  }
1487
+ return undefined;
1488
+ }
1334
1489
 
1335
- const resourceRebuildStart = performance.now();
1336
- if (affectedStylePaths.size > 0) {
1337
- try {
1338
- const overrides = await preprocessComponentStyles([...affectedStylePaths]);
1339
- if (overrides.length > 0) {
1340
- compiler.setResourceOverrides(overrides);
1341
- }
1342
- } catch (err) {
1343
- const msg = err instanceof Error ? err.message : String(err);
1344
- if (!options.suppressViteDiagnosticsLog) {
1345
- resolvedConfig?.logger?.error(msg);
1346
- }
1347
- ctx.server.ws.send({
1348
- type: 'error',
1349
- err: { message: msg, stack: '', id: cleanFile, plugin: 'ngrs:angular-compiler' },
1350
- });
1351
- options.onDevServerUpdate?.({ kind: 'error', file: cleanFile, message: msg });
1352
- return [];
1490
+ // Preserve only genuine Vite global CSS pipeline modules (e.g. `styles.scss?direct` with
1491
+ // `type === 'css'` / `isSelfAccepting`, or Sass partial `asset` nodes imported by global CSS).
1492
+ // Never return synthetic `type === 'js'` nodes registered via `this.addWatchFile(...)`,
1493
+ // which have `isSelfAccepting === false` and would otherwise force a Vite `full-reload`!
1494
+ const isStylesheetFile = /\.(?:css|scss|sass|less)$/i.test(normFile);
1495
+ const isHtmlTemplateFile = /\.html?$/i.test(normFile);
1496
+ const isGlobalCssPipelineMod = (m) =>
1497
+ m.type === 'css' ||
1498
+ Boolean(m.isSelfAccepting) ||
1499
+ (m.type === 'asset' &&
1500
+ Boolean(
1501
+ m.importers &&
1502
+ [...m.importers].some((imp) => imp.type === 'css' || Boolean(imp.isSelfAccepting)),
1503
+ ));
1504
+ const passthroughCssMods = isStylesheetFile
1505
+ ? (ctx.modules || []).filter(isGlobalCssPipelineMod)
1506
+ : [];
1507
+
1508
+ // Deduplicate duplicate OS watcher events (e.g. macOS FSEvents firing for both symlinked
1509
+ // `/var/folders/...` and canonical `/private/var/folders/...`) when content is unchanged.
1510
+ const diskContentNow = readDiskTextSafe(matchedNormFile);
1511
+ if (
1512
+ enableHmr &&
1513
+ diskContentNow !== null &&
1514
+ fileContentSnapshots.get(matchedNormFile) === diskContentNow
1515
+ ) {
1516
+ const ownerHasActiveHmr = directOwners.some((owner) =>
1517
+ compiler.getHmrIdsForFile(owner).some((id) => activeHmrUpdates.has(id)),
1518
+ );
1519
+ if (ownerHasActiveHmr) {
1520
+ if (supportsEnvironmentHotUpdate && isHtmlTemplateFile && passthroughCssMods.length === 0) {
1521
+ pendingHandledComponentHtmlCount++;
1353
1522
  }
1523
+ return passthroughCssMods;
1354
1524
  }
1525
+ }
1355
1526
 
1356
- const rebuildResult = compiler.rebuild(rebuildTargets);
1357
- const resourceRebuildMs = performance.now() - resourceRebuildStart;
1358
- for (const target of rebuildTargets) {
1359
- recordSnapshot(target);
1360
- }
1361
- recordSnapshot(cleanFile);
1362
- surfaceDiagnostics(rebuildResult.diagnostics, null, ctx.server);
1363
-
1364
- const allOwners = new Set(directOwners);
1365
- for (const target of rebuildTargets) {
1366
- for (const owner of compiler.getAffectedComponentsForResource(target)) {
1367
- allOwners.add(owner);
1527
+ const resourceRebuildStart = performance.now();
1528
+ if (affectedStylePaths.size > 0) {
1529
+ try {
1530
+ const overrides = await preprocessComponentStyles([...affectedStylePaths]);
1531
+ if (overrides.length > 0) {
1532
+ compiler.setResourceOverrides(overrides);
1533
+ }
1534
+ } catch (err) {
1535
+ const msg = err instanceof Error ? err.message : String(err);
1536
+ if (!options.suppressViteDiagnosticsLog) {
1537
+ resolvedConfig?.logger?.error(msg);
1538
+ }
1539
+ ctx.server.ws.send({
1540
+ type: 'error',
1541
+ err: { message: msg, stack: '', id: cleanFile, plugin: 'ngrs:angular-compiler' },
1542
+ });
1543
+ options.onDevServerUpdate?.({ kind: 'error', file: cleanFile, message: msg });
1544
+ if (supportsEnvironmentHotUpdate && isHtmlTemplateFile) {
1545
+ pendingHandledComponentHtmlCount++;
1368
1546
  }
1547
+ return [];
1369
1548
  }
1370
- const ownerList = [...allOwners];
1371
- const invalidatedOwnerMods = invalidateOwnerModules(ctx.server, ownerList);
1549
+ }
1372
1550
 
1373
- // Preserve any non-component Vite CSS modules (in case a file is both global & component CSS)
1374
- const passthroughCssMods = (ctx.modules || []).filter(
1375
- (m) => m.file && toPosixPath(m.file) === normFile,
1376
- );
1551
+ const rebuildResult = compiler.rebuild(rebuildTargets);
1552
+ const resourceRebuildMs = performance.now() - resourceRebuildStart;
1553
+ for (const target of rebuildTargets) {
1554
+ recordSnapshot(target);
1555
+ }
1556
+ recordSnapshot(matchedResourceFile);
1557
+ recordSnapshot(cleanFile);
1558
+ surfaceDiagnostics(rebuildResult.diagnostics, null, ctx.server);
1377
1559
 
1378
- if (enableHmr && rebuildResult.exitCode === 0) {
1379
- let sentLiveHmr = false;
1380
- const timestamp = Date.now();
1381
- for (const owner of ownerList) {
1382
- const hmrIds = compiler.getHmrIdsForFile(owner);
1383
- for (const hmrId of hmrIds) {
1384
- const updateCode = compiler.getHmrUpdateModule(hmrId);
1385
- if (updateCode) {
1386
- activeHmrUpdates.set(hmrId, updateCode);
1387
- ctx.server.ws.send({
1388
- type: 'custom',
1389
- event: 'angular:component-update',
1390
- data: { id: hmrId, timestamp },
1391
- });
1392
- sentLiveHmr = true;
1393
- }
1560
+ const allOwners = new Set(directOwners);
1561
+ for (const target of rebuildTargets) {
1562
+ for (const owner of compiler.getAffectedComponentsForResource(target)) {
1563
+ allOwners.add(owner);
1564
+ }
1565
+ }
1566
+ const ownerList = [...allOwners];
1567
+ const invalidatedOwnerMods = invalidateOwnerModules(ctx.server, ownerList);
1568
+
1569
+ if (enableHmr && rebuildResult.exitCode === 0) {
1570
+ let sentLiveHmr = false;
1571
+ const timestamp = Date.now();
1572
+ for (const owner of ownerList) {
1573
+ const hmrIds = compiler.getHmrIdsForFile(owner);
1574
+ for (const hmrId of hmrIds) {
1575
+ const updateCode = compiler.getHmrUpdateModule(hmrId);
1576
+ if (updateCode) {
1577
+ activeHmrUpdates.set(hmrId, updateCode);
1578
+ ctx.server.ws.send({
1579
+ type: 'custom',
1580
+ event: 'angular:component-update',
1581
+ data: { id: hmrId, timestamp },
1582
+ });
1583
+ sentLiveHmr = true;
1394
1584
  }
1395
1585
  }
1396
- if (sentLiveHmr) {
1397
- options.onDevServerUpdate?.({
1398
- kind: 'component-update',
1399
- file: cleanFile,
1400
- durationMs: resourceRebuildMs,
1401
- });
1402
- return passthroughCssMods;
1403
- }
1404
1586
  }
1405
-
1406
- if (invalidatedOwnerMods.length > 0) {
1587
+ if (sentLiveHmr) {
1407
1588
  options.onDevServerUpdate?.({
1408
- kind: 'reload',
1409
- file: cleanFile,
1589
+ kind: 'component-update',
1590
+ file: matchedResourceFile,
1410
1591
  durationMs: resourceRebuildMs,
1411
1592
  });
1412
- return [...invalidatedOwnerMods, ...passthroughCssMods];
1593
+ if (supportsEnvironmentHotUpdate && isHtmlTemplateFile && passthroughCssMods.length === 0) {
1594
+ pendingHandledComponentHtmlCount++;
1595
+ }
1596
+ return passthroughCssMods;
1413
1597
  }
1414
- ctx.server.ws.send({ type: 'full-reload', path: '*' });
1598
+ }
1599
+
1600
+ if (invalidatedOwnerMods.length > 0) {
1415
1601
  options.onDevServerUpdate?.({
1416
1602
  kind: 'reload',
1417
1603
  file: cleanFile,
1418
1604
  durationMs: resourceRebuildMs,
1419
1605
  });
1420
- return [];
1606
+ return [...invalidatedOwnerMods, ...passthroughCssMods];
1421
1607
  }
1422
-
1423
- // 2. Handle .ts / fileReplacements / tsconfig.json changes
1424
- if (isTsconfigChange) {
1425
- refreshTsconfigMappings(tsconfigPath);
1608
+ ctx.server.ws.send({ type: 'full-reload', path: '*' });
1609
+ options.onDevServerUpdate?.({
1610
+ kind: 'reload',
1611
+ file: cleanFile,
1612
+ durationMs: resourceRebuildMs,
1613
+ });
1614
+ if (supportsEnvironmentHotUpdate && isHtmlTemplateFile) {
1615
+ pendingHandledComponentHtmlCount++;
1426
1616
  }
1427
- const tsRebuildStart = performance.now();
1428
- compiler.rebuild([cleanFile]);
1429
- recordSnapshot(cleanFile);
1617
+ return [];
1618
+ }
1430
1619
 
1431
- // Check if newly added/edited component introduced new .scss resources
1432
- const postResources = compiler.getAllResources();
1433
- const uncompiledScss = postResources.filter((r) => {
1434
- if (!SASS_FILE_RE.test(r)) return false;
1435
- const norm = toPosixPath(path.resolve(workspaceRoot, r));
1436
- return !compiledComponentStyleCss.has(norm);
1437
- });
1438
- if (uncompiledScss.length > 0) {
1439
- const extraOverrides = await preprocessComponentStyles(uncompiledScss);
1440
- if (extraOverrides.length > 0) {
1441
- compiler.setResourceOverrides(extraOverrides);
1442
- compiler.rebuild(extraOverrides.map((o) => o.path));
1443
- }
1620
+ // 2. Handle .ts / fileReplacements / tsconfig.json changes
1621
+ if (isTsconfigChange) {
1622
+ refreshTsconfigMappings(tsconfigPath);
1623
+ }
1624
+ const matchedTsFile =
1625
+ candidates.find((c) => compiler.getEmittedModule?.(c) || compiler.getEmittedJs?.(c)) ||
1626
+ cleanFile;
1627
+ const tsRebuildStart = performance.now();
1628
+ compiler.rebuild([matchedTsFile]);
1629
+ recordSnapshot(matchedTsFile);
1630
+ recordSnapshot(cleanFile);
1631
+
1632
+ // Check if newly added/edited component introduced new .scss resources
1633
+ const postResources = compiler.getAllResources();
1634
+ const uncompiledScss = postResources.filter((r) => {
1635
+ if (!SASS_FILE_RE.test(r)) return false;
1636
+ const norm = toPosixPath(path.resolve(workspaceRoot, r));
1637
+ return !compiledComponentStyleCss.has(norm);
1638
+ });
1639
+ if (uncompiledScss.length > 0) {
1640
+ const extraOverrides = await preprocessComponentStyles(uncompiledScss);
1641
+ if (extraOverrides.length > 0) {
1642
+ compiler.setResourceOverrides(extraOverrides);
1643
+ compiler.rebuild(extraOverrides.map((o) => o.path));
1444
1644
  }
1645
+ }
1445
1646
 
1446
- const tsRebuildMs = performance.now() - tsRebuildStart;
1447
- surfaceDiagnostics(compiler.getDiagnostics(), null, ctx.server);
1647
+ const tsRebuildMs = performance.now() - tsRebuildStart;
1648
+ surfaceDiagnostics(compiler.getDiagnostics(), null, ctx.server);
1448
1649
 
1449
- // Refresh HMR cache for modified .ts components if applicable and invalidate Vite moduleGraph
1450
- const changedTsPaths = [cleanFile];
1451
- for (const rep of normalizedReplacements) {
1452
- if (toPosixPath(rep.with) === normFile) {
1453
- changedTsPaths.push(rep.replace);
1454
- }
1650
+ // Refresh HMR cache for modified .ts components if applicable and invalidate Vite moduleGraph
1651
+ const changedTsPaths = [matchedTsFile];
1652
+ for (const rep of normalizedReplacements) {
1653
+ if (candidates.some((c) => toPosixPath(rep.with) === toPosixPath(c))) {
1654
+ changedTsPaths.push(rep.replace);
1455
1655
  }
1456
- for (const tsPath of changedTsPaths) {
1457
- for (const hmrId of compiler.getHmrIdsForFile(tsPath)) {
1458
- const updateCode = compiler.getHmrUpdateModule(hmrId);
1459
- if (updateCode) {
1460
- activeHmrUpdates.set(hmrId, updateCode);
1461
- }
1656
+ }
1657
+ for (const tsPath of changedTsPaths) {
1658
+ for (const hmrId of compiler.getHmrIdsForFile(tsPath)) {
1659
+ const updateCode = compiler.getHmrUpdateModule(hmrId);
1660
+ if (updateCode) {
1661
+ activeHmrUpdates.set(hmrId, updateCode);
1462
1662
  }
1463
1663
  }
1664
+ }
1464
1665
 
1465
- options.onDevServerUpdate?.({
1466
- kind: 'reload',
1467
- file: cleanFile,
1468
- durationMs: tsRebuildMs,
1469
- });
1666
+ options.onDevServerUpdate?.({
1667
+ kind: 'reload',
1668
+ file: matchedTsFile,
1669
+ durationMs: tsRebuildMs,
1670
+ });
1470
1671
 
1471
- const invalidated = invalidateOwnerModules(ctx.server, changedTsPaths);
1472
- if (invalidated.length > 0) {
1473
- return invalidated;
1474
- }
1475
- return ctx.modules;
1476
- },
1477
- };
1672
+ const invalidated = invalidateOwnerModules(ctx.server, changedTsPaths);
1673
+ if (invalidated.length > 0) {
1674
+ return invalidated;
1675
+ }
1676
+ return ctx.modules;
1677
+ }
1478
1678
  }
1479
1679
 
1480
1680
  /**
@@ -1565,6 +1765,11 @@ export function angularLinkerPlugin(options = {}) {
1565
1765
  transform: {
1566
1766
  filter: {
1567
1767
  id: /\.[cm]?js(?:$|\?)/,
1768
+ ...(isRolldownVite
1769
+ ? {
1770
+ code: /(?:ngDeclare|setClassMetadata|setClassDebugInfo|static\s+ɵ|InjectionToken|\\u0275)/,
1771
+ }
1772
+ : {}),
1568
1773
  },
1569
1774
  async handler(code, id) {
1570
1775
  if (id.startsWith('\0')) {
package/src/testing.mjs CHANGED
@@ -165,7 +165,7 @@ if (!globalThis[ANGULAR_TESTBED_SETUP]) {
165
165
  /**
166
166
  * First-class Vitest plugin for Angular (`@ngrs/vite/testing`).
167
167
  * Configures Angular `TestBed` (`BrowserTestingModule` + `happy-dom` + zoneless / `zone.js/testing`),
168
- * compiles `*.spec.ts` + components/templates/SCSS via native Rust `NapiProjectCompiler`, and links
168
+ * compiles `*.spec.ts` + components/templates/SCSS via native Rust `NgrsProgram`, and links
169
169
  * all Partial-Ivy `node_modules` packages via native Rust Ivy Linker.
170
170
  *
171
171
  * @param {import('./testing.js').AngularTestingPluginOptions} [options]