@ngrs/vite 0.0.0-stage → 0.1.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/src/index.mjs ADDED
@@ -0,0 +1,1465 @@
1
+ import fs from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import * as viteNamespace from 'vite';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const napi = require('@ngrs/napi');
10
+
11
+ const {
12
+ NapiProjectCompiler,
13
+ needsLinking,
14
+ linkFile,
15
+ linkFileAsync,
16
+ compileSassWithDeps,
17
+ } = napi;
18
+
19
+ const linkFileAsyncFn =
20
+ typeof linkFileAsync === 'function'
21
+ ? linkFileAsync
22
+ : (filePath, source, opts) => Promise.resolve(linkFile(filePath, source, opts));
23
+
24
+ /**
25
+ * True when running under Vite 8+ powered by native Rust Rolldown (`'rolldownVersion' in vite`).
26
+ */
27
+ export const isRolldownVite =
28
+ 'rolldownVersion' in viteNamespace && Boolean(viteNamespace.rolldownVersion);
29
+
30
+ const INLINE_SOURCEMAP_RE =
31
+ /\n?\/\/# sourceMappingURL=data:application\/json;(?:charset=utf-8;)?base64,([A-Za-z0-9+/=]+)\s*$/;
32
+ const TS_FILE_RE = /\.[cm]?tsx?$/;
33
+ const DTS_FILE_RE = /\.d\.[cm]?ts$/;
34
+ const JS_MODULE_RE = /\.[cm]?js$/;
35
+ const RESOURCE_FILE_RE = /\.(?:html?|svg|css|scss|sass|less)$/i;
36
+ const SASS_FILE_RE = /\.(?:scss|sass)$/i;
37
+ const VITE_SPECIAL_QUERY_RE = /(?:^|&)(?:raw|url|worker|sharedworker|inline|commonjs-proxy)(?:&|=|$)/;
38
+ const ANGULAR_HMR_COMPONENT_PATH = '/@ng/component';
39
+
40
+ function stripQueryAndHash(id) {
41
+ const qIdx = id.indexOf('?');
42
+ const withoutQuery = qIdx === -1 ? id : id.slice(0, qIdx);
43
+ const hIdx = withoutQuery.indexOf('#');
44
+ return hIdx === -1 ? withoutQuery : withoutQuery.slice(0, hIdx);
45
+ }
46
+
47
+ function getQueryString(id) {
48
+ const qIdx = id.indexOf('?');
49
+ return qIdx === -1 ? '' : id.slice(qIdx + 1);
50
+ }
51
+
52
+ function toPosixPath(p) {
53
+ return p.replace(/\\/g, '/');
54
+ }
55
+
56
+ function resolveDefaultTsconfig(rootDir, explicitTsconfig, isTestMode = false) {
57
+ if (explicitTsconfig) {
58
+ return path.resolve(rootDir, explicitTsconfig);
59
+ }
60
+ if (isTestMode) {
61
+ const specTsconfig = path.resolve(rootDir, 'tsconfig.spec.json');
62
+ if (fs.existsSync(specTsconfig)) {
63
+ return specTsconfig;
64
+ }
65
+ }
66
+ const appTsconfig = path.resolve(rootDir, 'tsconfig.app.json');
67
+ if (fs.existsSync(appTsconfig)) {
68
+ return appTsconfig;
69
+ }
70
+ return path.resolve(rootDir, 'tsconfig.json');
71
+ }
72
+
73
+ function stripJsoncSimple(text) {
74
+ return text
75
+ .replace(/\/\*[\s\S]*?\*\//g, '')
76
+ .replace(/^\s*\/\/.*$/gm, '')
77
+ .replace(/,(\s*[}\]])/g, '$1');
78
+ }
79
+
80
+ function loadTsconfigPathMappings(tsconfigFile, visited = new Set()) {
81
+ const absFile = path.resolve(tsconfigFile);
82
+ if (visited.has(absFile) || !fs.existsSync(absFile)) {
83
+ return [];
84
+ }
85
+ visited.add(absFile);
86
+
87
+ let parsed;
88
+ try {
89
+ parsed = JSON.parse(stripJsoncSimple(fs.readFileSync(absFile, 'utf8')));
90
+ } catch {
91
+ return [];
92
+ }
93
+
94
+ const configDir = path.dirname(absFile);
95
+ let inherited = [];
96
+ if (parsed?.extends) {
97
+ const extList = Array.isArray(parsed.extends) ? parsed.extends : [parsed.extends];
98
+ for (const ext of extList) {
99
+ if (typeof ext !== 'string') continue;
100
+ const extCand = ext.endsWith('.json')
101
+ ? path.resolve(configDir, ext)
102
+ : path.resolve(configDir, `${ext}.json`);
103
+ inherited = [...inherited, ...loadTsconfigPathMappings(extCand, visited)];
104
+ }
105
+ }
106
+
107
+ const opts = parsed?.compilerOptions || {};
108
+ const rawPaths = opts.paths;
109
+ if (!rawPaths || typeof rawPaths !== 'object') {
110
+ return inherited;
111
+ }
112
+
113
+ const baseDir = opts.baseUrl ? path.resolve(configDir, opts.baseUrl) : configDir;
114
+ const own = [];
115
+ for (const [pattern, targets] of Object.entries(rawPaths)) {
116
+ if (!Array.isArray(targets) || targets.length === 0) continue;
117
+ const starIdx = pattern.indexOf('*');
118
+ own.push({
119
+ pattern,
120
+ hasWildcard: starIdx !== -1,
121
+ prefix: starIdx === -1 ? pattern : pattern.slice(0, starIdx),
122
+ suffix: starIdx === -1 ? '' : pattern.slice(starIdx + 1),
123
+ targets: targets
124
+ .filter((t) => typeof t === 'string')
125
+ .map((t) => path.resolve(baseDir, t)),
126
+ });
127
+ }
128
+
129
+ return [...own, ...inherited];
130
+ }
131
+
132
+ function resolveCandidateModuleTarget(absCandidate) {
133
+ const fileExts = ['', '.ts', '.tsx', '.mts', '.mjs', '.js'];
134
+ for (const ext of fileExts) {
135
+ const withExt = ext ? `${absCandidate}${ext}` : absCandidate;
136
+ if (fs.existsSync(withExt) && fs.statSync(withExt).isFile()) {
137
+ return toPosixPath(withExt);
138
+ }
139
+ }
140
+
141
+ if (fs.existsSync(absCandidate) && fs.statSync(absCandidate).isDirectory()) {
142
+ const pkgJsonPath = path.join(absCandidate, 'package.json');
143
+ if (fs.existsSync(pkgJsonPath)) {
144
+ try {
145
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
146
+ const entryRel =
147
+ pkg?.exports?.['.']?.es2022 ||
148
+ pkg?.exports?.['.']?.esm2022 ||
149
+ pkg?.exports?.['.']?.import ||
150
+ pkg?.exports?.['.']?.default ||
151
+ pkg?.fesm2022 ||
152
+ pkg?.es2022 ||
153
+ pkg?.module ||
154
+ pkg?.main;
155
+ if (typeof entryRel === 'string') {
156
+ const resolvedPkgEntry = path.resolve(absCandidate, entryRel);
157
+ if (fs.existsSync(resolvedPkgEntry)) {
158
+ return toPosixPath(resolvedPkgEntry);
159
+ }
160
+ }
161
+ } catch {
162
+ // Fall through to index lookup
163
+ }
164
+ }
165
+ for (const idx of ['index.ts', 'index.mts', 'index.mjs', 'index.js', 'src/index.ts']) {
166
+ const candIdx = path.join(absCandidate, idx);
167
+ if (fs.existsSync(candIdx) && fs.statSync(candIdx).isFile()) {
168
+ return toPosixPath(candIdx);
169
+ }
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+
175
+ function resolveViaTsconfigPaths(source, mappings) {
176
+ for (const entry of mappings) {
177
+ if (!entry.hasWildcard) {
178
+ if (source !== entry.pattern) continue;
179
+ for (const targetAbs of entry.targets) {
180
+ const hit = resolveCandidateModuleTarget(targetAbs);
181
+ if (hit) return hit;
182
+ }
183
+ } else if (
184
+ source.startsWith(entry.prefix) &&
185
+ source.endsWith(entry.suffix) &&
186
+ source.length >= entry.prefix.length + entry.suffix.length
187
+ ) {
188
+ const matchedWildcard = source.slice(
189
+ entry.prefix.length,
190
+ source.length - entry.suffix.length,
191
+ );
192
+ for (const targetPattern of entry.targets) {
193
+ const substituted = targetPattern.replace('*', matchedWildcard);
194
+ const hit = resolveCandidateModuleTarget(substituted);
195
+ if (hit) return hit;
196
+ }
197
+ }
198
+ }
199
+ return null;
200
+ }
201
+
202
+ function extractInlineSourceMap(jsCode) {
203
+ const match = INLINE_SOURCEMAP_RE.exec(jsCode);
204
+ if (!match) {
205
+ return { code: jsCode, map: null };
206
+ }
207
+ const stripped = jsCode.slice(0, match.index) + '\n';
208
+ try {
209
+ const decoded = Buffer.from(match[1], 'base64').toString('utf8');
210
+ return { code: stripped, map: JSON.parse(decoded) };
211
+ } catch {
212
+ return { code: jsCode, map: null };
213
+ }
214
+ }
215
+
216
+ let cachedSassModule;
217
+ async function loadSassPreprocessor(fromRoot) {
218
+ if (cachedSassModule !== undefined) {
219
+ return cachedSassModule;
220
+ }
221
+ const candidates = [
222
+ () => import('sass'),
223
+ () => {
224
+ const rootReq = createRequire(path.join(fromRoot, 'package.json'));
225
+ return Promise.resolve(rootReq('sass'));
226
+ },
227
+ ];
228
+ for (const loader of candidates) {
229
+ try {
230
+ const mod = await loader();
231
+ cachedSassModule = typeof mod?.compile === 'function' ? mod : (mod?.default ?? mod);
232
+ return cachedSassModule;
233
+ } catch {
234
+ // Try next candidate
235
+ }
236
+ }
237
+ cachedSassModule = null;
238
+ return null;
239
+ }
240
+
241
+ async function compileSassResource(filePath, includePaths, sassOptions, workspaceRoot) {
242
+ const hasJsSassCallbacks =
243
+ sassOptions &&
244
+ (sassOptions.functions !== undefined || sassOptions.importers !== undefined);
245
+
246
+ let nativeError = null;
247
+ if (!hasJsSassCallbacks && typeof compileSassWithDeps === 'function') {
248
+ try {
249
+ const nativeRes = compileSassWithDeps(filePath, includePaths, false);
250
+ return {
251
+ css: nativeRes.css,
252
+ loadedFiles: (nativeRes.loadedFiles || []).map((p) => toPosixPath(p)),
253
+ };
254
+ } catch (err) {
255
+ nativeError = err;
256
+ }
257
+ }
258
+
259
+ const sass = await loadSassPreprocessor(workspaceRoot);
260
+ if (!sass) {
261
+ if (nativeError) {
262
+ throw nativeError;
263
+ }
264
+ throw new Error(
265
+ `Component stylesheet "${filePath}" uses Sass/SCSS, but compilation failed and the "sass" package is not installed.`,
266
+ );
267
+ }
268
+ const isIndented = filePath.toLowerCase().endsWith('.sass');
269
+ const result = sass.compile(filePath, {
270
+ loadPaths: includePaths,
271
+ syntax: isIndented ? 'indented' : 'scss',
272
+ style: 'expanded',
273
+ ...(sassOptions || {}),
274
+ });
275
+
276
+ const loadedFiles = [];
277
+ if (Array.isArray(result.loadedUrls)) {
278
+ for (const u of result.loadedUrls) {
279
+ if (u && u.protocol === 'file:') {
280
+ try {
281
+ loadedFiles.push(toPosixPath(fileURLToPath(u)));
282
+ } catch {
283
+ // Ignore non-file URLs
284
+ }
285
+ }
286
+ }
287
+ }
288
+
289
+ return {
290
+ css: result.css,
291
+ loadedFiles,
292
+ };
293
+ }
294
+
295
+ /**
296
+ * Formats an array of `@ngrs/napi` diagnostics into human-readable compiler messages.
297
+ *
298
+ * @param {import('@ngrs/napi').NapiDiagnostic[]} diagnostics
299
+ * @param {string} [rootDir]
300
+ * @returns {{ warnings: string[], errors: string[], firstError?: import('@ngrs/napi').NapiDiagnostic }}
301
+ */
302
+ export function formatDiagnostics(diagnostics, rootDir = process.cwd()) {
303
+ const warnings = [];
304
+ const errors = [];
305
+ let firstError;
306
+
307
+ for (const diag of diagnostics || []) {
308
+ // Ignore TypeScript 6 config deprecation diagnostics (`baseUrl` TS5101 / TS5107) on standard
309
+ // Angular & Nx `tsconfig.base.json` files authored for TypeScript 5.x.
310
+ if (diag.code === 5101 || diag.code === 5107) {
311
+ continue;
312
+ }
313
+ const codePrefix =
314
+ diag.code < 0 ? `NG${Math.abs(diag.code)}` : diag.code > 0 ? `TS${diag.code}` : 'NGRS';
315
+ let location = '';
316
+ if (diag.file) {
317
+ const rel = path.isAbsolute(diag.file) ? path.relative(rootDir, diag.file) : diag.file;
318
+ const displayFile = rel.startsWith('..') ? diag.file : rel;
319
+ if (diag.line && diag.column) {
320
+ location = `${toPosixPath(displayFile)}:${diag.line}:${diag.column} - `;
321
+ } else {
322
+ location = `${toPosixPath(displayFile)} - `;
323
+ }
324
+ }
325
+ const formatted = `${location}${diag.category} ${codePrefix}: ${diag.message}`;
326
+ if (diag.category === 'error') {
327
+ errors.push(formatted);
328
+ if (!firstError) {
329
+ firstError = diag;
330
+ }
331
+ } else {
332
+ warnings.push(formatted);
333
+ }
334
+ }
335
+
336
+ return { warnings, errors, firstError };
337
+ }
338
+
339
+ /**
340
+ * Creates a native Rolldown plugin for Vite 8+ `optimizeDeps.rolldownOptions.plugins` that runs
341
+ * the native Rust Angular Ivy Linker (`@ngrs/napi` `needsLinking` + `linkFile`) on partially
342
+ * compiled Angular packages inside `node_modules`.
343
+ *
344
+ * @param {import('./index.js').AngularLinkerOptions} [options]
345
+ */
346
+ export function createRolldownLinkerPlugin(options = {}) {
347
+ const sourceMapping = options.sourceMapping ?? false;
348
+ const linkerJitMode = options.linkerJitMode ?? false;
349
+ const unknownDeclarationVersionHandling =
350
+ options.unknownDeclarationVersionHandling ?? 'ignore';
351
+
352
+ return {
353
+ name: 'ngrs:rolldown-ivy-linker',
354
+ transform(code, id) {
355
+ if (!id || id.startsWith('\0')) {
356
+ return null;
357
+ }
358
+ const cleanId = stripQueryAndHash(id);
359
+ const normalizedPath = toPosixPath(cleanId);
360
+ if (!JS_MODULE_RE.test(normalizedPath)) {
361
+ return null;
362
+ }
363
+ if (!needsLinking(cleanId, code) && !code.includes('\\u0275')) {
364
+ return null;
365
+ }
366
+ const linked = linkFile(cleanId, code, {
367
+ sourceMapping,
368
+ linkerJitMode,
369
+ unknownDeclarationVersionHandling,
370
+ });
371
+ if (!linked.linked) {
372
+ return null;
373
+ }
374
+ let map = null;
375
+ if (sourceMapping && linked.sourceMap) {
376
+ try {
377
+ map = JSON.parse(linked.sourceMap);
378
+ } catch {
379
+ map = null;
380
+ }
381
+ }
382
+ return {
383
+ code: linked.code,
384
+ map,
385
+ };
386
+ },
387
+ };
388
+ }
389
+
390
+ /**
391
+ * Creates a legacy esbuild plugin for Vite 6/7 `optimizeDeps.esbuildOptions.plugins` fallback that
392
+ * runs the native Rust Angular Ivy Linker (`@ngrs/napi` `needsLinking` + `linkFile`) on partially
393
+ * compiled Angular packages inside `node_modules`.
394
+ *
395
+ * @param {import('./index.js').AngularLinkerOptions} [options]
396
+ */
397
+ export function createEsbuildLinkerPlugin(options = {}) {
398
+ const sourceMapping = options.sourceMapping ?? false;
399
+ const linkerJitMode = options.linkerJitMode ?? false;
400
+ const unknownDeclarationVersionHandling =
401
+ options.unknownDeclarationVersionHandling ?? 'ignore';
402
+
403
+ return {
404
+ name: 'ngrs-esbuild-ivy-linker',
405
+ setup(build) {
406
+ build.onLoad({ filter: /\.[cm]?js$/ }, async (args) => {
407
+ const normalizedPath = toPosixPath(args.path);
408
+ if (!normalizedPath.includes('/node_modules/')) {
409
+ return undefined;
410
+ }
411
+ let source;
412
+ try {
413
+ source = await readFile(args.path, 'utf8');
414
+ } catch {
415
+ return undefined;
416
+ }
417
+ if (!needsLinking(args.path, source) && !source.includes('\\u0275')) {
418
+ return undefined;
419
+ }
420
+ const linked = linkFile(args.path, source, {
421
+ sourceMapping,
422
+ linkerJitMode,
423
+ unknownDeclarationVersionHandling,
424
+ });
425
+ if (!linked.linked) {
426
+ return undefined;
427
+ }
428
+ let contents = linked.code;
429
+ if (sourceMapping && linked.sourceMap) {
430
+ const b64 = Buffer.from(linked.sourceMap, 'utf8').toString('base64');
431
+ contents += `\n//# sourceMappingURL=data:application/json;base64,${b64}\n`;
432
+ }
433
+ return {
434
+ contents,
435
+ loader: 'js',
436
+ };
437
+ });
438
+ },
439
+ };
440
+ }
441
+
442
+ /**
443
+ * Plugin 1: `ngrs:angular-compiler`
444
+ *
445
+ * Stateful incremental Angular TypeScript + Ivy template/style compiler backed by
446
+ * `NapiProjectCompiler` (`@ngrs/napi`).
447
+ *
448
+ * @param {import('./index.js').AngularVitePluginOptions} [options]
449
+ * @returns {import('vite').Plugin}
450
+ */
451
+ export function angularCompilerPlugin(options = {}) {
452
+ let resolvedConfig;
453
+ let workspaceRoot = options.workspaceRoot ? path.resolve(options.workspaceRoot) : process.cwd();
454
+ let tsconfigPath = '';
455
+ let compiler = null;
456
+ let enableHmr = true;
457
+ let enableSourceMap = true;
458
+ let includePaths = [];
459
+ let normalizedReplacements = [];
460
+ let tsconfigPathMappings = [];
461
+
462
+ /** @type {Map<string, Set<string>>} partialPath -> Set<componentScssPath> */
463
+ const partialToComponentStyles = new Map();
464
+ /** @type {Map<string, Set<string>>} componentScssPath -> Set<partialPath> */
465
+ const componentStyleToPartials = new Map();
466
+ /** @type {Map<string, string>} componentStylePath -> compiled CSS text */
467
+ const compiledComponentStyleCss = new Map();
468
+ /** @type {Map<string, string>} encodedHmrId -> active HMR update ESM module */
469
+ const activeHmrUpdates = new Map();
470
+ /** @type {Map<string, string>} normalizedAbsFilePath -> last compiled disk contents */
471
+ const fileContentSnapshots = new Map();
472
+
473
+ /** @type {Set<string>} clean paths already served via `load` during one-shot build */
474
+ const servedViaLoad = new Set();
475
+ let pendingDeferredTypecheck = false;
476
+
477
+ function isOneShotBuild() {
478
+ return resolvedConfig?.command === 'build' && !resolvedConfig?.build?.watch;
479
+ }
480
+
481
+ function readDiskTextSafe(absPath) {
482
+ try {
483
+ return fs.readFileSync(absPath, 'utf8');
484
+ } catch {
485
+ return null;
486
+ }
487
+ }
488
+
489
+ function recordSnapshot(absPath) {
490
+ const norm = toPosixPath(path.resolve(workspaceRoot, absPath));
491
+ const text = readDiskTextSafe(norm);
492
+ if (text !== null) {
493
+ fileContentSnapshots.set(norm, text);
494
+ }
495
+ }
496
+
497
+ function collectChangedDepsOnDisk(tsAbsPath) {
498
+ if (!compiler) {
499
+ return { changedTs: false, changedResources: [] };
500
+ }
501
+ const normTs = toPosixPath(path.resolve(workspaceRoot, tsAbsPath));
502
+ let changedTs = false;
503
+ if (fileContentSnapshots.has(normTs)) {
504
+ const curTs = readDiskTextSafe(normTs);
505
+ if (curTs !== null && curTs !== fileContentSnapshots.get(normTs)) {
506
+ changedTs = true;
507
+ }
508
+ }
509
+
510
+ const changedResources = [];
511
+ const deps = compiler.getResourceDependencies(tsAbsPath) || [];
512
+ for (const dep of deps) {
513
+ const normDep = toPosixPath(path.resolve(workspaceRoot, dep));
514
+ const curDep = readDiskTextSafe(normDep);
515
+ if (
516
+ curDep !== null &&
517
+ fileContentSnapshots.has(normDep) &&
518
+ curDep !== fileContentSnapshots.get(normDep)
519
+ ) {
520
+ changedResources.push(normDep);
521
+ continue;
522
+ }
523
+ const partials = componentStyleToPartials.get(normDep);
524
+ if (partials) {
525
+ for (const p of partials) {
526
+ const curP = readDiskTextSafe(p);
527
+ if (curP !== null && fileContentSnapshots.has(p) && curP !== fileContentSnapshots.get(p)) {
528
+ changedResources.push(normDep);
529
+ break;
530
+ }
531
+ }
532
+ }
533
+ }
534
+ return { changedTs, changedResources };
535
+ }
536
+
537
+ async function syncOnDiskChangesForTs(tsAbsPath, server) {
538
+ const { changedTs, changedResources } = collectChangedDepsOnDisk(tsAbsPath);
539
+ if (!changedTs && changedResources.length === 0) {
540
+ return false;
541
+ }
542
+
543
+ const scssTargets = changedResources.filter((r) => SASS_FILE_RE.test(r));
544
+ if (scssTargets.length > 0) {
545
+ const overrides = await preprocessComponentStyles(scssTargets);
546
+ if (overrides.length > 0) {
547
+ compiler.setResourceOverrides(overrides);
548
+ }
549
+ }
550
+
551
+ const rebuildTargets = [...(changedTs ? [tsAbsPath] : []), ...changedResources];
552
+ const rebuildResult = compiler.rebuild(rebuildTargets);
553
+ surfaceDiagnostics(rebuildResult.diagnostics, null, server);
554
+
555
+ recordSnapshot(tsAbsPath);
556
+ for (const r of changedResources) {
557
+ recordSnapshot(r);
558
+ const partials = componentStyleToPartials.get(r);
559
+ if (partials) {
560
+ for (const p of partials) {
561
+ recordSnapshot(p);
562
+ }
563
+ }
564
+ }
565
+
566
+ for (const hmrId of compiler.getHmrIdsForFile(tsAbsPath)) {
567
+ const updateCode = compiler.getHmrUpdateModule(hmrId);
568
+ if (updateCode) {
569
+ activeHmrUpdates.set(hmrId, updateCode);
570
+ }
571
+ }
572
+
573
+ if (server) {
574
+ invalidateOwnerModules(server, [tsAbsPath]);
575
+ }
576
+ return true;
577
+ }
578
+
579
+ function resolveIncludePaths(rootDir) {
580
+ const rawPaths = options.stylePreprocessorOptions?.includePaths || [];
581
+ return rawPaths.map((p) => path.resolve(rootDir, p));
582
+ }
583
+
584
+ function resolveFileReplacements(rootDir) {
585
+ return (options.fileReplacements || []).map((entry) => ({
586
+ replace: path.resolve(rootDir, entry.replace),
587
+ with: path.resolve(rootDir, entry.with),
588
+ }));
589
+ }
590
+
591
+ async function preprocessComponentStyles(stylePaths) {
592
+ const scssPaths = stylePaths.filter((p) => SASS_FILE_RE.test(p));
593
+ if (scssPaths.length === 0) {
594
+ return [];
595
+ }
596
+
597
+ const overrides = [];
598
+ for (const rawStylePath of scssPaths) {
599
+ const absStylePath = path.resolve(workspaceRoot, rawStylePath);
600
+ if (!fs.existsSync(absStylePath)) {
601
+ continue;
602
+ }
603
+ const normStylePath = toPosixPath(absStylePath);
604
+
605
+ // Clear previous partial reverse-edges for this component stylesheet
606
+ const prevPartials = componentStyleToPartials.get(normStylePath);
607
+ if (prevPartials) {
608
+ for (const p of prevPartials) {
609
+ partialToComponentStyles.get(p)?.delete(normStylePath);
610
+ }
611
+ }
612
+
613
+ const { css, loadedFiles } = await compileSassResource(
614
+ absStylePath,
615
+ includePaths,
616
+ options.stylePreprocessorOptions?.sass,
617
+ workspaceRoot,
618
+ );
619
+
620
+ const nextPartials = new Set();
621
+ for (const loaded of loadedFiles) {
622
+ if (loaded !== normStylePath) {
623
+ nextPartials.add(loaded);
624
+ recordSnapshot(loaded);
625
+ let dependents = partialToComponentStyles.get(loaded);
626
+ if (!dependents) {
627
+ dependents = new Set();
628
+ partialToComponentStyles.set(loaded, dependents);
629
+ }
630
+ dependents.add(normStylePath);
631
+ }
632
+ }
633
+ componentStyleToPartials.set(normStylePath, nextPartials);
634
+ compiledComponentStyleCss.set(normStylePath, css);
635
+ recordSnapshot(normStylePath);
636
+ overrides.push({ path: absStylePath, content: css });
637
+ }
638
+
639
+ return overrides;
640
+ }
641
+
642
+ function collectComponentStylesForBudgets() {
643
+ if (typeof options.onComponentStylesCollected !== 'function' || !compiler) {
644
+ return;
645
+ }
646
+ const collected = [];
647
+ for (const resPath of compiler.getAllResources()) {
648
+ if (!/\.(?:css|scss|sass|less)$/i.test(resPath)) {
649
+ continue;
650
+ }
651
+ const norm = toPosixPath(path.resolve(workspaceRoot, resPath));
652
+ let cssText = compiledComponentStyleCss.get(norm);
653
+ if (cssText === undefined) {
654
+ try {
655
+ cssText = fs.readFileSync(norm, 'utf8');
656
+ } catch {
657
+ cssText = '';
658
+ }
659
+ }
660
+ collected.push({
661
+ file: norm,
662
+ css: cssText,
663
+ size: Buffer.byteLength(cssText, 'utf8'),
664
+ });
665
+ }
666
+ options.onComponentStylesCollected(collected);
667
+ }
668
+
669
+ function surfaceDiagnostics(diagnostics, pluginContext, viteServer) {
670
+ options.onDiagnostics?.(diagnostics);
671
+ const { warnings, errors, firstError } = formatDiagnostics(diagnostics, workspaceRoot);
672
+ const logger = resolvedConfig?.logger ?? console;
673
+ const suppressLog = Boolean(options.suppressViteDiagnosticsLog);
674
+
675
+ if (!suppressLog) {
676
+ for (const warn of warnings) {
677
+ logger.warn(warn);
678
+ }
679
+ }
680
+
681
+ if (errors.length > 0) {
682
+ const combined = errors.join('\n');
683
+ if (resolvedConfig?.command === 'build' && !options.ignoreDiagnostics && pluginContext) {
684
+ pluginContext.error({
685
+ message: combined,
686
+ id: firstError?.file,
687
+ loc:
688
+ firstError?.file && firstError?.line
689
+ ? {
690
+ file: firstError.file,
691
+ line: firstError.line,
692
+ column: firstError.column ?? 1,
693
+ }
694
+ : undefined,
695
+ });
696
+ } else {
697
+ if (!suppressLog) {
698
+ logger.error(combined);
699
+ }
700
+ if (viteServer?.ws) {
701
+ viteServer.ws.send({
702
+ type: 'error',
703
+ err: {
704
+ message: combined,
705
+ stack: '',
706
+ id: firstError?.file,
707
+ loc:
708
+ firstError?.file && firstError?.line
709
+ ? {
710
+ file: firstError.file,
711
+ line: firstError.line,
712
+ column: firstError.column ?? 1,
713
+ }
714
+ : undefined,
715
+ plugin: 'ngrs:angular-compiler',
716
+ },
717
+ });
718
+ }
719
+ }
720
+ }
721
+ }
722
+
723
+ function invalidateOwnerModules(server, ownerFiles) {
724
+ const invalidated = [];
725
+ const seen = new Set();
726
+
727
+ // Invalidate across both Vite's top-level moduleGraph and Vite 8 per-environment moduleGraphs
728
+ const graphs = [];
729
+ if (server?.moduleGraph) {
730
+ graphs.push(server.moduleGraph);
731
+ }
732
+ if (server?.environments && typeof server.environments === 'object') {
733
+ for (const env of Object.values(server.environments)) {
734
+ if (env?.moduleGraph && !graphs.includes(env.moduleGraph)) {
735
+ graphs.push(env.moduleGraph);
736
+ }
737
+ }
738
+ }
739
+
740
+ for (const owner of ownerFiles) {
741
+ const candidates = [owner, toPosixPath(owner)];
742
+ try {
743
+ candidates.push(toPosixPath(fs.realpathSync(owner)));
744
+ } catch {
745
+ // Ignore missing realpath
746
+ }
747
+ for (const graph of graphs) {
748
+ for (const cand of candidates) {
749
+ const mods = graph.getModulesByFile(cand);
750
+ if (!mods) continue;
751
+ for (const mod of mods) {
752
+ if (!seen.has(mod)) {
753
+ seen.add(mod);
754
+ graph.invalidateModule(mod);
755
+ if (graph === server.moduleGraph) {
756
+ invalidated.push(mod);
757
+ }
758
+ }
759
+ }
760
+ }
761
+ }
762
+ }
763
+ return invalidated;
764
+ }
765
+
766
+ function resolveRequestToProjectTsFile(rawUrl) {
767
+ const parsed = new URL(rawUrl, 'http://localhost');
768
+ let pathname = decodeURIComponent(parsed.pathname);
769
+ const base = resolvedConfig?.base || '/';
770
+ if (base !== '/' && pathname.startsWith(base)) {
771
+ pathname = '/' + pathname.slice(base.length).replace(/^\/+/, '');
772
+ }
773
+ if (pathname.startsWith('/@fs/')) {
774
+ const fsPath = pathname.slice('/@fs'.length);
775
+ return fs.existsSync(fsPath) ? fsPath : fsPath.replace(/^\/([A-Za-z]:\/)/, '$1');
776
+ }
777
+ if (!pathname.startsWith('/') || pathname.startsWith('/@') || pathname.includes('/node_modules/')) {
778
+ return null;
779
+ }
780
+ return path.resolve(workspaceRoot, pathname.slice(1));
781
+ }
782
+
783
+ return {
784
+ name: 'ngrs:angular-compiler',
785
+ enforce: 'pre',
786
+
787
+ config(userConfig, env) {
788
+ const rootDir = path.resolve(
789
+ options.workspaceRoot || userConfig.root || process.cwd(),
790
+ );
791
+ const resolvedIncPaths = resolveIncludePaths(rootDir);
792
+ const resolvedReplacements = resolveFileReplacements(rootDir);
793
+
794
+ /** @type {import('vite').UserConfig} */
795
+ const patch = {};
796
+
797
+ if (resolvedReplacements.length > 0) {
798
+ patch.resolve = {
799
+ alias: resolvedReplacements.map((r) => ({
800
+ find: r.replace,
801
+ replacement: r.with,
802
+ })),
803
+ };
804
+ }
805
+
806
+ if (resolvedIncPaths.length > 0) {
807
+ patch.css = {
808
+ preprocessorOptions: {
809
+ scss: {
810
+ loadPaths: resolvedIncPaths,
811
+ },
812
+ sass: {
813
+ loadPaths: resolvedIncPaths,
814
+ },
815
+ },
816
+ };
817
+ }
818
+
819
+ if (env.command === 'serve') {
820
+ const allowDirs = new Set([rootDir, process.cwd()]);
821
+ for (const d of [...allowDirs]) {
822
+ try {
823
+ allowDirs.add(fs.realpathSync(d));
824
+ } catch {
825
+ // Ignore missing realpath
826
+ }
827
+ }
828
+ patch.server = {
829
+ fs: {
830
+ allow: [...allowDirs],
831
+ },
832
+ };
833
+ }
834
+
835
+ const isVitest = Boolean(
836
+ options.test || process.env.VITEST || env.mode === 'test' || userConfig?.test,
837
+ );
838
+ if (isVitest) {
839
+ patch.test = {
840
+ server: {
841
+ deps: {
842
+ inline: [
843
+ /^(?!vitest(?:\/|$)|@vitest\/|happy-dom(?:\/|$)|playwright(?:\/|$)|@playwright\/).*/,
844
+ ],
845
+ },
846
+ },
847
+ };
848
+ }
849
+
850
+ return patch;
851
+ },
852
+
853
+ configResolved(config) {
854
+ resolvedConfig = config;
855
+ workspaceRoot = path.resolve(options.workspaceRoot || config.root || process.cwd());
856
+ const isTestMode = Boolean(
857
+ options.test || process.env.VITEST || config.mode === 'test' || config.test,
858
+ );
859
+ tsconfigPath = resolveDefaultTsconfig(workspaceRoot, options.tsconfig, isTestMode);
860
+ tsconfigPathMappings = loadTsconfigPathMappings(tsconfigPath);
861
+ includePaths = resolveIncludePaths(workspaceRoot);
862
+ normalizedReplacements = resolveFileReplacements(workspaceRoot);
863
+ enableHmr = isTestMode
864
+ ? false
865
+ : (options.hmr ?? (config.command === 'serve' && config.server?.hmr !== false));
866
+ enableSourceMap =
867
+ options.sourceMap ??
868
+ (config.command === 'serve' || isTestMode ? true : Boolean(config.build?.sourcemap));
869
+ },
870
+
871
+ configureServer(server) {
872
+ // Pre-transform middleware: serves `/@ng/component` HMR updates and ensures immediate
873
+ // incremental rebuild + cache invalidation if a component's `.html`/`.scss`/`.css`/`.ts`
874
+ // was just modified on disk before OS file-watcher events fire.
875
+ server.middlewares.use(async (req, res, next) => {
876
+ if (!req.url || res.writableEnded) {
877
+ next();
878
+ return;
879
+ }
880
+ const parsed = new URL(req.url, 'http://localhost');
881
+ if (parsed.pathname.endsWith(ANGULAR_HMR_COMPONENT_PATH)) {
882
+ const compId = parsed.searchParams.get('c');
883
+ if (!compId) {
884
+ res.statusCode = 400;
885
+ res.end();
886
+ return;
887
+ }
888
+ const encoded = encodeURIComponent(compId);
889
+ const code =
890
+ activeHmrUpdates.get(encoded) ??
891
+ activeHmrUpdates.get(compId) ??
892
+ 'export default null;\n';
893
+ res.statusCode = 200;
894
+ res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
895
+ res.setHeader('Cache-Control', 'no-cache');
896
+ res.end(code);
897
+ return;
898
+ }
899
+
900
+ if (compiler && (req.method === 'GET' || req.method === 'HEAD')) {
901
+ const candidateTs = resolveRequestToProjectTsFile(req.url);
902
+ if (
903
+ candidateTs &&
904
+ TS_FILE_RE.test(candidateTs) &&
905
+ !DTS_FILE_RE.test(candidateTs) &&
906
+ fs.existsSync(candidateTs)
907
+ ) {
908
+ try {
909
+ await syncOnDiskChangesForTs(candidateTs, server);
910
+ } catch (err) {
911
+ next(err);
912
+ return;
913
+ }
914
+ }
915
+ }
916
+
917
+ next();
918
+ });
919
+ },
920
+
921
+ async buildStart() {
922
+ activeHmrUpdates.clear();
923
+ partialToComponentStyles.clear();
924
+ componentStyleToPartials.clear();
925
+ compiledComponentStyleCss.clear();
926
+ fileContentSnapshots.clear();
927
+ servedViaLoad.clear();
928
+ pendingDeferredTypecheck = false;
929
+
930
+ const oneShot = isOneShotBuild();
931
+ const isTestMode = Boolean(
932
+ options.test || process.env.VITEST || resolvedConfig?.mode === 'test' || resolvedConfig?.test,
933
+ );
934
+ const modeName = options.compilationMode ?? 'full';
935
+ const isProdOptimized = oneShot && !isTestMode && resolvedConfig?.define?.ngDevMode === 'false';
936
+ const useDeferredTypecheck =
937
+ oneShot &&
938
+ !isTestMode &&
939
+ modeName !== 'experimental-local' &&
940
+ (options.deferTypecheck ?? true) &&
941
+ typeof NapiProjectCompiler.prototype.finishDeferredTypecheckAsync === 'function';
942
+
943
+ compiler = NapiProjectCompiler.open(tsconfigPath, {
944
+ fileReplacements: normalizedReplacements,
945
+ hmr: enableHmr,
946
+ sourceMap: enableSourceMap,
947
+ compilationMode: modeName,
948
+ emitDts: options.emitDts ?? false,
949
+ deferTypecheck: useDeferredTypecheck,
950
+ inlineStyleLanguage: options.inlineStyleLanguage,
951
+ styleIncludePaths: includePaths,
952
+ ...(isTestMode
953
+ ? {
954
+ supportTestBed: options.supportTestBed ?? true,
955
+ supportJitMode: options.supportJitMode ?? true,
956
+ }
957
+ : isProdOptimized
958
+ ? {
959
+ supportTestBed: options.supportTestBed ?? false,
960
+ supportJitMode: options.supportJitMode ?? Boolean(options.jit),
961
+ }
962
+ : {}),
963
+ });
964
+
965
+ const allResources = compiler.getAllResources();
966
+ if (!oneShot) {
967
+ for (const res of allResources) {
968
+ recordSnapshot(res);
969
+ }
970
+ }
971
+ const sassOverrides = await preprocessComponentStyles(allResources);
972
+ if (sassOverrides.length > 0) {
973
+ compiler.setResourceOverrides(sassOverrides);
974
+ compiler.rebuild(sassOverrides.map((o) => o.path));
975
+ }
976
+
977
+ collectComponentStylesForBudgets();
978
+ if (useDeferredTypecheck) {
979
+ compiler.startDeferredTypecheck();
980
+ pendingDeferredTypecheck = true;
981
+ } else {
982
+ surfaceDiagnostics(compiler.getDiagnostics(), this, null);
983
+ }
984
+ options.onCompilerReady?.(compiler);
985
+ },
986
+
987
+ async generateBundle() {
988
+ if (compiler && pendingDeferredTypecheck) {
989
+ pendingDeferredTypecheck = false;
990
+ const diags = await compiler.finishDeferredTypecheckAsync();
991
+ surfaceDiagnostics(diags, this, null);
992
+ }
993
+ },
994
+
995
+ async buildEnd(err) {
996
+ if (err && compiler && pendingDeferredTypecheck) {
997
+ pendingDeferredTypecheck = false;
998
+ await compiler.finishDeferredTypecheckAsync().catch(() => {});
999
+ }
1000
+ },
1001
+
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
+ },
1014
+
1015
+ load: {
1016
+ filter: {
1017
+ id: {
1018
+ include: TS_FILE_RE,
1019
+ exclude: [/\/node_modules\//, DTS_FILE_RE],
1020
+ },
1021
+ },
1022
+ handler(id) {
1023
+ if (!compiler || !isOneShotBuild() || id.startsWith('\0')) {
1024
+ return null;
1025
+ }
1026
+ const query = getQueryString(id);
1027
+ if (query && VITE_SPECIAL_QUERY_RE.test(query)) {
1028
+ return null;
1029
+ }
1030
+ const cleanId = stripQueryAndHash(id);
1031
+ const posixId = toPosixPath(cleanId);
1032
+ if (
1033
+ posixId.includes('/node_modules/') ||
1034
+ DTS_FILE_RE.test(posixId) ||
1035
+ !TS_FILE_RE.test(posixId)
1036
+ ) {
1037
+ return null;
1038
+ }
1039
+ const emittedJs = compiler.getEmittedJs(cleanId);
1040
+ if (emittedJs === null || emittedJs === undefined) {
1041
+ return null;
1042
+ }
1043
+ servedViaLoad.add(cleanId);
1044
+ const out = enableSourceMap
1045
+ ? extractInlineSourceMap(emittedJs)
1046
+ : { code: emittedJs, map: null };
1047
+ return isRolldownVite ? { ...out, moduleType: 'js' } : out;
1048
+ },
1049
+ },
1050
+
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
+ }
1078
+
1079
+ if (resolvedConfig?.command === 'serve') {
1080
+ await syncOnDiskChangesForTs(cleanId, null);
1081
+ }
1082
+
1083
+ const emittedJs = compiler.getEmittedJs(cleanId);
1084
+ if (emittedJs === null || emittedJs === undefined) {
1085
+ return null;
1086
+ }
1087
+
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);
1100
+ }
1101
+ }
1102
+ }
1103
+ }
1104
+
1105
+ if (enableSourceMap) {
1106
+ return extractInlineSourceMap(emittedJs);
1107
+ }
1108
+ return { code: emittedJs, map: null };
1109
+ },
1110
+ },
1111
+
1112
+ async handleHotUpdate(ctx) {
1113
+ if (!compiler) {
1114
+ return undefined;
1115
+ }
1116
+ const cleanFile = stripQueryAndHash(ctx.file);
1117
+ const normFile = toPosixPath(path.resolve(cleanFile));
1118
+ if (normFile.includes('/node_modules/') || DTS_FILE_RE.test(normFile)) {
1119
+ return undefined;
1120
+ }
1121
+
1122
+ const isTsChange = TS_FILE_RE.test(normFile);
1123
+ const isResourceChange = RESOURCE_FILE_RE.test(normFile);
1124
+ const isTsconfigChange =
1125
+ normFile.endsWith('/tsconfig.json') || /tsconfig.*\.json$/i.test(path.basename(normFile));
1126
+
1127
+ if (!isTsChange && !isResourceChange && !isTsconfigChange) {
1128
+ return undefined;
1129
+ }
1130
+
1131
+ // 1. Handle external component resource (.html / .css / .scss / .sass + SCSS partials)
1132
+ if (isResourceChange && !isTsChange) {
1133
+ const directOwners = compiler.getAffectedComponentsForResource(cleanFile);
1134
+ const affectedStylePaths = new Set();
1135
+
1136
+ if (SASS_FILE_RE.test(normFile)) {
1137
+ if (directOwners.length > 0) {
1138
+ affectedStylePaths.add(normFile);
1139
+ }
1140
+ const dependentStyles = partialToComponentStyles.get(normFile);
1141
+ if (dependentStyles) {
1142
+ for (const depStyle of dependentStyles) {
1143
+ affectedStylePaths.add(depStyle);
1144
+ }
1145
+ }
1146
+ }
1147
+
1148
+ const rebuildTargets =
1149
+ affectedStylePaths.size > 0 ? [...affectedStylePaths] : directOwners.length > 0 ? [cleanFile] : [];
1150
+
1151
+ if (rebuildTargets.length === 0) {
1152
+ // Global stylesheet or unrelated static HTML file — let Vite handle natively
1153
+ if (/\.(?:css|scss|sass|less)$/i.test(normFile)) {
1154
+ options.onDevServerUpdate?.({ kind: 'style-update', file: cleanFile });
1155
+ }
1156
+ return undefined;
1157
+ }
1158
+
1159
+ const resourceRebuildStart = performance.now();
1160
+ if (affectedStylePaths.size > 0) {
1161
+ try {
1162
+ const overrides = await preprocessComponentStyles([...affectedStylePaths]);
1163
+ if (overrides.length > 0) {
1164
+ compiler.setResourceOverrides(overrides);
1165
+ }
1166
+ } catch (err) {
1167
+ const msg = err instanceof Error ? err.message : String(err);
1168
+ if (!options.suppressViteDiagnosticsLog) {
1169
+ resolvedConfig?.logger?.error(msg);
1170
+ }
1171
+ ctx.server.ws.send({
1172
+ type: 'error',
1173
+ err: { message: msg, stack: '', id: cleanFile, plugin: 'ngrs:angular-compiler' },
1174
+ });
1175
+ options.onDevServerUpdate?.({ kind: 'error', file: cleanFile, message: msg });
1176
+ return [];
1177
+ }
1178
+ }
1179
+
1180
+ const rebuildResult = compiler.rebuild(rebuildTargets);
1181
+ const resourceRebuildMs = performance.now() - resourceRebuildStart;
1182
+ for (const target of rebuildTargets) {
1183
+ recordSnapshot(target);
1184
+ }
1185
+ recordSnapshot(cleanFile);
1186
+ surfaceDiagnostics(rebuildResult.diagnostics, null, ctx.server);
1187
+
1188
+ const allOwners = new Set(directOwners);
1189
+ for (const target of rebuildTargets) {
1190
+ for (const owner of compiler.getAffectedComponentsForResource(target)) {
1191
+ allOwners.add(owner);
1192
+ }
1193
+ }
1194
+ const ownerList = [...allOwners];
1195
+ const invalidatedOwnerMods = invalidateOwnerModules(ctx.server, ownerList);
1196
+
1197
+ // Preserve any non-component Vite CSS modules (in case a file is both global & component CSS)
1198
+ const passthroughCssMods = (ctx.modules || []).filter(
1199
+ (m) => m.file && toPosixPath(m.file) === normFile,
1200
+ );
1201
+
1202
+ if (enableHmr && rebuildResult.exitCode === 0) {
1203
+ let sentLiveHmr = false;
1204
+ const timestamp = Date.now();
1205
+ for (const owner of ownerList) {
1206
+ const hmrIds = compiler.getHmrIdsForFile(owner);
1207
+ for (const hmrId of hmrIds) {
1208
+ const updateCode = compiler.getHmrUpdateModule(hmrId);
1209
+ if (updateCode) {
1210
+ activeHmrUpdates.set(hmrId, updateCode);
1211
+ ctx.server.ws.send({
1212
+ type: 'custom',
1213
+ event: 'angular:component-update',
1214
+ data: { id: hmrId, timestamp },
1215
+ });
1216
+ sentLiveHmr = true;
1217
+ }
1218
+ }
1219
+ }
1220
+ if (sentLiveHmr) {
1221
+ options.onDevServerUpdate?.({
1222
+ kind: 'component-update',
1223
+ file: cleanFile,
1224
+ durationMs: resourceRebuildMs,
1225
+ });
1226
+ return passthroughCssMods;
1227
+ }
1228
+ }
1229
+
1230
+ if (invalidatedOwnerMods.length > 0) {
1231
+ options.onDevServerUpdate?.({
1232
+ kind: 'reload',
1233
+ file: cleanFile,
1234
+ durationMs: resourceRebuildMs,
1235
+ });
1236
+ return [...invalidatedOwnerMods, ...passthroughCssMods];
1237
+ }
1238
+ ctx.server.ws.send({ type: 'full-reload', path: '*' });
1239
+ options.onDevServerUpdate?.({
1240
+ kind: 'reload',
1241
+ file: cleanFile,
1242
+ durationMs: resourceRebuildMs,
1243
+ });
1244
+ return [];
1245
+ }
1246
+
1247
+ // 2. Handle .ts / fileReplacements / tsconfig.json changes
1248
+ const tsRebuildStart = performance.now();
1249
+ compiler.rebuild([cleanFile]);
1250
+ recordSnapshot(cleanFile);
1251
+
1252
+ // Check if newly added/edited component introduced new .scss resources
1253
+ const postResources = compiler.getAllResources();
1254
+ const uncompiledScss = postResources.filter((r) => {
1255
+ if (!SASS_FILE_RE.test(r)) return false;
1256
+ const norm = toPosixPath(path.resolve(workspaceRoot, r));
1257
+ return !compiledComponentStyleCss.has(norm);
1258
+ });
1259
+ if (uncompiledScss.length > 0) {
1260
+ const extraOverrides = await preprocessComponentStyles(uncompiledScss);
1261
+ if (extraOverrides.length > 0) {
1262
+ compiler.setResourceOverrides(extraOverrides);
1263
+ compiler.rebuild(extraOverrides.map((o) => o.path));
1264
+ }
1265
+ }
1266
+
1267
+ const tsRebuildMs = performance.now() - tsRebuildStart;
1268
+ surfaceDiagnostics(compiler.getDiagnostics(), null, ctx.server);
1269
+
1270
+ // Refresh HMR cache for modified .ts components if applicable and invalidate Vite moduleGraph
1271
+ const changedTsPaths = [cleanFile];
1272
+ for (const rep of normalizedReplacements) {
1273
+ if (toPosixPath(rep.with) === normFile) {
1274
+ changedTsPaths.push(rep.replace);
1275
+ }
1276
+ }
1277
+ for (const tsPath of changedTsPaths) {
1278
+ for (const hmrId of compiler.getHmrIdsForFile(tsPath)) {
1279
+ const updateCode = compiler.getHmrUpdateModule(hmrId);
1280
+ if (updateCode) {
1281
+ activeHmrUpdates.set(hmrId, updateCode);
1282
+ }
1283
+ }
1284
+ }
1285
+
1286
+ options.onDevServerUpdate?.({
1287
+ kind: 'reload',
1288
+ file: cleanFile,
1289
+ durationMs: tsRebuildMs,
1290
+ });
1291
+
1292
+ const invalidated = invalidateOwnerModules(ctx.server, changedTsPaths);
1293
+ if (invalidated.length > 0) {
1294
+ return invalidated;
1295
+ }
1296
+ return ctx.modules;
1297
+ },
1298
+ };
1299
+ }
1300
+
1301
+ /**
1302
+ * Plugin 2: `ngrs:ivy-linker`
1303
+ *
1304
+ * 100% native Rust Angular Ivy Linker (`@ngrs/napi` `needsLinking` + `linkFile` — zero `@babel/core`)
1305
+ * running both during Vite dependency pre-bundling (`optimizeDeps.rolldownOptions.plugins` on Vite 8
1306
+ * Rolldown, with `optimizeDeps.esbuildOptions.plugins` fallback on Vite 6/7) and on any un-prebundled
1307
+ * `node_modules` `.js`/`.mjs` modules during `vite serve` and `vite build`.
1308
+ *
1309
+ * @param {import('./index.js').AngularVitePluginOptions} [options]
1310
+ * @returns {import('vite').Plugin}
1311
+ */
1312
+ export function angularLinkerPlugin(options = {}) {
1313
+ let resolvedConfig;
1314
+ let sourceMapping = true;
1315
+ const linkerJitMode = options.jit ?? false;
1316
+ const unknownDeclarationVersionHandling =
1317
+ options.unknownDeclarationVersionHandling ?? 'error';
1318
+
1319
+ return {
1320
+ name: 'ngrs:ivy-linker',
1321
+ enforce: 'pre',
1322
+
1323
+ config(userConfig, env) {
1324
+ const prebundleSourceMap =
1325
+ options.sourceMap ??
1326
+ (env.command === 'serve' ? false : Boolean(userConfig.build?.sourcemap));
1327
+ const useRolldown = options.useRolldown ?? isRolldownVite;
1328
+
1329
+ if (useRolldown) {
1330
+ const rolldownLinker = createRolldownLinkerPlugin({
1331
+ sourceMapping: prebundleSourceMap,
1332
+ linkerJitMode,
1333
+ unknownDeclarationVersionHandling: 'ignore',
1334
+ });
1335
+ const existingPlugins = userConfig.optimizeDeps?.rolldownOptions?.plugins;
1336
+ const normalizedExisting = Array.isArray(existingPlugins)
1337
+ ? existingPlugins
1338
+ : existingPlugins
1339
+ ? [existingPlugins]
1340
+ : [];
1341
+ return {
1342
+ optimizeDeps: {
1343
+ rolldownOptions: {
1344
+ plugins: [...normalizedExisting, rolldownLinker],
1345
+ },
1346
+ },
1347
+ };
1348
+ }
1349
+
1350
+ const esbuildLinker = createEsbuildLinkerPlugin({
1351
+ sourceMapping: prebundleSourceMap,
1352
+ linkerJitMode,
1353
+ unknownDeclarationVersionHandling: 'ignore',
1354
+ });
1355
+ const existingPlugins = userConfig.optimizeDeps?.esbuildOptions?.plugins || [];
1356
+ return {
1357
+ optimizeDeps: {
1358
+ esbuildOptions: {
1359
+ plugins: [...existingPlugins, esbuildLinker],
1360
+ },
1361
+ },
1362
+ };
1363
+ },
1364
+
1365
+ configResolved(config) {
1366
+ resolvedConfig = config;
1367
+ sourceMapping =
1368
+ options.sourceMap ??
1369
+ (config.command === 'serve' ? true : Boolean(config.build?.sourcemap));
1370
+ },
1371
+
1372
+ transform: {
1373
+ filter: {
1374
+ id: /\.[cm]?js(?:$|\?)/,
1375
+ },
1376
+ async handler(code, id) {
1377
+ if (id.startsWith('\0')) {
1378
+ return null;
1379
+ }
1380
+ const cleanId = stripQueryAndHash(id);
1381
+ const posixId = toPosixPath(cleanId);
1382
+ if (!JS_MODULE_RE.test(posixId)) {
1383
+ return null;
1384
+ }
1385
+ const isNodeModules = posixId.includes('/node_modules/');
1386
+
1387
+ const optimizeForBundling =
1388
+ options.optimizeForBundling ??
1389
+ (resolvedConfig?.command === 'build' &&
1390
+ !resolvedConfig?.build?.watch &&
1391
+ resolvedConfig?.define?.ngDevMode === 'false' &&
1392
+ !linkerJitMode);
1393
+
1394
+ const canOptimizeWithoutLinking =
1395
+ isNodeModules &&
1396
+ optimizeForBundling &&
1397
+ (posixId.includes('/node_modules/@angular/') ||
1398
+ code.includes('setClassMetadata') ||
1399
+ code.includes('setClassDebugInfo') ||
1400
+ code.includes('static ɵ') ||
1401
+ code.includes('InjectionToken'));
1402
+
1403
+ if (!canOptimizeWithoutLinking && !needsLinking(cleanId, code) && !code.includes('\\u0275')) {
1404
+ return null;
1405
+ }
1406
+
1407
+ const result = await linkFileAsyncFn(cleanId, code, {
1408
+ sourceMapping,
1409
+ linkerJitMode,
1410
+ unknownDeclarationVersionHandling,
1411
+ optimizeForBundling,
1412
+ });
1413
+
1414
+ if (result.diagnostics?.length) {
1415
+ const { warnings, errors } = formatDiagnostics(
1416
+ result.diagnostics,
1417
+ resolvedConfig?.root ?? process.cwd(),
1418
+ );
1419
+ const logger = resolvedConfig?.logger ?? console;
1420
+ for (const warn of warnings) {
1421
+ logger.warn(warn);
1422
+ }
1423
+ if (errors.length > 0) {
1424
+ const msg = errors.join('\n');
1425
+ if (resolvedConfig?.command === 'build') {
1426
+ this.error(msg);
1427
+ } else {
1428
+ logger.error(msg);
1429
+ }
1430
+ }
1431
+ }
1432
+
1433
+ if (!result.linked) {
1434
+ return null;
1435
+ }
1436
+
1437
+ let map = null;
1438
+ if (sourceMapping && result.sourceMap) {
1439
+ try {
1440
+ map = JSON.parse(result.sourceMap);
1441
+ } catch {
1442
+ map = null;
1443
+ }
1444
+ }
1445
+
1446
+ return {
1447
+ code: result.code,
1448
+ map,
1449
+ };
1450
+ },
1451
+ },
1452
+ };
1453
+ }
1454
+
1455
+ /**
1456
+ * Returns the `@ngrs/vite` Vite plugin array (`[ngrs:angular-compiler, ngrs:ivy-linker]`).
1457
+ *
1458
+ * @param {import('./index.js').AngularVitePluginOptions} [options]
1459
+ * @returns {import('vite').Plugin[]}
1460
+ */
1461
+ export function angular(options = {}) {
1462
+ return [angularCompilerPlugin(options), angularLinkerPlugin(options)];
1463
+ }
1464
+
1465
+ export default angular;