@ngrs/vite 0.2.0 → 0.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngrs/vite",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
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.3.0"
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
@@ -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';
@@ -9,17 +10,71 @@ const require = createRequire(import.meta.url);
9
10
  const napi = require('@ngrs/compiler');
10
11
 
11
12
  const {
12
- NapiProjectCompiler,
13
+ NgrsProgram,
13
14
  needsLinking,
14
15
  linkFile,
15
16
  linkFileAsync,
17
+ linkFilesAsync,
16
18
  compileSassWithDeps,
19
+ version: getCompilerVersion,
17
20
  } = napi;
18
21
 
19
- const linkFileAsyncFn =
20
- typeof linkFileAsync === 'function'
21
- ? linkFileAsync
22
- : (filePath, source, opts) => Promise.resolve(linkFile(filePath, source, opts));
22
+ const COMPILER_CACHE_VERSION =
23
+ typeof getCompilerVersion === 'function' ? getCompilerVersion() : '0.2.0';
24
+
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;
23
78
 
24
79
  /**
25
80
  * True when running under Vite 8+ powered by native Rust Rolldown (`'rolldownVersion' in vite`).
@@ -199,6 +254,86 @@ function resolveViaTsconfigPaths(source, mappings) {
199
254
  return null;
200
255
  }
201
256
 
257
+ function loadEmittedModuleFromCompiler(compilerInstance, cleanId, wantSourceMap) {
258
+ if (typeof compilerInstance.getEmittedModule === 'function') {
259
+ const mod = compilerInstance.getEmittedModule(cleanId);
260
+ if (!mod) {
261
+ return null;
262
+ }
263
+ if (!wantSourceMap || !mod.map) {
264
+ return { code: mod.code, map: null };
265
+ }
266
+ try {
267
+ return { code: mod.code, map: JSON.parse(mod.map) };
268
+ } catch {
269
+ return { code: mod.code, map: null };
270
+ }
271
+ }
272
+ const emittedJs = compilerInstance.getEmittedJs(cleanId);
273
+ if (emittedJs === null || emittedJs === undefined) {
274
+ return null;
275
+ }
276
+ return wantSourceMap ? extractInlineSourceMap(emittedJs) : { code: emittedJs, map: null };
277
+ }
278
+
279
+ /** @type {Map<string, { code: string, sourceMap: string | null }>} */
280
+ const linkerMemoryCache = new Map();
281
+
282
+ function computeLinkerCacheKey(source, { sourceMapping, linkerJitMode, unknownDeclarationVersionHandling, optimizeForBundling }) {
283
+ return crypto
284
+ .createHash('md5')
285
+ .update(
286
+ `${COMPILER_CACHE_VERSION}|${sourceMapping ? 1 : 0}|${linkerJitMode ? 1 : 0}|${unknownDeclarationVersionHandling || 'error'}|${optimizeForBundling ? 1 : 0}|`,
287
+ )
288
+ .update(source)
289
+ .digest('hex');
290
+ }
291
+
292
+ async function readLinkerCache(cacheDir, cacheDirExistsOnDisk, key, sourceMapping) {
293
+ const mem = linkerMemoryCache.get(key);
294
+ if (mem) {
295
+ return mem;
296
+ }
297
+ if (!cacheDir || !cacheDirExistsOnDisk) {
298
+ return null;
299
+ }
300
+ try {
301
+ if (!sourceMapping) {
302
+ const code = await readFile(path.join(cacheDir, `${key}.js`), 'utf8');
303
+ const entry = { code, sourceMap: null };
304
+ linkerMemoryCache.set(key, entry);
305
+ return entry;
306
+ }
307
+ const raw = await readFile(path.join(cacheDir, `${key}.json`), 'utf8');
308
+ const parsed = JSON.parse(raw);
309
+ if (parsed && typeof parsed.code === 'string') {
310
+ linkerMemoryCache.set(key, parsed);
311
+ return parsed;
312
+ }
313
+ } catch {
314
+ // Cache miss
315
+ }
316
+ return null;
317
+ }
318
+
319
+ async function flushLinkerCacheWrites(cacheDir, pendingWrites) {
320
+ if (!cacheDir || pendingWrites.length === 0) {
321
+ return;
322
+ }
323
+ try {
324
+ await mkdir(cacheDir, { recursive: true });
325
+ await Promise.all(
326
+ pendingWrites.map(({ key, entry, sourceMapping }) =>
327
+ sourceMapping
328
+ ? writeFile(path.join(cacheDir, `${key}.json`), JSON.stringify(entry), 'utf8')
329
+ : writeFile(path.join(cacheDir, `${key}.js`), entry.code, 'utf8'),
330
+ ),
331
+ );
332
+ } catch {
333
+ // Ignore disk cache write errors on read-only filesystems
334
+ }
335
+ }
336
+
202
337
  function extractInlineSourceMap(jsCode) {
203
338
  const match = INLINE_SOURCEMAP_RE.exec(jsCode);
204
339
  if (!match) {
@@ -295,9 +430,9 @@ async function compileSassResource(filePath, includePaths, sassOptions, workspac
295
430
  /**
296
431
  * Formats an array of `@ngrs/compiler` diagnostics into human-readable compiler messages.
297
432
  *
298
- * @param {import('@ngrs/compiler').NapiDiagnostic[]} diagnostics
433
+ * @param {import('@ngrs/compiler').NgrsDiagnostic[]} diagnostics
299
434
  * @param {string} [rootDir]
300
- * @returns {{ warnings: string[], errors: string[], firstError?: import('@ngrs/compiler').NapiDiagnostic }}
435
+ * @returns {{ warnings: string[], errors: string[], firstError?: import('@ngrs/compiler').NgrsDiagnostic }}
301
436
  */
302
437
  export function formatDiagnostics(diagnostics, rootDir = process.cwd()) {
303
438
  const warnings = [];
@@ -443,7 +578,7 @@ export function createEsbuildLinkerPlugin(options = {}) {
443
578
  * Plugin 1: `ngrs:angular-compiler`
444
579
  *
445
580
  * Stateful incremental Angular TypeScript + Ivy template/style compiler backed by
446
- * `NapiProjectCompiler` (`@ngrs/compiler`).
581
+ * `NgrsProgram` (`@ngrs/compiler`).
447
582
  *
448
583
  * @param {import('./index.js').AngularVitePluginOptions} [options]
449
584
  * @returns {import('vite').Plugin}
@@ -458,6 +593,27 @@ export function angularCompilerPlugin(options = {}) {
458
593
  let includePaths = [];
459
594
  let normalizedReplacements = [];
460
595
  let tsconfigPathMappings = [];
596
+ /** @type {Set<string>} */
597
+ let tsconfigExactPatterns = new Set();
598
+ /** @type {string[]} */
599
+ let tsconfigWildcardPrefixes = [];
600
+ /** @type {Map<string, string | null>} */
601
+ const tsconfigResolveCache = new Map();
602
+
603
+ function refreshTsconfigMappings(cfgPath) {
604
+ tsconfigPathMappings = loadTsconfigPathMappings(cfgPath);
605
+ tsconfigResolveCache.clear();
606
+ tsconfigExactPatterns = new Set();
607
+ const prefixes = new Set();
608
+ for (const m of tsconfigPathMappings) {
609
+ if (m.hasWildcard) {
610
+ prefixes.add(m.prefix);
611
+ } else {
612
+ tsconfigExactPatterns.add(m.pattern);
613
+ }
614
+ }
615
+ tsconfigWildcardPrefixes = [...prefixes];
616
+ }
461
617
 
462
618
  /** @type {Map<string, Set<string>>} partialPath -> Set<componentScssPath> */
463
619
  const partialToComponentStyles = new Map();
@@ -470,6 +626,13 @@ export function angularCompilerPlugin(options = {}) {
470
626
  /** @type {Map<string, string>} normalizedAbsFilePath -> last compiled disk contents */
471
627
  const fileContentSnapshots = new Map();
472
628
 
629
+ const initialIsTestMode = Boolean(options.test || process.env.VITEST);
630
+ const initialSkipResolveId =
631
+ Boolean(options._skipBuildTransform) &&
632
+ loadTsconfigPathMappings(
633
+ resolveDefaultTsconfig(workspaceRoot, options.tsconfig, initialIsTestMode),
634
+ ).length === 0;
635
+
473
636
  /** @type {Set<string>} clean paths already served via `load` during one-shot build */
474
637
  const servedViaLoad = new Set();
475
638
  let pendingDeferredTypecheck = false;
@@ -649,19 +812,26 @@ export function angularCompilerPlugin(options = {}) {
649
812
  continue;
650
813
  }
651
814
  const norm = toPosixPath(path.resolve(workspaceRoot, resPath));
652
- let cssText = compiledComponentStyleCss.get(norm);
653
- if (cssText === undefined) {
815
+ const cssText = compiledComponentStyleCss.get(norm);
816
+ if (cssText !== undefined) {
817
+ collected.push({
818
+ file: norm,
819
+ css: cssText,
820
+ size: Buffer.byteLength(cssText, 'utf8'),
821
+ });
822
+ } else {
823
+ let size = 0;
654
824
  try {
655
- cssText = fs.readFileSync(norm, 'utf8');
825
+ size = fs.statSync(norm).size;
656
826
  } catch {
657
- cssText = '';
827
+ size = 0;
658
828
  }
829
+ collected.push({
830
+ file: norm,
831
+ css: '',
832
+ size,
833
+ });
659
834
  }
660
- collected.push({
661
- file: norm,
662
- css: cssText,
663
- size: Buffer.byteLength(cssText, 'utf8'),
664
- });
665
835
  }
666
836
  options.onComponentStylesCollected(collected);
667
837
  }
@@ -857,7 +1027,7 @@ export function angularCompilerPlugin(options = {}) {
857
1027
  options.test || process.env.VITEST || config.mode === 'test' || config.test,
858
1028
  );
859
1029
  tsconfigPath = resolveDefaultTsconfig(workspaceRoot, options.tsconfig, isTestMode);
860
- tsconfigPathMappings = loadTsconfigPathMappings(tsconfigPath);
1030
+ refreshTsconfigMappings(tsconfigPath);
861
1031
  includePaths = resolveIncludePaths(workspaceRoot);
862
1032
  normalizedReplacements = resolveFileReplacements(workspaceRoot);
863
1033
  enableHmr = isTestMode
@@ -938,9 +1108,17 @@ export function angularCompilerPlugin(options = {}) {
938
1108
  !isTestMode &&
939
1109
  modeName !== 'experimental-local' &&
940
1110
  (options.deferTypecheck ?? true) &&
941
- typeof NapiProjectCompiler.prototype.finishDeferredTypecheckAsync === 'function';
1111
+ typeof NgrsProgram.prototype.finishDeferredTypecheckAsync === 'function';
942
1112
 
943
- compiler = NapiProjectCompiler.open(tsconfigPath, {
1113
+ const hasCustomJsSass = Boolean(
1114
+ options.stylePreprocessorOptions?.sass?.functions !== undefined ||
1115
+ options.stylePreprocessorOptions?.sass?.importers !== undefined,
1116
+ );
1117
+ const canUseNativeExternalSass =
1118
+ !hasCustomJsSass &&
1119
+ typeof NgrsProgram.prototype.getUncompiledExternalSassFiles === 'function';
1120
+
1121
+ compiler = NgrsProgram.open(tsconfigPath, {
944
1122
  fileReplacements: normalizedReplacements,
945
1123
  hmr: enableHmr,
946
1124
  sourceMap: enableSourceMap,
@@ -949,17 +1127,18 @@ export function angularCompilerPlugin(options = {}) {
949
1127
  deferTypecheck: useDeferredTypecheck,
950
1128
  inlineStyleLanguage: options.inlineStyleLanguage,
951
1129
  styleIncludePaths: includePaths,
1130
+ disableNativeExternalSass: hasCustomJsSass,
952
1131
  ...(isTestMode
953
1132
  ? {
954
1133
  supportTestBed: options.supportTestBed ?? true,
955
1134
  supportJitMode: options.supportJitMode ?? true,
956
1135
  }
957
1136
  : isProdOptimized
958
- ? {
959
- supportTestBed: options.supportTestBed ?? false,
960
- supportJitMode: options.supportJitMode ?? Boolean(options.jit),
961
- }
962
- : {}),
1137
+ ? {
1138
+ supportTestBed: options.supportTestBed ?? false,
1139
+ supportJitMode: options.supportJitMode ?? Boolean(options.jit),
1140
+ }
1141
+ : {}),
963
1142
  });
964
1143
 
965
1144
  const allResources = compiler.getAllResources();
@@ -968,10 +1147,52 @@ export function angularCompilerPlugin(options = {}) {
968
1147
  recordSnapshot(res);
969
1148
  }
970
1149
  }
971
- const sassOverrides = await preprocessComponentStyles(allResources);
972
- if (sassOverrides.length > 0) {
973
- compiler.setResourceOverrides(sassOverrides);
974
- compiler.rebuild(sassOverrides.map((o) => o.path));
1150
+
1151
+ if (canUseNativeExternalSass) {
1152
+ if (!oneShot || typeof options.onComponentStylesCollected === 'function') {
1153
+ for (const rawRes of allResources) {
1154
+ if (!SASS_FILE_RE.test(rawRes)) continue;
1155
+ const absRes = path.resolve(workspaceRoot, rawRes);
1156
+ const normStylePath = toPosixPath(absRes);
1157
+ const compiledCss = compiler.getCompiledStyleCss(absRes);
1158
+ if (compiledCss !== null && compiledCss !== undefined) {
1159
+ compiledComponentStyleCss.set(normStylePath, compiledCss);
1160
+ }
1161
+ if (!oneShot) {
1162
+ const partials = compiler.getSassPartialsForStyle(absRes) || [];
1163
+ const nextPartials = new Set();
1164
+ for (const loaded of partials) {
1165
+ const normLoaded = toPosixPath(loaded);
1166
+ if (normLoaded !== normStylePath) {
1167
+ nextPartials.add(normLoaded);
1168
+ recordSnapshot(normLoaded);
1169
+ let dependents = partialToComponentStyles.get(normLoaded);
1170
+ if (!dependents) {
1171
+ dependents = new Set();
1172
+ partialToComponentStyles.set(normLoaded, dependents);
1173
+ }
1174
+ dependents.add(normStylePath);
1175
+ }
1176
+ }
1177
+ componentStyleToPartials.set(normStylePath, nextPartials);
1178
+ }
1179
+ }
1180
+ }
1181
+
1182
+ const fallbackScss = compiler.getUncompiledExternalSassFiles();
1183
+ if (fallbackScss.length > 0) {
1184
+ const sassOverrides = await preprocessComponentStyles(fallbackScss);
1185
+ if (sassOverrides.length > 0) {
1186
+ compiler.setResourceOverrides(sassOverrides);
1187
+ compiler.rebuild(sassOverrides.map((o) => o.path));
1188
+ }
1189
+ }
1190
+ } else {
1191
+ const sassOverrides = await preprocessComponentStyles(allResources);
1192
+ if (sassOverrides.length > 0) {
1193
+ compiler.setResourceOverrides(sassOverrides);
1194
+ compiler.rebuild(sassOverrides.map((o) => o.path));
1195
+ }
975
1196
  }
976
1197
 
977
1198
  collectComponentStylesForBudgets();
@@ -999,18 +1220,47 @@ export function angularCompilerPlugin(options = {}) {
999
1220
  }
1000
1221
  },
1001
1222
 
1002
- resolveId(source) {
1003
- if (
1004
- !tsconfigPathMappings.length ||
1005
- !source ||
1006
- source.startsWith('.') ||
1007
- source.startsWith('/') ||
1008
- source.startsWith('\0')
1009
- ) {
1010
- return null;
1011
- }
1012
- return resolveViaTsconfigPaths(source, tsconfigPathMappings);
1013
- },
1223
+ ...(initialSkipResolveId
1224
+ ? {}
1225
+ : {
1226
+ resolveId: {
1227
+ filter: {
1228
+ id: {
1229
+ exclude: /^(?:\.\.?\/|\/|\0)/,
1230
+ },
1231
+ },
1232
+ handler(source) {
1233
+ if (
1234
+ !tsconfigPathMappings.length ||
1235
+ !source ||
1236
+ source.startsWith('.') ||
1237
+ source.startsWith('/') ||
1238
+ source.startsWith('\0')
1239
+ ) {
1240
+ return null;
1241
+ }
1242
+ if (tsconfigResolveCache.has(source)) {
1243
+ return tsconfigResolveCache.get(source);
1244
+ }
1245
+ let mayMatch = tsconfigExactPatterns.has(source);
1246
+ if (!mayMatch) {
1247
+ for (let i = 0; i < tsconfigWildcardPrefixes.length; i++) {
1248
+ if (source.startsWith(tsconfigWildcardPrefixes[i])) {
1249
+ mayMatch = true;
1250
+ break;
1251
+ }
1252
+ }
1253
+ }
1254
+ if (!mayMatch) {
1255
+ tsconfigResolveCache.set(source, null);
1256
+ return null;
1257
+ }
1258
+ const resolved = resolveViaTsconfigPaths(source, tsconfigPathMappings);
1259
+ tsconfigResolveCache.set(source, resolved);
1260
+ return resolved;
1261
+ },
1262
+ },
1263
+ }),
1014
1264
 
1015
1265
  load: {
1016
1266
  filter: {
@@ -1036,78 +1286,76 @@ export function angularCompilerPlugin(options = {}) {
1036
1286
  ) {
1037
1287
  return null;
1038
1288
  }
1039
- const emittedJs = compiler.getEmittedJs(cleanId);
1040
- if (emittedJs === null || emittedJs === undefined) {
1289
+ const out = loadEmittedModuleFromCompiler(compiler, cleanId, enableSourceMap);
1290
+ if (!out) {
1041
1291
  return null;
1042
1292
  }
1043
1293
  servedViaLoad.add(cleanId);
1044
- const out = enableSourceMap
1045
- ? extractInlineSourceMap(emittedJs)
1046
- : { code: emittedJs, map: null };
1047
1294
  return isRolldownVite ? { ...out, moduleType: 'js' } : out;
1048
1295
  },
1049
1296
  },
1050
1297
 
1051
- transform: {
1052
- filter: {
1053
- id: {
1054
- include: TS_FILE_RE,
1055
- exclude: [/\/node_modules\//, DTS_FILE_RE],
1056
- },
1057
- },
1058
- async handler(_code, id) {
1059
- if (!compiler || id.startsWith('\0')) {
1060
- return null;
1061
- }
1062
- const query = getQueryString(id);
1063
- if (query && VITE_SPECIAL_QUERY_RE.test(query)) {
1064
- return null;
1065
- }
1066
- const cleanId = stripQueryAndHash(id);
1067
- if (servedViaLoad.has(cleanId)) {
1068
- return null;
1069
- }
1070
- const posixId = toPosixPath(cleanId);
1071
- if (
1072
- posixId.includes('/node_modules/') ||
1073
- DTS_FILE_RE.test(posixId) ||
1074
- !TS_FILE_RE.test(posixId)
1075
- ) {
1076
- return null;
1077
- }
1298
+ ...(options._skipBuildTransform
1299
+ ? {}
1300
+ : {
1301
+ transform: {
1302
+ filter: {
1303
+ id: {
1304
+ include: TS_FILE_RE,
1305
+ exclude: [/\/node_modules\//, DTS_FILE_RE],
1306
+ },
1307
+ },
1308
+ async handler(_code, id) {
1309
+ if (!compiler || id.startsWith('\0')) {
1310
+ return null;
1311
+ }
1312
+ const query = getQueryString(id);
1313
+ if (query && VITE_SPECIAL_QUERY_RE.test(query)) {
1314
+ return null;
1315
+ }
1316
+ const cleanId = stripQueryAndHash(id);
1317
+ if (servedViaLoad.has(cleanId)) {
1318
+ return null;
1319
+ }
1320
+ const posixId = toPosixPath(cleanId);
1321
+ if (
1322
+ posixId.includes('/node_modules/') ||
1323
+ DTS_FILE_RE.test(posixId) ||
1324
+ !TS_FILE_RE.test(posixId)
1325
+ ) {
1326
+ return null;
1327
+ }
1078
1328
 
1079
- if (resolvedConfig?.command === 'serve') {
1080
- await syncOnDiskChangesForTs(cleanId, null);
1081
- }
1329
+ if (resolvedConfig?.command === 'serve') {
1330
+ await syncOnDiskChangesForTs(cleanId, null);
1331
+ }
1082
1332
 
1083
- const emittedJs = compiler.getEmittedJs(cleanId);
1084
- if (emittedJs === null || emittedJs === undefined) {
1085
- return null;
1086
- }
1333
+ const modOut = loadEmittedModuleFromCompiler(compiler, cleanId, enableSourceMap);
1334
+ if (!modOut) {
1335
+ return null;
1336
+ }
1087
1337
 
1088
- if (!isOneShotBuild()) {
1089
- recordSnapshot(cleanId);
1090
- const resourceDeps = compiler.getResourceDependencies(cleanId);
1091
- for (const dep of resourceDeps) {
1092
- recordSnapshot(dep);
1093
- this.addWatchFile(dep);
1094
- const normDep = toPosixPath(path.resolve(workspaceRoot, dep));
1095
- const partials = componentStyleToPartials.get(normDep);
1096
- if (partials) {
1097
- for (const partialPath of partials) {
1098
- recordSnapshot(partialPath);
1099
- this.addWatchFile(partialPath);
1338
+ if (!isOneShotBuild()) {
1339
+ recordSnapshot(cleanId);
1340
+ const resourceDeps = compiler.getResourceDependencies(cleanId);
1341
+ for (const dep of resourceDeps) {
1342
+ recordSnapshot(dep);
1343
+ this.addWatchFile(dep);
1344
+ const normDep = toPosixPath(path.resolve(workspaceRoot, dep));
1345
+ const partials = componentStyleToPartials.get(normDep);
1346
+ if (partials) {
1347
+ for (const partialPath of partials) {
1348
+ recordSnapshot(partialPath);
1349
+ this.addWatchFile(partialPath);
1350
+ }
1351
+ }
1352
+ }
1100
1353
  }
1101
- }
1102
- }
1103
- }
1104
1354
 
1105
- if (enableSourceMap) {
1106
- return extractInlineSourceMap(emittedJs);
1107
- }
1108
- return { code: emittedJs, map: null };
1109
- },
1110
- },
1355
+ return modOut;
1356
+ },
1357
+ },
1358
+ }),
1111
1359
 
1112
1360
  async handleHotUpdate(ctx) {
1113
1361
  if (!compiler) {
@@ -1137,7 +1385,16 @@ export function angularCompilerPlugin(options = {}) {
1137
1385
  if (directOwners.length > 0) {
1138
1386
  affectedStylePaths.add(normFile);
1139
1387
  }
1140
- const dependentStyles = partialToComponentStyles.get(normFile);
1388
+ let dependentStyles = partialToComponentStyles.get(normFile);
1389
+ if (!dependentStyles) {
1390
+ try {
1391
+ dependentStyles = partialToComponentStyles.get(
1392
+ toPosixPath(fs.realpathSync(cleanFile)),
1393
+ );
1394
+ } catch {
1395
+ // Ignore missing realpath
1396
+ }
1397
+ }
1141
1398
  if (dependentStyles) {
1142
1399
  for (const depStyle of dependentStyles) {
1143
1400
  affectedStylePaths.add(depStyle);
@@ -1245,6 +1502,9 @@ export function angularCompilerPlugin(options = {}) {
1245
1502
  }
1246
1503
 
1247
1504
  // 2. Handle .ts / fileReplacements / tsconfig.json changes
1505
+ if (isTsconfigChange) {
1506
+ refreshTsconfigMappings(tsconfigPath);
1507
+ }
1248
1508
  const tsRebuildStart = performance.now();
1249
1509
  compiler.rebuild([cleanFile]);
1250
1510
  recordSnapshot(cleanFile);
@@ -1312,6 +1572,10 @@ export function angularCompilerPlugin(options = {}) {
1312
1572
  export function angularLinkerPlugin(options = {}) {
1313
1573
  let resolvedConfig;
1314
1574
  let sourceMapping = true;
1575
+ let linkerCacheDir = '';
1576
+ let linkerCacheDirExists = false;
1577
+ /** @type {Array<{ key: string, entry: { code: string, sourceMap: string | null }, sourceMapping: boolean }>} */
1578
+ let pendingLinkerCacheWrites = [];
1315
1579
  const linkerJitMode = options.jit ?? false;
1316
1580
  const unknownDeclarationVersionHandling =
1317
1581
  options.unknownDeclarationVersionHandling ?? 'error';
@@ -1367,11 +1631,26 @@ export function angularLinkerPlugin(options = {}) {
1367
1631
  sourceMapping =
1368
1632
  options.sourceMap ??
1369
1633
  (config.command === 'serve' ? true : Boolean(config.build?.sourcemap));
1634
+ const rootDir = path.resolve(options.workspaceRoot || config.root || process.cwd());
1635
+ linkerCacheDir =
1636
+ options.linkerCache === false
1637
+ ? ''
1638
+ : path.join(rootDir, '.angular', 'cache', 'ngrs-linker');
1639
+ linkerCacheDirExists = Boolean(linkerCacheDir && fs.existsSync(linkerCacheDir));
1640
+ },
1641
+
1642
+ buildStart() {
1643
+ linkerCacheDirExists = Boolean(linkerCacheDir && fs.existsSync(linkerCacheDir));
1370
1644
  },
1371
1645
 
1372
1646
  transform: {
1373
1647
  filter: {
1374
1648
  id: /\.[cm]?js(?:$|\?)/,
1649
+ ...(isRolldownVite
1650
+ ? {
1651
+ code: /(?:ngDeclare|setClassMetadata|setClassDebugInfo|static\s+ɵ|InjectionToken|\\u0275)/,
1652
+ }
1653
+ : {}),
1375
1654
  },
1376
1655
  async handler(code, id) {
1377
1656
  if (id.startsWith('\0')) {
@@ -1404,12 +1683,34 @@ export function angularLinkerPlugin(options = {}) {
1404
1683
  return null;
1405
1684
  }
1406
1685
 
1407
- const result = await linkFileAsyncFn(cleanId, code, {
1686
+ const linkOpts = {
1408
1687
  sourceMapping,
1409
1688
  linkerJitMode,
1410
1689
  unknownDeclarationVersionHandling,
1411
1690
  optimizeForBundling,
1412
- });
1691
+ };
1692
+ const cacheKey = isNodeModules ? computeLinkerCacheKey(code, linkOpts) : '';
1693
+ if (cacheKey) {
1694
+ const cached = await readLinkerCache(
1695
+ linkerCacheDir,
1696
+ linkerCacheDirExists,
1697
+ cacheKey,
1698
+ sourceMapping,
1699
+ );
1700
+ if (cached) {
1701
+ let map = null;
1702
+ if (sourceMapping && cached.sourceMap) {
1703
+ try {
1704
+ map = JSON.parse(cached.sourceMap);
1705
+ } catch {
1706
+ map = null;
1707
+ }
1708
+ }
1709
+ return { code: cached.code, map };
1710
+ }
1711
+ }
1712
+
1713
+ const result = await linkFileAsyncFn(cleanId, code, linkOpts);
1413
1714
 
1414
1715
  if (result.diagnostics?.length) {
1415
1716
  const { warnings, errors } = formatDiagnostics(
@@ -1434,6 +1735,21 @@ export function angularLinkerPlugin(options = {}) {
1434
1735
  return null;
1435
1736
  }
1436
1737
 
1738
+ if (cacheKey && (!result.diagnostics || result.diagnostics.length === 0)) {
1739
+ const entry = {
1740
+ code: result.code,
1741
+ sourceMap: sourceMapping ? (result.sourceMap ?? null) : null,
1742
+ };
1743
+ linkerMemoryCache.set(cacheKey, entry);
1744
+ if (linkerCacheDir) {
1745
+ if (resolvedConfig?.command === 'build') {
1746
+ pendingLinkerCacheWrites.push({ key: cacheKey, entry, sourceMapping });
1747
+ } else {
1748
+ flushLinkerCacheWrites(linkerCacheDir, [{ key: cacheKey, entry, sourceMapping }]);
1749
+ }
1750
+ }
1751
+ }
1752
+
1437
1753
  let map = null;
1438
1754
  if (sourceMapping && result.sourceMap) {
1439
1755
  try {
@@ -1449,6 +1765,14 @@ export function angularLinkerPlugin(options = {}) {
1449
1765
  };
1450
1766
  },
1451
1767
  },
1768
+
1769
+ async closeBundle() {
1770
+ if (pendingLinkerCacheWrites.length > 0) {
1771
+ const batch = pendingLinkerCacheWrites;
1772
+ pendingLinkerCacheWrites = [];
1773
+ await flushLinkerCacheWrites(linkerCacheDir, batch);
1774
+ }
1775
+ },
1452
1776
  };
1453
1777
  }
1454
1778
 
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]