@analogjs/vite-plugin-angular 3.0.0-alpha.7 → 3.0.0-alpha.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/README.md +30 -0
  2. package/migrations/migrate-setup-vitest/migrate-setup-vitest.d.ts +2 -0
  3. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js +49 -0
  4. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js.map +1 -0
  5. package/migrations/migration.json +7 -1
  6. package/migrations/migrations.json +9 -0
  7. package/migrations/update-3-0-0/migrate-setup-vitest.d.ts +2 -0
  8. package/migrations/update-3-0-0/migrate-setup-vitest.js +36 -0
  9. package/migrations/update-3-0-0/migrate-setup-vitest.js.map +1 -0
  10. package/package.json +51 -12
  11. package/src/index.d.ts +5 -2
  12. package/src/index.js +6 -2
  13. package/src/index.js.map +1 -1
  14. package/src/lib/analog-plugin-interop.d.ts +40 -0
  15. package/src/lib/analog-plugin-interop.js +61 -0
  16. package/src/lib/analog-plugin-interop.js.map +1 -0
  17. package/src/lib/angular-build-optimizer-plugin.d.ts +4 -4
  18. package/src/lib/angular-build-optimizer-plugin.js +57 -62
  19. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  20. package/src/lib/angular-jit-plugin.d.ts +3 -3
  21. package/src/lib/angular-jit-plugin.js +51 -37
  22. package/src/lib/angular-jit-plugin.js.map +1 -1
  23. package/src/lib/angular-pending-tasks.plugin.d.ts +7 -7
  24. package/src/lib/angular-pending-tasks.plugin.js +17 -18
  25. package/src/lib/angular-pending-tasks.plugin.js.map +1 -1
  26. package/src/lib/angular-vite-plugin.d.ts +177 -69
  27. package/src/lib/angular-vite-plugin.js +1227 -1084
  28. package/src/lib/angular-vite-plugin.js.map +1 -1
  29. package/src/lib/angular-vitest-plugin.d.ts +26 -17
  30. package/src/lib/angular-vitest-plugin.js +106 -114
  31. package/src/lib/angular-vitest-plugin.js.map +1 -1
  32. package/src/lib/compilation-api/compilation-api-plugin.d.ts +29 -0
  33. package/src/lib/compilation-api/compilation-api-plugin.js +491 -0
  34. package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -0
  35. package/src/lib/compilation-api/index.d.ts +1 -0
  36. package/src/lib/compilation-api/index.js +1 -0
  37. package/src/lib/compiler/angular-version.d.ts +19 -0
  38. package/src/lib/compiler/angular-version.js +31 -0
  39. package/src/lib/compiler/angular-version.js.map +1 -0
  40. package/src/lib/compiler/class-field-lowering.d.ts +23 -0
  41. package/src/lib/compiler/class-field-lowering.js +131 -0
  42. package/src/lib/compiler/class-field-lowering.js.map +1 -0
  43. package/src/lib/compiler/compile.d.ts +50 -0
  44. package/src/lib/compiler/compile.js +814 -0
  45. package/src/lib/compiler/compile.js.map +1 -0
  46. package/src/lib/compiler/constants.d.ts +24 -0
  47. package/src/lib/compiler/constants.js +59 -0
  48. package/src/lib/compiler/constants.js.map +1 -0
  49. package/src/lib/compiler/debug.d.ts +22 -0
  50. package/src/lib/compiler/debug.js +20 -0
  51. package/src/lib/compiler/debug.js.map +1 -0
  52. package/src/lib/compiler/defer.d.ts +57 -0
  53. package/src/lib/compiler/defer.js +154 -0
  54. package/src/lib/compiler/defer.js.map +1 -0
  55. package/src/lib/compiler/dts-reader.d.ts +45 -0
  56. package/src/lib/compiler/dts-reader.js +395 -0
  57. package/src/lib/compiler/dts-reader.js.map +1 -0
  58. package/src/lib/compiler/hmr.d.ts +16 -0
  59. package/src/lib/compiler/hmr.js +69 -0
  60. package/src/lib/compiler/hmr.js.map +1 -0
  61. package/src/lib/compiler/index.d.ts +8 -0
  62. package/src/lib/compiler/index.js +8 -0
  63. package/src/lib/compiler/jit-metadata.d.ts +14 -0
  64. package/src/lib/compiler/jit-metadata.js +168 -0
  65. package/src/lib/compiler/jit-metadata.js.map +1 -0
  66. package/src/lib/compiler/jit-transform.d.ts +24 -0
  67. package/src/lib/compiler/jit-transform.js +204 -0
  68. package/src/lib/compiler/jit-transform.js.map +1 -0
  69. package/src/lib/compiler/js-emitter.d.ts +10 -0
  70. package/src/lib/compiler/js-emitter.js +446 -0
  71. package/src/lib/compiler/js-emitter.js.map +1 -0
  72. package/src/lib/compiler/metadata.d.ts +36 -0
  73. package/src/lib/compiler/metadata.js +710 -0
  74. package/src/lib/compiler/metadata.js.map +1 -0
  75. package/src/lib/compiler/registry.d.ts +56 -0
  76. package/src/lib/compiler/registry.js +176 -0
  77. package/src/lib/compiler/registry.js.map +1 -0
  78. package/src/lib/compiler/resource-inliner.d.ts +43 -0
  79. package/src/lib/compiler/resource-inliner.js +230 -0
  80. package/src/lib/compiler/resource-inliner.js.map +1 -0
  81. package/src/lib/compiler/style-ast.d.ts +9 -0
  82. package/src/lib/compiler/style-ast.js +54 -0
  83. package/src/lib/compiler/style-ast.js.map +1 -0
  84. package/src/lib/compiler/styles.d.ts +13 -0
  85. package/src/lib/compiler/test-helpers.d.ts +7 -0
  86. package/src/lib/compiler/type-elision.d.ts +28 -0
  87. package/src/lib/compiler/type-elision.js +211 -0
  88. package/src/lib/compiler/type-elision.js.map +1 -0
  89. package/src/lib/compiler/utils.d.ts +40 -0
  90. package/src/lib/compiler/utils.js +76 -0
  91. package/src/lib/compiler/utils.js.map +1 -0
  92. package/src/lib/compiler-plugin.d.ts +13 -12
  93. package/src/lib/compiler-plugin.js +40 -44
  94. package/src/lib/compiler-plugin.js.map +1 -1
  95. package/src/lib/component-resolvers.d.ts +23 -5
  96. package/src/lib/component-resolvers.js +107 -64
  97. package/src/lib/component-resolvers.js.map +1 -1
  98. package/src/lib/encapsulation-plugin.d.ts +13 -0
  99. package/src/lib/encapsulation-plugin.js +48 -0
  100. package/src/lib/encapsulation-plugin.js.map +1 -0
  101. package/src/lib/fast-compile-plugin.d.ts +28 -0
  102. package/src/lib/fast-compile-plugin.js +414 -0
  103. package/src/lib/fast-compile-plugin.js.map +1 -0
  104. package/src/lib/host.d.ts +10 -8
  105. package/src/lib/host.js +113 -101
  106. package/src/lib/host.js.map +1 -1
  107. package/src/lib/live-reload-plugin.d.ts +5 -5
  108. package/src/lib/live-reload-plugin.js +61 -63
  109. package/src/lib/live-reload-plugin.js.map +1 -1
  110. package/src/lib/models.d.ts +9 -9
  111. package/src/lib/nx-folder-plugin.d.ts +5 -5
  112. package/src/lib/nx-folder-plugin.js +18 -16
  113. package/src/lib/nx-folder-plugin.js.map +1 -1
  114. package/src/lib/plugins/file-replacements.plugin.d.ts +4 -4
  115. package/src/lib/plugins/file-replacements.plugin.js +40 -62
  116. package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
  117. package/src/lib/router-plugin.d.ts +1 -1
  118. package/src/lib/router-plugin.js +35 -23
  119. package/src/lib/router-plugin.js.map +1 -1
  120. package/src/lib/style-pipeline.d.ts +15 -0
  121. package/src/lib/style-pipeline.js +31 -0
  122. package/src/lib/style-pipeline.js.map +1 -0
  123. package/src/lib/style-preprocessor.d.ts +35 -0
  124. package/src/lib/style-preprocessor.js +35 -0
  125. package/src/lib/style-preprocessor.js.map +1 -0
  126. package/src/lib/stylesheet-registry.d.ts +74 -0
  127. package/src/lib/stylesheet-registry.js +174 -0
  128. package/src/lib/stylesheet-registry.js.map +1 -0
  129. package/src/lib/tailwind-plugin.d.ts +34 -0
  130. package/src/lib/tailwind-plugin.js +116 -0
  131. package/src/lib/tailwind-plugin.js.map +1 -0
  132. package/src/lib/tools/package.json +2 -7
  133. package/src/lib/tools/src/builders/vite/vite-build.impl.js +33 -38
  134. package/src/lib/tools/src/builders/vite/vite-build.impl.js.map +1 -1
  135. package/src/lib/tools/src/builders/vite-dev-server/dev-server.impl.js +51 -62
  136. package/src/lib/tools/src/builders/vite-dev-server/dev-server.impl.js.map +1 -1
  137. package/src/lib/tools/src/index.js +0 -2
  138. package/src/lib/utils/compilation-shared.d.ts +62 -0
  139. package/src/lib/utils/compilation-shared.js +138 -0
  140. package/src/lib/utils/compilation-shared.js.map +1 -0
  141. package/src/lib/utils/compiler-plugin-options.d.ts +11 -11
  142. package/src/lib/utils/css-extension-resolver.d.ts +32 -0
  143. package/src/lib/utils/css-extension-resolver.js +73 -0
  144. package/src/lib/utils/css-extension-resolver.js.map +1 -0
  145. package/src/lib/utils/debug-harness.d.ts +23 -0
  146. package/src/lib/utils/debug-harness.js +88 -0
  147. package/src/lib/utils/debug-harness.js.map +1 -0
  148. package/src/lib/utils/debug-log-file.d.ts +5 -0
  149. package/src/lib/utils/debug-log-file.js +56 -0
  150. package/src/lib/utils/debug-log-file.js.map +1 -0
  151. package/src/lib/utils/debug.d.ts +28 -0
  152. package/src/lib/utils/debug.js +39 -0
  153. package/src/lib/utils/debug.js.map +1 -0
  154. package/src/lib/utils/devkit.d.ts +6 -6
  155. package/src/lib/utils/devkit.js +34 -38
  156. package/src/lib/utils/devkit.js.map +1 -1
  157. package/src/lib/utils/hmr-candidates.d.ts +28 -28
  158. package/src/lib/utils/jit-inline-styles.d.ts +3 -0
  159. package/src/lib/utils/jit-inline-styles.js +16 -0
  160. package/src/lib/utils/jit-inline-styles.js.map +1 -0
  161. package/src/lib/utils/plugin-config.d.ts +41 -0
  162. package/src/lib/utils/plugin-config.js +85 -0
  163. package/src/lib/utils/plugin-config.js.map +1 -0
  164. package/src/lib/utils/rolldown.d.ts +2 -0
  165. package/src/lib/utils/rolldown.js +12 -0
  166. package/src/lib/utils/rolldown.js.map +1 -0
  167. package/src/lib/utils/safe-module-paths.d.ts +16 -0
  168. package/src/lib/utils/safe-module-paths.js +29 -0
  169. package/src/lib/utils/safe-module-paths.js.map +1 -0
  170. package/src/lib/utils/source-file-cache.d.ts +8 -15
  171. package/src/lib/utils/source-file-cache.js +35 -37
  172. package/src/lib/utils/source-file-cache.js.map +1 -1
  173. package/src/lib/utils/tailwind-reference.d.ts +12 -0
  174. package/src/lib/utils/tailwind-reference.js +99 -0
  175. package/src/lib/utils/tailwind-reference.js.map +1 -0
  176. package/src/lib/utils/transform-cache.d.ts +43 -0
  177. package/src/lib/utils/transform-cache.js +97 -0
  178. package/src/lib/utils/transform-cache.js.map +1 -0
  179. package/src/lib/utils/tsconfig-resolver.d.ts +28 -0
  180. package/src/lib/utils/tsconfig-resolver.js +191 -0
  181. package/src/lib/utils/tsconfig-resolver.js.map +1 -0
  182. package/src/lib/utils/virtual-ids.d.ts +4 -0
  183. package/src/lib/utils/virtual-ids.js +23 -0
  184. package/src/lib/utils/virtual-ids.js.map +1 -0
  185. package/src/lib/utils/virtual-resources.d.ts +19 -0
  186. package/src/lib/utils/virtual-resources.js +38 -0
  187. package/src/lib/utils/virtual-resources.js.map +1 -0
  188. package/src/lib/virtual-modules-plugin.d.ts +5 -0
  189. package/src/lib/virtual-modules-plugin.js +23 -0
  190. package/src/lib/virtual-modules-plugin.js.map +1 -0
  191. package/src/test-setup.d.ts +2 -0
  192. package/setup-vitest.d.ts +0 -4
  193. package/setup-vitest.js +0 -215
  194. package/setup-vitest.js.map +0 -1
  195. package/src/lib/models.js +0 -1
  196. package/src/lib/models.js.map +0 -1
  197. package/src/lib/tools/README.md +0 -3
  198. package/src/lib/tools/src/index.d.ts +0 -0
  199. package/src/lib/tools/src/index.js.map +0 -1
  200. package/src/lib/utils/compiler-plugin-options.js +0 -1
  201. package/src/lib/utils/compiler-plugin-options.js.map +0 -1
  202. package/src/lib/utils/hmr-candidates.js +0 -272
  203. package/src/lib/utils/hmr-candidates.js.map +0 -1
@@ -1,1100 +1,1243 @@
1
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
- import { basename, dirname, isAbsolute, join, relative, resolve, } from 'node:path';
3
- import * as vite from 'vite';
4
- import * as compilerCli from '@angular/compiler-cli';
5
- import { createRequire } from 'node:module';
6
- import * as ngCompiler from '@angular/compiler';
7
- import { globSync } from 'tinyglobby';
8
- import { defaultClientConditions, normalizePath, preprocessCSS, } from 'vite';
9
- import { buildOptimizerPlugin } from './angular-build-optimizer-plugin.js';
10
- import { jitPlugin } from './angular-jit-plugin.js';
11
- import { createCompilerPlugin, createRolldownCompilerPlugin, } from './compiler-plugin.js';
12
- import { StyleUrlsResolver, TemplateUrlsResolver, } from './component-resolvers.js';
13
- import { augmentHostWithCaching, augmentHostWithResources, augmentProgramWithVersioning, mergeTransformers, } from './host.js';
14
- import { angularVitestPlugins } from './angular-vitest-plugin.js';
15
- import { createAngularCompilation, createJitResourceTransformer, SourceFileCache, angularFullVersion, } from './utils/devkit.js';
16
- const require = createRequire(import.meta.url);
17
- import { pendingTasksPlugin } from './angular-pending-tasks.plugin.js';
18
- import { liveReloadPlugin } from './live-reload-plugin.js';
19
- import { nxFolderPlugin } from './nx-folder-plugin.js';
20
- import { replaceFiles, } from './plugins/file-replacements.plugin.js';
21
- import { routerPlugin } from './router-plugin.js';
22
- import { createHash } from 'node:crypto';
23
- export var DiagnosticModes;
24
- (function (DiagnosticModes) {
25
- DiagnosticModes[DiagnosticModes["None"] = 0] = "None";
26
- DiagnosticModes[DiagnosticModes["Option"] = 1] = "Option";
27
- DiagnosticModes[DiagnosticModes["Syntactic"] = 2] = "Syntactic";
28
- DiagnosticModes[DiagnosticModes["Semantic"] = 4] = "Semantic";
29
- DiagnosticModes[DiagnosticModes["All"] = 7] = "All";
30
- })(DiagnosticModes || (DiagnosticModes = {}));
31
- /**
32
- * TypeScript file extension regex
33
- * Match .(c or m)ts, .ts extensions with an optional ? for query params
34
- * Ignore .tsx extensions
35
- */
36
- const TS_EXT_REGEX = /\.[cm]?(ts)[^x]?\??/;
37
- const classNames = new Map();
38
- export function angular(options) {
39
- /**
40
- * Normalize plugin options so defaults
41
- * are used for values not provided.
42
- */
43
- const pluginOptions = {
44
- tsconfigGetter: createTsConfigGetter(options?.tsconfig),
45
- workspaceRoot: options?.workspaceRoot ?? process.cwd(),
46
- inlineStylesExtension: options?.inlineStylesExtension ?? 'css',
47
- advanced: {
48
- tsTransformers: {
49
- before: options?.advanced?.tsTransformers?.before ?? [],
50
- after: options?.advanced?.tsTransformers?.after ?? [],
51
- afterDeclarations: options?.advanced?.tsTransformers?.afterDeclarations ?? [],
52
- },
53
- },
54
- supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],
55
- jit: options?.jit,
56
- include: options?.include ?? [],
57
- additionalContentDirs: options?.additionalContentDirs ?? [],
58
- liveReload: options?.liveReload ?? false,
59
- disableTypeChecking: options?.disableTypeChecking ?? true,
60
- fileReplacements: options?.fileReplacements ?? [],
61
- useAngularCompilationAPI: options?.experimental?.useAngularCompilationAPI ?? false,
62
- };
63
- let resolvedConfig;
64
- // Store config context needed for getTsConfigPath resolution
65
- let tsConfigResolutionContext = null;
66
- const ts = require('typescript');
67
- let builder;
68
- let nextProgram;
69
- // Caches (always rebuild Angular program per user request)
70
- const tsconfigOptionsCache = new Map();
71
- let cachedHost;
72
- let cachedHostKey;
73
- let includeCache = [];
74
- function invalidateFsCaches() {
75
- includeCache = [];
76
- }
77
- function invalidateTsconfigCaches() {
78
- // `readConfiguration` caches the root file list, so hot-added pages can be
79
- // missing from Angular's compilation program until we clear this state.
80
- tsconfigOptionsCache.clear();
81
- cachedHost = undefined;
82
- cachedHostKey = undefined;
83
- }
84
- let watchMode = false;
85
- let testWatchMode = isTestWatchMode();
86
- let inlineComponentStyles;
87
- let externalComponentStyles;
88
- const sourceFileCache = new SourceFileCache();
89
- const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];
90
- const isVitestVscode = !!process.env['VITEST_VSCODE'];
91
- const isStackBlitz = !!process.versions['webcontainer'];
92
- const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';
93
- const jit = typeof pluginOptions?.jit !== 'undefined' ? pluginOptions.jit : isTest;
94
- let viteServer;
95
- const styleUrlsResolver = new StyleUrlsResolver();
96
- const templateUrlsResolver = new TemplateUrlsResolver();
97
- let outputFile;
98
- const outputFiles = new Map();
99
- const fileEmitter = (file) => {
100
- outputFile?.(file);
101
- return outputFiles.get(normalizePath(file));
102
- };
103
- let initialCompilation = false;
104
- const declarationFiles = [];
105
- const fileTransformMap = new Map();
106
- let styleTransform;
107
- let pendingCompilation;
108
- let compilationLock = Promise.resolve();
109
- // Persistent Angular Compilation API instance. Kept alive across rebuilds so
110
- // Angular can diff previous state and emit `templateUpdates` for HMR.
111
- // Previously the compilation was recreated on every pass, which meant Angular
112
- // never had prior state and could never produce HMR payloads.
113
- let angularCompilation;
114
- function angularPlugin() {
115
- let isProd = false;
116
- if (angularFullVersion < 190000 || isTest) {
117
- pluginOptions.liveReload = false;
118
- }
119
- // liveReload and fileReplacements guards were previously here and forced
120
- // both options off when useAngularCompilationAPI was enabled. Those guards
121
- // have been removed because:
122
- // - liveReload: the persistent compilation instance (above) now gives
123
- // Angular the prior state it needs to emit `templateUpdates` for HMR
124
- // - fileReplacements: Angular's AngularHostOptions already accepts a
125
- // `fileReplacements` record — we now convert and pass it through in
126
- // `performAngularCompilation` via `toAngularCompilationFileReplacements`
127
- if (pluginOptions.useAngularCompilationAPI) {
128
- if (angularFullVersion < 200100) {
129
- pluginOptions.useAngularCompilationAPI = false;
130
- console.warn('[@analogjs/vite-plugin-angular]: The Angular Compilation API is only available with Angular v20.1 and later');
131
- }
132
- }
133
- return {
134
- name: '@analogjs/vite-plugin-angular',
135
- async config(config, { command }) {
136
- watchMode = command === 'serve';
137
- isProd =
138
- config.mode === 'production' ||
139
- process.env['NODE_ENV'] === 'production';
140
- // Store the config context for later resolution in configResolved
141
- tsConfigResolutionContext = {
142
- root: config.root || '.',
143
- isProd,
144
- isLib: !!config?.build?.lib,
145
- };
146
- // Do a preliminary resolution for esbuild plugin (before configResolved)
147
- const preliminaryTsConfigPath = resolveTsConfigPath();
148
- const esbuild = pluginOptions.useAngularCompilationAPI
149
- ? undefined
150
- : (config.esbuild ?? false);
151
- const oxc = pluginOptions.useAngularCompilationAPI
152
- ? undefined
153
- : (config.oxc ?? false);
154
- const defineOptions = {
155
- ngJitMode: 'false',
156
- ngI18nClosureMode: 'false',
157
- ...(watchMode ? {} : { ngDevMode: 'false' }),
158
- };
159
- const rolldownOptions = {
160
- plugins: [
161
- createRolldownCompilerPlugin({
162
- tsconfig: preliminaryTsConfigPath,
163
- sourcemap: !isProd,
164
- advancedOptimizations: isProd,
165
- jit,
166
- incremental: watchMode,
167
- }),
168
- ],
169
- };
170
- const esbuildOptions = {
171
- plugins: [
172
- createCompilerPlugin({
173
- tsconfig: preliminaryTsConfigPath,
174
- sourcemap: !isProd,
175
- advancedOptimizations: isProd,
176
- jit,
177
- incremental: watchMode,
178
- }, isTest, !isAstroIntegration),
179
- ],
180
- define: defineOptions,
181
- };
182
- return {
183
- ...(vite.rolldownVersion ? { oxc } : { esbuild }),
184
- optimizeDeps: {
185
- include: ['rxjs/operators', 'rxjs'],
186
- exclude: ['@angular/platform-server'],
187
- ...(vite.rolldownVersion
188
- ? { rolldownOptions }
189
- : { esbuildOptions }),
190
- },
191
- resolve: {
192
- conditions: [
193
- 'style',
194
- ...(config.resolve?.conditions || defaultClientConditions),
195
- ],
196
- },
197
- };
198
- },
199
- configResolved(config) {
200
- resolvedConfig = config;
201
- if (pluginOptions.useAngularCompilationAPI) {
202
- externalComponentStyles = new Map();
203
- inlineComponentStyles = new Map();
204
- }
205
- if (!jit) {
206
- styleTransform = (code, filename) => preprocessCSS(code, filename, config);
207
- }
208
- if (isTest) {
209
- // set test watch mode
210
- // - vite override from vitest-angular
211
- // - @nx/vite executor set server.watch explicitly to undefined (watch)/null (watch=false)
212
- // - vite config for test.watch variable
213
- // - vitest watch mode detected from the command line
214
- testWatchMode =
215
- !(config.server.watch === null) ||
216
- config.test?.watch === true ||
217
- testWatchMode;
218
- }
219
- },
220
- configureServer(server) {
221
- viteServer = server;
222
- // Add/unlink changes the TypeScript program shape, not just file
223
- // contents, so we need to invalidate both include discovery and the
224
- // cached tsconfig root names before recompiling.
225
- const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, () => performCompilation(resolvedConfig));
226
- server.watcher.on('add', invalidateCompilationOnFsChange);
227
- server.watcher.on('unlink', invalidateCompilationOnFsChange);
228
- server.watcher.on('change', (file) => {
229
- if (file.includes('tsconfig')) {
230
- invalidateTsconfigCaches();
231
- }
232
- });
233
- },
234
- async buildStart() {
235
- // Defer the first compilation in test mode
236
- if (!isVitestVscode) {
237
- await performCompilation(resolvedConfig);
238
- pendingCompilation = null;
239
- initialCompilation = true;
240
- }
241
- },
242
- async handleHotUpdate(ctx) {
243
- if (TS_EXT_REGEX.test(ctx.file)) {
244
- const [fileId] = ctx.file.split('?');
245
- pendingCompilation = performCompilation(resolvedConfig, [fileId]);
246
- let result;
247
- if (pluginOptions.liveReload) {
248
- await pendingCompilation;
249
- pendingCompilation = null;
250
- result = fileEmitter(fileId);
251
- }
252
- if (pluginOptions.liveReload &&
253
- result?.hmrEligible &&
254
- classNames.get(fileId)) {
255
- const relativeFileId = `${normalizePath(relative(process.cwd(), fileId))}@${classNames.get(fileId)}`;
256
- sendHMRComponentUpdate(ctx.server, relativeFileId);
257
- return ctx.modules.map((mod) => {
258
- if (mod.id === ctx.file) {
259
- return markModuleSelfAccepting(mod);
260
- }
261
- return mod;
262
- });
263
- }
264
- }
265
- if (/\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {
266
- fileTransformMap.delete(ctx.file.split('?')[0]);
267
- /**
268
- * Check to see if this was a direct request
269
- * for an external resource (styles, html).
270
- */
271
- const isDirect = ctx.modules.find((mod) => ctx.file === mod.file && mod.id?.includes('?direct'));
272
- const isInline = ctx.modules.find((mod) => ctx.file === mod.file && mod.id?.includes('?inline'));
273
- if (isDirect || isInline) {
274
- if (pluginOptions.liveReload && isDirect?.id && isDirect.file) {
275
- const isComponentStyle = isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);
276
- if (isComponentStyle) {
277
- const { encapsulation } = getComponentStyleSheetMeta(isDirect.id);
278
- // Track if the component uses ShadowDOM encapsulation
279
- // Shadow DOM components currently require a full reload.
280
- // Vite's CSS hot replacement does not support shadow root searching.
281
- if (encapsulation !== 'shadow') {
282
- ctx.server.ws.send({
283
- type: 'update',
284
- updates: [
285
- {
286
- type: 'css-update',
287
- timestamp: Date.now(),
288
- path: isDirect.url,
289
- acceptedPath: isDirect.file,
290
- },
291
- ],
292
- });
293
- return ctx.modules
294
- .filter((mod) => {
295
- // Component stylesheets will have 2 modules (*.component.scss and *.component.scss?direct&ngcomp=xyz&e=x)
296
- // We remove the module with the query params to prevent vite double logging the stylesheet name "hmr update *.component.scss, *.component.scss?direct&ngcomp=xyz&e=x"
297
- return mod.file !== ctx.file || mod.id !== isDirect.id;
298
- })
299
- .map((mod) => {
300
- if (mod.file === ctx.file) {
301
- return markModuleSelfAccepting(mod);
302
- }
303
- return mod;
304
- });
305
- }
306
- }
307
- }
308
- return ctx.modules;
309
- }
310
- const mods = [];
311
- const updates = [];
312
- ctx.modules.forEach((mod) => {
313
- mod.importers.forEach((imp) => {
314
- ctx.server.moduleGraph.invalidateModule(imp);
315
- if (pluginOptions.liveReload && classNames.get(imp.id)) {
316
- updates.push(imp.id);
317
- }
318
- else {
319
- mods.push(imp);
320
- }
321
- });
322
- });
323
- pendingCompilation = performCompilation(resolvedConfig, [
324
- ...mods.map((mod) => mod.id),
325
- ...updates,
326
- ]);
327
- if (updates.length > 0) {
328
- await pendingCompilation;
329
- pendingCompilation = null;
330
- updates.forEach((updateId) => {
331
- const impRelativeFileId = `${normalizePath(relative(process.cwd(), updateId))}@${classNames.get(updateId)}`;
332
- sendHMRComponentUpdate(ctx.server, impRelativeFileId);
333
- });
334
- return ctx.modules.map((mod) => {
335
- if (mod.id === ctx.file) {
336
- return markModuleSelfAccepting(mod);
337
- }
338
- return mod;
339
- });
340
- }
341
- return mods;
342
- }
343
- // clear HMR updates with a full reload
344
- classNames.clear();
345
- return ctx.modules;
346
- },
347
- resolveId(id, importer) {
348
- if (jit && id.startsWith('angular:jit:')) {
349
- const path = id.split(';')[1];
350
- return `${normalizePath(resolve(dirname(importer), path))}?${id.includes(':style') ? 'inline' : 'raw'}`;
351
- }
352
- // Map angular external styleUrls to the source file
353
- if (isComponentStyleSheet(id)) {
354
- const componentStyles = externalComponentStyles?.get(getFilenameFromPath(id));
355
- if (componentStyles) {
356
- return componentStyles + new URL(id, 'http://localhost').search;
357
- }
358
- }
359
- return undefined;
360
- },
361
- async load(id) {
362
- // Map angular inline styles to the source text
363
- if (isComponentStyleSheet(id)) {
364
- const componentStyles = inlineComponentStyles?.get(getFilenameFromPath(id));
365
- if (componentStyles) {
366
- return componentStyles;
367
- }
368
- }
369
- return;
370
- },
371
- transform: {
372
- filter: {
373
- id: {
374
- include: [TS_EXT_REGEX],
375
- exclude: [/node_modules/, 'type=script', '@ng/component'],
376
- },
377
- },
378
- async handler(code, id) {
379
- /**
380
- * Check for options.transformFilter
381
- */
382
- if (options?.transformFilter &&
383
- !(options?.transformFilter(code, id) ?? true)) {
384
- return;
385
- }
386
- if (pluginOptions.useAngularCompilationAPI) {
387
- const isAngular = /(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
388
- if (!isAngular) {
389
- return;
390
- }
391
- }
392
- /**
393
- * Skip transforming content files
394
- */
395
- if (id.includes('?') && id.includes('analog-content-')) {
396
- return;
397
- }
398
- /**
399
- * Encapsulate component stylesheets that use emulated encapsulation
400
- */
401
- if (pluginOptions.liveReload && isComponentStyleSheet(id)) {
402
- const { encapsulation, componentId } = getComponentStyleSheetMeta(id);
403
- if (encapsulation === 'emulated' && componentId) {
404
- const encapsulated = ngCompiler.encapsulateStyle(code, componentId);
405
- return {
406
- code: encapsulated,
407
- map: null,
408
- };
409
- }
410
- }
411
- if (id.includes('.ts?')) {
412
- // Strip the query string off the ID
413
- // in case of a dynamically loaded file
414
- id = id.replace(/\?(.*)/, '');
415
- }
416
- fileTransformMap.set(id, code);
417
- /**
418
- * Re-analyze on each transform
419
- * for test(Vitest)
420
- */
421
- if (isTest) {
422
- if (isVitestVscode && !initialCompilation) {
423
- // Do full initial compilation
424
- pendingCompilation = performCompilation(resolvedConfig);
425
- initialCompilation = true;
426
- }
427
- const tsMod = viteServer?.moduleGraph.getModuleById(id);
428
- if (tsMod) {
429
- const invalidated = tsMod.lastInvalidationTimestamp;
430
- if (testWatchMode && invalidated) {
431
- pendingCompilation = performCompilation(resolvedConfig, [id]);
432
- }
433
- }
434
- }
435
- const hasComponent = code.includes('@Component');
436
- const templateUrls = hasComponent
437
- ? templateUrlsResolver.resolve(code, id)
438
- : [];
439
- const styleUrls = hasComponent
440
- ? styleUrlsResolver.resolve(code, id)
441
- : [];
442
- if (hasComponent && watchMode) {
443
- for (const urlSet of [...templateUrls, ...styleUrls]) {
444
- // `urlSet` is a string where a relative path is joined with an
445
- // absolute path using the `|` symbol.
446
- // For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.
447
- const [, absoluteFileUrl] = urlSet.split('|');
448
- this.addWatchFile(absoluteFileUrl);
449
- }
450
- }
451
- if (pendingCompilation) {
452
- await pendingCompilation;
453
- pendingCompilation = null;
454
- }
455
- const typescriptResult = fileEmitter(id);
456
- if (typescriptResult?.warnings &&
457
- typescriptResult?.warnings.length > 0) {
458
- this.warn(`${typescriptResult.warnings.join('\n')}`);
459
- }
460
- if (typescriptResult?.errors && typescriptResult?.errors.length > 0) {
461
- this.error(`${typescriptResult.errors.join('\n')}`);
462
- }
463
- // return fileEmitter
464
- let data = typescriptResult?.content ?? '';
465
- if (jit && data.includes('angular:jit:')) {
466
- data = data.replace(/angular:jit:style:inline;/g, 'virtual:angular:jit:style:inline;');
467
- templateUrls.forEach((templateUrlSet) => {
468
- const [templateFile, resolvedTemplateUrl] = templateUrlSet.split('|');
469
- data = data.replace(`angular:jit:template:file;${templateFile}`, `${resolvedTemplateUrl}?raw`);
470
- });
471
- styleUrls.forEach((styleUrlSet) => {
472
- const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');
473
- data = data.replace(`angular:jit:style:file;${styleFile}`, `${resolvedStyleUrl}?inline`);
474
- });
475
- }
476
- return {
477
- code: data,
478
- map: null,
479
- };
480
- },
481
- },
482
- closeBundle() {
483
- declarationFiles.forEach(({ declarationFileDir, declarationPath, data }) => {
484
- mkdirSync(declarationFileDir, { recursive: true });
485
- writeFileSync(declarationPath, data, 'utf-8');
486
- });
487
- // Tear down the persistent compilation instance at end of build so it
488
- // does not leak memory across unrelated Vite invocations.
489
- angularCompilation?.close?.();
490
- angularCompilation = undefined;
491
- },
492
- };
493
- }
494
- return [
495
- replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
496
- angularPlugin(),
497
- pluginOptions.liveReload && liveReloadPlugin({ classNames, fileEmitter }),
498
- ...(isTest && !isStackBlitz ? angularVitestPlugins() : []),
499
- (jit &&
500
- jitPlugin({
501
- inlineStylesExtension: pluginOptions.inlineStylesExtension,
502
- })),
503
- buildOptimizerPlugin({
504
- supportedBrowsers: pluginOptions.supportedBrowsers,
505
- jit,
506
- }),
507
- routerPlugin(),
508
- angularFullVersion < 190004 && pendingTasksPlugin(),
509
- nxFolderPlugin(),
510
- ].filter(Boolean);
511
- function findIncludes() {
512
- const workspaceRoot = normalizePath(resolve(pluginOptions.workspaceRoot));
513
- // Map include patterns to absolute workspace paths
514
- const globs = [
515
- ...pluginOptions.include.map((glob) => `${workspaceRoot}${glob}`),
516
- ];
517
- // Discover TypeScript files using tinyglobby
518
- return globSync(globs, {
519
- dot: true,
520
- absolute: true,
521
- });
522
- }
523
- function createTsConfigGetter(tsconfigOrGetter) {
524
- if (typeof tsconfigOrGetter === 'function') {
525
- return tsconfigOrGetter;
526
- }
527
- return () => tsconfigOrGetter || '';
528
- }
529
- function getTsConfigPath(root, tsconfig, isProd, isTest, isLib) {
530
- if (tsconfig && isAbsolute(tsconfig)) {
531
- if (!existsSync(tsconfig)) {
532
- console.error(`[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${tsconfig}. This causes compilation issues. Check the path or set the "tsconfig" property with an absolute path.`);
533
- }
534
- return tsconfig;
535
- }
536
- let tsconfigFilePath = './tsconfig.app.json';
537
- if (isLib) {
538
- tsconfigFilePath = isProd
539
- ? './tsconfig.lib.prod.json'
540
- : './tsconfig.lib.json';
541
- }
542
- if (isTest) {
543
- tsconfigFilePath = './tsconfig.spec.json';
544
- }
545
- if (tsconfig) {
546
- tsconfigFilePath = tsconfig;
547
- }
548
- const resolvedPath = resolve(root, tsconfigFilePath);
549
- if (!existsSync(resolvedPath)) {
550
- console.error(`[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${resolvedPath}. This causes compilation issues. Check the path or set the "tsconfig" property with an absolute path.`);
551
- }
552
- return resolvedPath;
553
- }
554
- function resolveTsConfigPath() {
555
- const tsconfigValue = pluginOptions.tsconfigGetter();
556
- return getTsConfigPath(tsConfigResolutionContext.root, tsconfigValue, tsConfigResolutionContext.isProd, isTest, tsConfigResolutionContext.isLib);
557
- }
558
- /**
559
- * Perform compilation using Angular's private Compilation API.
560
- *
561
- * Key differences from the standard `performCompilation` path:
562
- * 1. The compilation instance is reused across rebuilds (nullish-coalescing
563
- * assignment below) so Angular retains prior state and can diff it to
564
- * produce `templateUpdates` for HMR.
565
- * 2. `ids` (modified files) are forwarded to both the source-file cache and
566
- * `angularCompilation.update()` so that incremental re-analysis is
567
- * scoped to what actually changed.
568
- * 3. `fileReplacements` are converted and passed into Angular's host via
569
- * `toAngularCompilationFileReplacements`.
570
- * 4. `templateUpdates` from the compilation result are mapped back to
571
- * file-level HMR metadata (`hmrUpdateCode`, `hmrEligible`, `classNames`).
572
- */
573
- async function performAngularCompilation(config, ids) {
574
- // Reuse the existing instance so Angular can diff against prior state.
575
- angularCompilation ??= await createAngularCompilation(!!pluginOptions.jit, false);
576
- const modifiedFiles = ids?.length
577
- ? new Set(ids.map((file) => normalizePath(file)))
578
- : undefined;
579
- if (modifiedFiles?.size) {
580
- sourceFileCache.invalidate(modifiedFiles);
581
- }
582
- // Notify Angular of modified files before re-initialization so it can
583
- // scope its incremental analysis.
584
- if (modifiedFiles?.size && angularCompilation.update) {
585
- await angularCompilation.update(modifiedFiles);
586
- }
587
- const resolvedTsConfigPath = resolveTsConfigPath();
588
- const compilationResult = await angularCompilation.initialize(resolvedTsConfigPath, {
589
- // Convert Analog's browser-style `{ replace, with }` entries into the
590
- // `Record<string, string>` shape that Angular's AngularHostOptions
591
- // expects. SSR-only replacements (`{ replace, ssr }`) are intentionally
592
- // excluded — they stay on the Vite runtime side.
593
- fileReplacements: toAngularCompilationFileReplacements(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
594
- modifiedFiles,
595
- async transformStylesheet(data, containingFile, resourceFile, order, className) {
596
- if (pluginOptions.liveReload) {
597
- const id = createHash('sha256')
598
- .update(containingFile)
599
- .update(className)
600
- .update(String(order))
601
- .update(data)
602
- .digest('hex');
603
- const filename = id + '.' + pluginOptions.inlineStylesExtension;
604
- inlineComponentStyles.set(filename, data);
605
- return filename;
606
- }
607
- const filename = resourceFile ??
608
- containingFile.replace('.ts', `.${options?.inlineStylesExtension}`);
609
- let stylesheetResult;
610
- try {
611
- stylesheetResult = await preprocessCSS(data, `${filename}?direct`, resolvedConfig);
612
- }
613
- catch (e) {
614
- console.error(`${e}`);
615
- }
616
- return stylesheetResult?.code || '';
617
- },
618
- processWebWorker(workerFile, containingFile) {
619
- return '';
620
- },
621
- }, (tsCompilerOptions) => {
622
- if (pluginOptions.liveReload && watchMode) {
623
- tsCompilerOptions['_enableHmr'] = true;
624
- tsCompilerOptions['externalRuntimeStyles'] = true;
625
- // Workaround for https://github.com/angular/angular/issues/59310
626
- // Force extra instructions to be generated for HMR w/defer
627
- tsCompilerOptions['supportTestBed'] = true;
628
- }
629
- if (tsCompilerOptions.compilationMode === 'partial') {
630
- // These options can't be false in partial mode
631
- tsCompilerOptions['supportTestBed'] = true;
632
- tsCompilerOptions['supportJitMode'] = true;
633
- }
634
- if (!isTest && config.build?.lib) {
635
- tsCompilerOptions['declaration'] = true;
636
- tsCompilerOptions['declarationMap'] = watchMode;
637
- tsCompilerOptions['inlineSources'] = true;
638
- }
639
- if (isTest) {
640
- // Allow `TestBed.overrideXXX()` APIs.
641
- tsCompilerOptions['supportTestBed'] = true;
642
- }
643
- return tsCompilerOptions;
644
- });
645
- compilationResult.externalStylesheets?.forEach((value, key) => {
646
- externalComponentStyles?.set(`${value}.css`, key);
647
- });
648
- const diagnostics = await angularCompilation.diagnoseFiles(pluginOptions.disableTypeChecking
649
- ? DiagnosticModes.All & ~DiagnosticModes.Semantic
650
- : DiagnosticModes.All);
651
- const errors = diagnostics.errors?.length ? diagnostics.errors : [];
652
- const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];
653
- // Angular encodes template updates as `encodedFilePath@ClassName` keys.
654
- // `mapTemplateUpdatesToFiles` decodes them back to absolute file paths so
655
- // we can attach HMR metadata to the correct `EmitFileResult` below.
656
- const templateUpdates = mapTemplateUpdatesToFiles(compilationResult.templateUpdates);
657
- for (const file of await angularCompilation.emitAffectedFiles()) {
658
- const normalizedFilename = normalizePath(file.filename);
659
- const templateUpdate = templateUpdates.get(normalizedFilename);
660
- if (templateUpdate) {
661
- classNames.set(normalizedFilename, templateUpdate.className);
662
- }
663
- // Surface Angular's HMR payloads into Analog's existing live-reload
664
- // flow via the `hmrUpdateCode` / `hmrEligible` fields.
665
- outputFiles.set(normalizedFilename, {
666
- content: file.contents,
667
- dependencies: [],
668
- errors: errors.map((error) => error.text || ''),
669
- warnings: warnings.map((warning) => warning.text || ''),
670
- hmrUpdateCode: templateUpdate?.code,
671
- hmrEligible: !!templateUpdate?.code,
672
- });
673
- }
674
- }
675
- async function performCompilation(config, ids) {
676
- let resolve;
677
- const previousLock = compilationLock;
678
- compilationLock = new Promise((r) => {
679
- resolve = r;
680
- });
681
- try {
682
- await previousLock;
683
- await _doPerformCompilation(config, ids);
684
- }
685
- finally {
686
- resolve();
687
- }
688
- }
689
- /**
690
- * This method share mutable state and performs the actual compilation work.
691
- * It should not be called concurrently. Use `performCompilation` which wraps this method in a lock to ensure only one compilation runs at a time.
692
- */
693
- async function _doPerformCompilation(config, ids) {
694
- // Forward `ids` (modified files) so the Compilation API path can do
695
- // incremental re-analysis instead of a full recompile on every change.
696
- if (pluginOptions.useAngularCompilationAPI) {
697
- await performAngularCompilation(config, ids);
698
- return;
699
- }
700
- const isProd = config.mode === 'production';
701
- const modifiedFiles = new Set(ids ?? []);
702
- sourceFileCache.invalidate(modifiedFiles);
703
- if (ids?.length) {
704
- for (const id of ids || []) {
705
- fileTransformMap.delete(id);
706
- }
707
- }
708
- // Cached include discovery (invalidated only on FS events)
709
- if (pluginOptions.include.length > 0 && includeCache.length === 0) {
710
- includeCache = findIncludes();
711
- }
712
- const resolvedTsConfigPath = resolveTsConfigPath();
713
- const tsconfigKey = [
714
- resolvedTsConfigPath,
715
- isProd ? 'prod' : 'dev',
716
- isTest ? 'test' : 'app',
717
- config.build?.lib ? 'lib' : 'nolib',
718
- ].join('|');
719
- let cached = tsconfigOptionsCache.get(tsconfigKey);
720
- if (!cached) {
721
- const read = compilerCli.readConfiguration(resolvedTsConfigPath, {
722
- suppressOutputPathCheck: true,
723
- outDir: undefined,
724
- sourceMap: false,
725
- inlineSourceMap: !isProd,
726
- inlineSources: !isProd,
727
- declaration: false,
728
- declarationMap: false,
729
- allowEmptyCodegenFiles: false,
730
- annotationsAs: 'decorators',
731
- enableResourceInlining: false,
732
- noEmitOnError: false,
733
- mapRoot: undefined,
734
- sourceRoot: undefined,
735
- supportTestBed: false,
736
- supportJitMode: false,
737
- });
738
- cached = { options: read.options, rootNames: read.rootNames };
739
- tsconfigOptionsCache.set(tsconfigKey, cached);
740
- }
741
- // Clone options before mutation (preserve cache purity)
742
- const tsCompilerOptions = { ...cached.options };
743
- let rootNames = [...cached.rootNames];
744
- if (pluginOptions.liveReload && watchMode) {
745
- tsCompilerOptions['_enableHmr'] = true;
746
- tsCompilerOptions['externalRuntimeStyles'] = true;
747
- // Workaround for https://github.com/angular/angular/issues/59310
748
- // Force extra instructions to be generated for HMR w/defer
749
- tsCompilerOptions['supportTestBed'] = true;
750
- }
751
- if (tsCompilerOptions['compilationMode'] === 'partial') {
752
- // These options can't be false in partial mode
753
- tsCompilerOptions['supportTestBed'] = true;
754
- tsCompilerOptions['supportJitMode'] = true;
755
- }
756
- if (!isTest && config.build?.lib) {
757
- tsCompilerOptions['declaration'] = true;
758
- tsCompilerOptions['declarationMap'] = watchMode;
759
- tsCompilerOptions['inlineSources'] = true;
760
- }
761
- if (isTest) {
762
- // Allow `TestBed.overrideXXX()` APIs.
763
- tsCompilerOptions['supportTestBed'] = true;
764
- }
765
- const replacements = pluginOptions.fileReplacements.map((rp) => join(pluginOptions.workspaceRoot, rp.ssr || rp.with));
766
- // Merge + dedupe root names
767
- rootNames = [...new Set([...rootNames, ...includeCache, ...replacements])];
768
- const hostKey = JSON.stringify(tsCompilerOptions);
769
- let host;
770
- if (cachedHost && cachedHostKey === hostKey) {
771
- host = cachedHost;
772
- }
773
- else {
774
- host = ts.createIncrementalCompilerHost(tsCompilerOptions, {
775
- ...ts.sys,
776
- readFile(path, encoding) {
777
- if (fileTransformMap.has(path)) {
778
- return fileTransformMap.get(path);
779
- }
780
- const file = ts.sys.readFile.call(null, path, encoding);
781
- if (file) {
782
- fileTransformMap.set(path, file);
783
- }
784
- return file;
785
- },
786
- });
787
- cachedHost = host;
788
- cachedHostKey = hostKey;
789
- // Only store cache if in watch mode
790
- if (watchMode) {
791
- augmentHostWithCaching(host, sourceFileCache);
792
- }
793
- }
794
- if (!jit) {
795
- inlineComponentStyles = tsCompilerOptions['externalRuntimeStyles']
796
- ? new Map()
797
- : undefined;
798
- externalComponentStyles = tsCompilerOptions['externalRuntimeStyles']
799
- ? new Map()
800
- : undefined;
801
- augmentHostWithResources(host, styleTransform, {
802
- inlineStylesExtension: pluginOptions.inlineStylesExtension,
803
- isProd,
804
- inlineComponentStyles,
805
- externalComponentStyles,
806
- sourceFileCache,
807
- });
808
- }
809
- /**
810
- * Creates a new NgtscProgram to analyze/re-analyze
811
- * the source files and create a file emitter.
812
- * This is shared between an initial build and a hot update.
813
- */
814
- let typeScriptProgram;
815
- let angularCompiler;
816
- const oldBuilder = builder ?? ts.readBuilderProgram(tsCompilerOptions, host);
817
- if (!jit) {
818
- // Create the Angular specific program that contains the Angular compiler
819
- const angularProgram = new compilerCli.NgtscProgram(rootNames, tsCompilerOptions, host, nextProgram);
820
- angularCompiler = angularProgram.compiler;
821
- typeScriptProgram = angularProgram.compiler.getCurrentProgram();
822
- augmentProgramWithVersioning(typeScriptProgram);
823
- builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, host, oldBuilder);
824
- nextProgram = angularProgram;
825
- }
826
- else {
827
- builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(rootNames, tsCompilerOptions, host, oldBuilder);
828
- typeScriptProgram = builder.getProgram();
829
- }
830
- if (!watchMode) {
831
- // When not in watch mode, the startup cost of the incremental analysis can be avoided by
832
- // using an abstract builder that only wraps a TypeScript program.
833
- builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);
834
- }
835
- if (angularCompiler) {
836
- await angularCompiler.analyzeAsync();
837
- }
838
- const beforeTransformers = jit
839
- ? [
840
- compilerCli.constructorParametersDownlevelTransform(builder.getProgram()),
841
- createJitResourceTransformer(() => builder.getProgram().getTypeChecker()),
842
- ]
843
- : [];
844
- const transformers = mergeTransformers({ before: beforeTransformers }, jit ? {} : angularCompiler.prepareEmit().transformers);
845
- const fileMetadata = getFileMetadata(builder, angularCompiler, pluginOptions.liveReload, pluginOptions.disableTypeChecking);
846
- const writeFileCallback = (_filename, content, _a, _b, sourceFiles) => {
847
- if (!sourceFiles?.length) {
848
- return;
849
- }
850
- const filename = normalizePath(sourceFiles[0].fileName);
851
- if (filename.includes('ngtypecheck.ts') || filename.includes('.d.')) {
852
- return;
853
- }
854
- const metadata = watchMode ? fileMetadata(filename) : {};
855
- outputFiles.set(filename, {
856
- content,
857
- dependencies: [],
858
- errors: metadata.errors,
859
- warnings: metadata.warnings,
860
- hmrUpdateCode: metadata.hmrUpdateCode,
861
- hmrEligible: metadata.hmrEligible,
862
- });
863
- };
864
- const writeOutputFile = (id) => {
865
- const sourceFile = builder.getSourceFile(id);
866
- if (!sourceFile) {
867
- return;
868
- }
869
- let content = '';
870
- builder.emit(sourceFile, (filename, data) => {
871
- if (/\.[cm]?js$/.test(filename)) {
872
- content = data;
873
- }
874
- if (!watchMode &&
875
- !isTest &&
876
- /\.d\.ts/.test(filename) &&
877
- !filename.includes('.ngtypecheck.')) {
878
- // output to library root instead /src
879
- const declarationPath = resolve(config.root, config.build.outDir, relative(config.root, filename)).replace('/src/', '/');
880
- const declarationFileDir = declarationPath
881
- .replace(basename(filename), '')
882
- .replace('/src/', '/');
883
- declarationFiles.push({
884
- declarationFileDir,
885
- declarationPath,
886
- data,
887
- });
888
- }
889
- }, undefined /* cancellationToken */, undefined /* emitOnlyDtsFiles */, transformers);
890
- writeFileCallback(id, content, false, undefined, [sourceFile]);
891
- if (angularCompiler) {
892
- angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);
893
- }
894
- };
895
- if (watchMode) {
896
- if (ids && ids.length > 0) {
897
- ids.forEach((id) => writeOutputFile(id));
898
- }
899
- else {
900
- /**
901
- * Only block the server from starting up
902
- * during testing.
903
- */
904
- if (isTest) {
905
- // TypeScript will loop until there are no more affected files in the program
906
- while (builder.emitNextAffectedFile(writeFileCallback, undefined, undefined, transformers)) {
907
- /* empty */
908
- }
909
- }
910
- }
911
- }
912
- if (!isTest) {
913
- /**
914
- * Perf: Output files on demand so the dev server
915
- * isn't blocked when emitting files.
916
- */
917
- outputFile = writeOutputFile;
918
- }
919
- }
1
+ import { angularFullVersion, cjt, sourceFileCache } from "./utils/devkit.js";
2
+ import { createCompilerPlugin, createRolldownCompilerPlugin } from "./compiler-plugin.js";
3
+ import { TS_EXT_REGEX, createTsConfigGetter, getTsConfigPath, isProdMode } from "./utils/plugin-config.js";
4
+ import { getJsTransformConfigKey, isRolldown } from "./utils/rolldown.js";
5
+ import { buildOptimizerPlugin } from "./angular-build-optimizer-plugin.js";
6
+ import { toJitInlineStyleId } from "./utils/jit-inline-styles.js";
7
+ import { activateDeferredDebug, applyDebugOption, debugCompiler, debugCompilerV, debugEmit, debugEmitV, debugHmr, debugHmrV, debugStyles, debugStylesV } from "./utils/debug.js";
8
+ import { resolveStylePreprocessor } from "./analog-plugin-interop.js";
9
+ import { AnalogStylesheetRegistry, preprocessStylesheet, rewriteRelativeCssImports } from "./stylesheet-registry.js";
10
+ import { jitPlugin } from "./angular-jit-plugin.js";
11
+ import { StyleUrlsResolver, TemplateUrlsResolver } from "./component-resolvers.js";
12
+ import { augmentHostWithCaching, augmentHostWithResources, augmentProgramWithVersioning, mergeTransformers } from "./host.js";
13
+ import { TsconfigResolver } from "./utils/tsconfig-resolver.js";
14
+ import { configureStylePipelineRegistry } from "./style-pipeline.js";
15
+ import { describeStylesheetContent, injectViteIgnoreForHmrMetadata, isIgnoredHmrFile, isTestWatchMode } from "./utils/compilation-shared.js";
16
+ import { toVirtualRawId } from "./utils/virtual-ids.js";
17
+ import { loadVirtualRawModule, rewriteHtmlRawImport } from "./utils/virtual-resources.js";
18
+ import { compilationAPIPlugin } from "./compilation-api/compilation-api-plugin.js";
19
+ import "./compilation-api/index.js";
20
+ import { ANGULAR_DECORATOR_CALL_RE } from "./compiler/constants.js";
21
+ import "./compiler/index.js";
22
+ import { markStylePathSafe } from "./utils/safe-module-paths.js";
23
+ import { fastCompilePlugin } from "./fast-compile-plugin.js";
24
+ import { buildStylePreprocessor, tailwindReferencePlugin, validateTailwindConfig } from "./tailwind-plugin.js";
25
+ import { encapsulationPlugin, getComponentStyleSheetMeta, isComponentStyleSheet } from "./encapsulation-plugin.js";
26
+ import { virtualModulesPlugin } from "./virtual-modules-plugin.js";
27
+ import { angularVitestPlugins } from "./angular-vitest-plugin.js";
28
+ import { cssExtensionStyleResolverPlugin } from "./utils/css-extension-resolver.js";
29
+ import { pendingTasksPlugin } from "./angular-pending-tasks.plugin.js";
30
+ import { liveReloadPlugin } from "./live-reload-plugin.js";
31
+ import { nxFolderPlugin } from "./nx-folder-plugin.js";
32
+ import { replaceFiles } from "./plugins/file-replacements.plugin.js";
33
+ import { routerPlugin } from "./router-plugin.js";
34
+ import { union } from "es-toolkit";
35
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
36
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
37
+ import * as compilerCli from "@angular/compiler-cli";
38
+ import { createRequire } from "node:module";
39
+ import { normalizePath, preprocessCSS } from "vite";
40
+ //#region packages/vite-plugin-angular/src/lib/angular-vite-plugin.ts
41
+ var require = createRequire(import.meta.url);
42
+ var classNames = /* @__PURE__ */ new Map();
43
+ function evictDeletedFileMetadata(file, { classNamesMap, fileTransformMap }) {
44
+ const normalizedFile = normalizePath(file.split("?")[0]);
45
+ classNamesMap.delete(normalizedFile);
46
+ fileTransformMap.delete(normalizedFile);
920
47
  }
921
- export function createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, performCompilation) {
922
- return async () => {
923
- invalidateFsCaches();
924
- invalidateTsconfigCaches();
925
- await performCompilation();
926
- };
48
+ function angular(options) {
49
+ applyDebugOption(options?.debug, options?.workspaceRoot);
50
+ const liveReload = options?.liveReload ?? true;
51
+ const configuredStylePreprocessor = buildStylePreprocessor(options);
52
+ /**
53
+ * Normalize plugin options so defaults
54
+ * are used for values not provided.
55
+ */
56
+ const pluginOptions = {
57
+ tsconfigGetter: createTsConfigGetter(options?.tsconfig),
58
+ workspaceRoot: options?.workspaceRoot ?? process.env["NX_WORKSPACE_ROOT"] ?? process.cwd(),
59
+ inlineStylesExtension: options?.inlineStylesExtension ?? "css",
60
+ advanced: { tsTransformers: {
61
+ before: options?.advanced?.tsTransformers?.before ?? [],
62
+ after: options?.advanced?.tsTransformers?.after ?? [],
63
+ afterDeclarations: options?.advanced?.tsTransformers?.afterDeclarations ?? []
64
+ } },
65
+ supportedBrowsers: options?.supportedBrowsers ?? ["safari 15"],
66
+ jit: options?.jit,
67
+ include: options?.include ?? [],
68
+ additionalContentDirs: options?.additionalContentDirs ?? [],
69
+ liveReload,
70
+ disableTypeChecking: options?.disableTypeChecking ?? true,
71
+ fileReplacements: options?.fileReplacements ?? [],
72
+ useAngularCompilationAPI: options?.experimental?.useAngularCompilationAPI ?? false,
73
+ fastCompile: options?.fastCompile ?? false,
74
+ fastCompileMode: options?.fastCompileMode ?? "full",
75
+ hasTailwindCss: !!options?.tailwindCss,
76
+ tailwindCss: options?.tailwindCss,
77
+ stylePreprocessor: configuredStylePreprocessor
78
+ };
79
+ let resolvedConfig;
80
+ let tsConfigResolutionContext = null;
81
+ const ts = require("typescript");
82
+ let builder;
83
+ let nextProgram;
84
+ let cachedHost;
85
+ let cachedHostKey;
86
+ const isTest = process.env.NODE_ENV === "test" || !!process.env["VITEST"];
87
+ const tsconfigResolver = new TsconfigResolver({
88
+ workspaceRoot: pluginOptions.workspaceRoot,
89
+ include: pluginOptions.include,
90
+ liveReload: pluginOptions.liveReload,
91
+ hasTailwindCss: pluginOptions.hasTailwindCss,
92
+ isTest
93
+ });
94
+ function invalidateFsCaches() {
95
+ tsconfigResolver.invalidateIncludeCache();
96
+ }
97
+ function invalidateTsconfigCaches() {
98
+ tsconfigResolver.invalidateTsconfigCaches();
99
+ cachedHost = void 0;
100
+ cachedHostKey = void 0;
101
+ }
102
+ let watchMode = false;
103
+ let testWatchMode = isTestWatchMode();
104
+ function hasViteHmrTransport() {
105
+ return resolvedConfig ? resolvedConfig.server.hmr !== false : true;
106
+ }
107
+ function shouldEnableLiveReload() {
108
+ return !!((isTest ? testWatchMode : watchMode) && pluginOptions.liveReload && hasViteHmrTransport());
109
+ }
110
+ /**
111
+ * Determines whether Angular should externalize component styles.
112
+ *
113
+ * When true, Angular emits style references (hash-based IDs) instead of
114
+ * inlining CSS strings. Vite's resolveId → load → transform pipeline
115
+ * then serves these virtual modules, allowing @tailwindcss/vite to
116
+ * process @reference directives.
117
+ *
118
+ * Required for TWO independent use-cases:
119
+ * 1. HMR — Vite needs external modules for hot replacement
120
+ * 2. Tailwind CSS (hasTailwindCss) — styles must pass through Vite's
121
+ * CSS pipeline so @tailwindcss/vite can resolve @apply directives
122
+ *
123
+ * In production builds (!watchMode), styles are NOT externalized — they
124
+ * are inlined after preprocessCSS runs eagerly in transformStylesheet.
125
+ */
126
+ function shouldExternalizeStyles() {
127
+ if (!(isTest ? testWatchMode : watchMode)) return false;
128
+ return !!(shouldEnableLiveReload() || pluginOptions.hasTailwindCss);
129
+ }
130
+ function validateNoDuplicateAnalogPlugins(config) {
131
+ const analogInstances = (config.plugins ?? []).filter((p) => p.name === "@analogjs/vite-plugin-angular");
132
+ if (analogInstances.length > 1 && !config.build?.ssr) throw new Error(`[@analogjs/vite-plugin-angular] analog() is registered ${analogInstances.length} times. Each instance creates separate style maps, causing component styles to be lost. Remove duplicate registrations.`);
133
+ }
134
+ let stylesheetRegistry;
135
+ const sourceFileCache$1 = new sourceFileCache();
136
+ const isVitestVscode = !!process.env["VITEST_VSCODE"];
137
+ const isStackBlitz = !!process.versions["webcontainer"];
138
+ const isAstroIntegration = process.env["ANALOG_ASTRO"] === "true";
139
+ const jit = typeof pluginOptions?.jit !== "undefined" ? pluginOptions.jit : isTest;
140
+ let viteServer;
141
+ const styleUrlsResolver = new StyleUrlsResolver();
142
+ const templateUrlsResolver = new TemplateUrlsResolver();
143
+ let outputFile;
144
+ const outputFiles = /* @__PURE__ */ new Map();
145
+ const normalizeEmitterLookupId = (file) => {
146
+ const normalizedFile = normalizePath(file);
147
+ if (!normalizedFile.startsWith("/@fs/")) return normalizedFile;
148
+ return normalizePath(normalizedFile.slice(4).replace(/^\/([A-Za-z]:\/)/, "$1"));
149
+ };
150
+ const describeEmitMarkers = (content) => ({
151
+ contentLength: content.length,
152
+ hasCmp: content.includes("ɵcmp"),
153
+ hasFac: content.includes("ɵfac"),
154
+ hasProv: content.includes("ɵprov"),
155
+ hasDecorate: content.includes("__decorate"),
156
+ hasMetadata: content.includes("__metadata")
157
+ });
158
+ const fileEmitter = (file) => {
159
+ const normalizedFile = normalizeEmitterLookupId(file);
160
+ const hadCachedEmit = outputFiles.has(normalizedFile);
161
+ outputFile?.(normalizedFile);
162
+ const emittedResult = outputFiles.get(normalizedFile);
163
+ debugEmitV("fileEmitter lookup", {
164
+ requestFile: file,
165
+ normalizedFile,
166
+ hadCachedEmit,
167
+ hasOutputFileHook: !!outputFile,
168
+ emitted: !!emittedResult,
169
+ knownOutputCount: outputFiles.size,
170
+ contentLength: emittedResult?.content?.length ?? 0,
171
+ errorCount: emittedResult?.errors?.length ?? 0,
172
+ warningCount: emittedResult?.warnings?.length ?? 0
173
+ });
174
+ return emittedResult;
175
+ };
176
+ let initialCompilation = false;
177
+ const declarationFiles = [];
178
+ const fileTransformMap = /* @__PURE__ */ new Map();
179
+ let styleTransform;
180
+ let pendingCompilation;
181
+ let compilationLock = Promise.resolve();
182
+ function angularPlugin() {
183
+ let isProd = false;
184
+ if (angularFullVersion < 19e4 && pluginOptions.liveReload) {
185
+ debugHmr("hmr disabled: Angular version does not support HMR APIs", {
186
+ angularVersion: angularFullVersion,
187
+ isTest
188
+ });
189
+ console.warn("[@analogjs/vite-plugin-angular]: HMR was disabled because Angular v19+ is required for externalRuntimeStyles/_enableHmr support. Detected Angular version: %s.", angularFullVersion);
190
+ pluginOptions.liveReload = false;
191
+ }
192
+ if (isTest) {
193
+ pluginOptions.liveReload = false;
194
+ debugHmr("hmr disabled", {
195
+ angularVersion: angularFullVersion,
196
+ isTest
197
+ });
198
+ }
199
+ return {
200
+ name: "@analogjs/vite-plugin-angular",
201
+ async config(config, { command }) {
202
+ activateDeferredDebug(command);
203
+ watchMode = command === "serve";
204
+ isProd = isProdMode(config.mode);
205
+ tsConfigResolutionContext = {
206
+ root: config.root || ".",
207
+ isProd,
208
+ isLib: !!config?.build?.lib
209
+ };
210
+ const preliminaryTsConfigPath = resolveTsConfigPath();
211
+ const esbuild = config.esbuild ?? false;
212
+ const oxc = config.oxc ?? false;
213
+ const defineOptions = {
214
+ ngJitMode: "false",
215
+ ngI18nClosureMode: "false",
216
+ ...watchMode ? {} : { ngDevMode: "false" }
217
+ };
218
+ const useRolldown = isRolldown();
219
+ const jsTransformConfigKey = getJsTransformConfigKey();
220
+ const jsTransformConfigValue = jsTransformConfigKey === "oxc" ? oxc : esbuild;
221
+ const rolldownOptions = { plugins: [createRolldownCompilerPlugin({
222
+ tsconfig: preliminaryTsConfigPath,
223
+ sourcemap: !isProd,
224
+ advancedOptimizations: isProd,
225
+ jit,
226
+ incremental: watchMode
227
+ }, !isAstroIntegration)] };
228
+ const esbuildOptions = {
229
+ plugins: [createCompilerPlugin({
230
+ tsconfig: preliminaryTsConfigPath,
231
+ sourcemap: !isProd,
232
+ advancedOptimizations: isProd,
233
+ jit,
234
+ incremental: watchMode
235
+ }, isTest, !isAstroIntegration)],
236
+ define: defineOptions
237
+ };
238
+ return {
239
+ [jsTransformConfigKey]: jsTransformConfigValue,
240
+ optimizeDeps: {
241
+ include: [
242
+ "rxjs/operators",
243
+ "rxjs",
244
+ "tslib"
245
+ ],
246
+ exclude: ["@angular/platform-server"],
247
+ ...useRolldown ? { rolldownOptions } : { esbuildOptions }
248
+ }
249
+ };
250
+ },
251
+ configResolved(config) {
252
+ resolvedConfig = config;
253
+ if (config.logger?.warnOnce) {
254
+ const originalWarnOnce = config.logger.warnOnce;
255
+ config.logger.warnOnce = (msg, options) => {
256
+ if (typeof msg === "string" && msg.includes("Sourcemap") && msg.includes("node_modules")) return;
257
+ originalWarnOnce(msg, options);
258
+ };
259
+ }
260
+ if (pluginOptions.hasTailwindCss) {
261
+ validateTailwindConfig(pluginOptions.tailwindCss, config, watchMode);
262
+ validateNoDuplicateAnalogPlugins(config);
263
+ }
264
+ if (!jit) styleTransform = (code, filename) => preprocessCSS(code, filename, config);
265
+ if (isTest) testWatchMode = !(config.server.watch === null) || config.test?.watch === true || testWatchMode;
266
+ },
267
+ configureServer(server) {
268
+ viteServer = server;
269
+ const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, () => performCompilation(resolvedConfig));
270
+ server.watcher.on("add", invalidateCompilationOnFsChange);
271
+ server.watcher.on("unlink", (file) => {
272
+ evictDeletedFileMetadata(file, {
273
+ classNamesMap: classNames,
274
+ fileTransformMap
275
+ });
276
+ return invalidateCompilationOnFsChange();
277
+ });
278
+ server.watcher.on("change", (file) => {
279
+ if (file.includes("tsconfig")) invalidateTsconfigCaches();
280
+ });
281
+ },
282
+ async buildStart() {
283
+ if (!isVitestVscode) {
284
+ pendingCompilation = performCompilation(resolvedConfig);
285
+ await pendingCompilation;
286
+ pendingCompilation = null;
287
+ initialCompilation = true;
288
+ }
289
+ },
290
+ async handleHotUpdate(ctx) {
291
+ if (isIgnoredHmrFile(ctx.file)) {
292
+ debugHmr("ignored file change", { file: ctx.file });
293
+ return [];
294
+ }
295
+ if (TS_EXT_REGEX.test(ctx.file)) {
296
+ const [fileId] = ctx.file.split("?");
297
+ debugHmr("TS file changed", {
298
+ file: ctx.file,
299
+ fileId
300
+ });
301
+ pendingCompilation = performCompilation(resolvedConfig, [fileId]);
302
+ let result;
303
+ if (shouldEnableLiveReload()) {
304
+ await pendingCompilation;
305
+ pendingCompilation = null;
306
+ result = fileEmitter(fileId);
307
+ debugHmr("TS file emitted", {
308
+ fileId,
309
+ hmrEligible: !!result?.hmrEligible,
310
+ hasClassName: !!classNames.get(fileId)
311
+ });
312
+ debugHmrV("ts hmr evaluation", {
313
+ file: ctx.file,
314
+ fileId,
315
+ hasResult: !!result,
316
+ hmrEligible: !!result?.hmrEligible,
317
+ hasClassName: !!classNames.get(fileId),
318
+ className: classNames.get(fileId),
319
+ updateCode: result?.hmrUpdateCode ? describeStylesheetContent(result.hmrUpdateCode) : void 0,
320
+ errors: result?.errors?.length ?? 0,
321
+ warnings: result?.warnings?.length ?? 0,
322
+ hint: result?.hmrEligible ? "A TS-side component change, including inline template edits, produced an Angular HMR payload." : "No Angular HMR payload was emitted for this TS change; the change may not affect component template state."
323
+ });
324
+ }
325
+ if (shouldEnableLiveReload() && result?.hmrEligible && classNames.get(fileId)) {
326
+ const relativeFileId = `${normalizePath(relative(process.cwd(), fileId))}@${classNames.get(fileId)}`;
327
+ debugHmr("sending component update", { relativeFileId });
328
+ debugHmrV("ts hmr component update payload", {
329
+ file: ctx.file,
330
+ fileId,
331
+ relativeFileId,
332
+ className: classNames.get(fileId)
333
+ });
334
+ sendHMRComponentUpdate(ctx.server, relativeFileId);
335
+ return ctx.modules.map((mod) => {
336
+ if (mod.id === ctx.file) return markModuleSelfAccepting(mod);
337
+ return mod;
338
+ });
339
+ }
340
+ }
341
+ if (/\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {
342
+ debugHmr("resource file changed", { file: ctx.file });
343
+ fileTransformMap.delete(ctx.file.split("?")[0]);
344
+ const fileModules = await getModulesForChangedFile(ctx.server, ctx.file, ctx.modules, stylesheetRegistry);
345
+ /**
346
+ * Check to see if this was a direct request
347
+ * for an external resource (styles, html).
348
+ */
349
+ const isDirect = fileModules.find((mod) => !!mod.id && mod.id.includes("?direct") && isModuleForChangedResource(mod, ctx.file, stylesheetRegistry));
350
+ const isInline = fileModules.find((mod) => !!mod.id && mod.id.includes("?inline") && isModuleForChangedResource(mod, ctx.file, stylesheetRegistry));
351
+ debugHmrV("resource direct/inline detection", {
352
+ file: ctx.file,
353
+ hasDirect: !!isDirect,
354
+ directId: isDirect?.id,
355
+ hasInline: !!isInline,
356
+ inlineId: isInline?.id
357
+ });
358
+ if (isDirect || isInline) {
359
+ if (shouldExternalizeStyles() && isDirect?.id && isDirect.file) {
360
+ const isComponentStyle = isDirect.type === "css" && isComponentStyleSheet(isDirect.id);
361
+ debugHmrV("resource direct branch", {
362
+ file: ctx.file,
363
+ directId: isDirect.id,
364
+ directType: isDirect.type,
365
+ shouldExternalize: shouldExternalizeStyles(),
366
+ isComponentStyle
367
+ });
368
+ if (isComponentStyle) {
369
+ const { encapsulation } = getComponentStyleSheetMeta(isDirect.id);
370
+ const wrapperModules = await findComponentStylesheetWrapperModules(ctx.server, ctx.file, isDirect, fileModules, stylesheetRegistry);
371
+ const stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(ctx.file, isDirect, stylesheetRegistry, wrapperModules, pluginOptions.stylePreprocessor);
372
+ debugStylesV("HMR: component stylesheet changed", {
373
+ file: isDirect.file,
374
+ encapsulation
375
+ });
376
+ debugHmrV("component stylesheet wrapper modules", {
377
+ file: ctx.file,
378
+ wrapperCount: wrapperModules.length,
379
+ wrapperIds: wrapperModules.map((mod) => mod.id),
380
+ availableModuleIds: fileModules.map((mod) => mod.id)
381
+ });
382
+ debugHmrV("component stylesheet pipeline diagnosis", stylesheetDiagnosis);
383
+ ctx.server.moduleGraph.invalidateModule(isDirect);
384
+ debugHmrV("component stylesheet direct module invalidated", {
385
+ file: ctx.file,
386
+ directModuleId: isDirect.id,
387
+ directModuleUrl: isDirect.url,
388
+ reason: "Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues."
389
+ });
390
+ const trackedWrapperRequestIds = stylesheetDiagnosis.trackedRequestIds.filter((id) => id.includes("?ngcomp="));
391
+ if (encapsulation !== "shadow" && (wrapperModules.length > 0 || trackedWrapperRequestIds.length > 0)) {
392
+ wrapperModules.forEach((mod) => ctx.server.moduleGraph.invalidateModule(mod));
393
+ debugHmrV("sending css-update for component stylesheet", {
394
+ file: ctx.file,
395
+ path: isDirect.url,
396
+ acceptedPath: isDirect.file,
397
+ wrapperCount: wrapperModules.length,
398
+ trackedWrapperRequestIds,
399
+ hint: wrapperModules.length > 0 ? "Live wrapper modules were found and invalidated before sending the CSS update." : "No live wrapper ModuleNode was available, but the wrapper request id is already tracked, so Analog is trusting the browser-visible wrapper identity and patching the direct stylesheet instead of forcing a reload."
400
+ });
401
+ sendCssUpdate(ctx.server, {
402
+ path: isDirect.url,
403
+ acceptedPath: isDirect.file
404
+ });
405
+ logComponentStylesheetHmrOutcome({
406
+ file: ctx.file,
407
+ encapsulation,
408
+ diagnosis: stylesheetDiagnosis,
409
+ outcome: "css-update",
410
+ directModuleId: isDirect.id,
411
+ wrapperIds: wrapperModules.map((mod) => mod.id)
412
+ });
413
+ return union(fileModules.filter((mod) => {
414
+ return mod.file !== ctx.file || mod.id !== isDirect.id;
415
+ }).map((mod) => {
416
+ if (mod.file === ctx.file) return markModuleSelfAccepting(mod);
417
+ return mod;
418
+ }), wrapperModules.map((mod) => markModuleSelfAccepting(mod)));
419
+ }
420
+ debugHmrV("component stylesheet hmr fallback: full reload", {
421
+ file: ctx.file,
422
+ encapsulation,
423
+ reason: trackedWrapperRequestIds.length === 0 ? "missing-wrapper-module" : encapsulation === "shadow" ? "shadow-encapsulation" : "tracked-wrapper-still-not-patchable",
424
+ directId: isDirect.id,
425
+ trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? []
426
+ });
427
+ logComponentStylesheetHmrOutcome({
428
+ file: ctx.file,
429
+ encapsulation,
430
+ diagnosis: stylesheetDiagnosis,
431
+ outcome: "full-reload",
432
+ directModuleId: isDirect.id,
433
+ wrapperIds: wrapperModules.map((mod) => mod.id)
434
+ });
435
+ sendFullReload(ctx.server, {
436
+ file: ctx.file,
437
+ encapsulation,
438
+ reason: wrapperModules.length === 0 ? "missing-wrapper-module" : "shadow-encapsulation",
439
+ directId: isDirect.id,
440
+ trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? []
441
+ });
442
+ return [];
443
+ }
444
+ }
445
+ return fileModules;
446
+ }
447
+ if (shouldEnableLiveReload() && /\.(html|htm)$/.test(ctx.file) && fileModules.length === 0) {
448
+ const ownerModules = findTemplateOwnerModules(ctx.server, ctx.file);
449
+ debugHmrV("template owner lookup", {
450
+ file: ctx.file,
451
+ ownerCount: ownerModules.length,
452
+ ownerIds: ownerModules.map((mod) => mod.id),
453
+ hint: ownerModules.length > 0 ? "The external template has candidate TS owner modules that can be recompiled for HMR." : "No TS owner modules were visible for this external template change; HMR will fall through to the generic importer path."
454
+ });
455
+ if (ownerModules.length > 0) {
456
+ const ownerIds = ownerModules.map((mod) => mod.id).filter(Boolean);
457
+ ownerModules.forEach((mod) => ctx.server.moduleGraph.invalidateModule(mod));
458
+ pendingCompilation = performCompilation(resolvedConfig, ownerIds);
459
+ await pendingCompilation;
460
+ pendingCompilation = null;
461
+ const updates = ownerIds.filter((id) => classNames.get(id));
462
+ debugHmrV("template owner recompilation result", {
463
+ file: ctx.file,
464
+ ownerIds,
465
+ updates,
466
+ updateClassNames: updates.map((id) => ({
467
+ id,
468
+ className: classNames.get(id)
469
+ })),
470
+ hint: updates.length > 0 ? "External template recompilation produced Angular component update targets." : "External template recompilation completed, but no Angular component update targets were surfaced."
471
+ });
472
+ if (updates.length > 0) {
473
+ debugHmr("template owner module invalidation", {
474
+ file: ctx.file,
475
+ ownerIds,
476
+ updateCount: updates.length
477
+ });
478
+ updates.forEach((updateId) => {
479
+ const relativeFileId = `${normalizePath(relative(process.cwd(), updateId))}@${classNames.get(updateId)}`;
480
+ sendHMRComponentUpdate(ctx.server, relativeFileId);
481
+ });
482
+ return ownerModules.map((mod) => markModuleSelfAccepting(mod));
483
+ }
484
+ }
485
+ }
486
+ const mods = [];
487
+ const updates = [];
488
+ fileModules.forEach((mod) => {
489
+ mod.importers.forEach((imp) => {
490
+ ctx.server.moduleGraph.invalidateModule(imp);
491
+ if (shouldExternalizeStyles() && classNames.get(imp.id)) updates.push(imp.id);
492
+ else mods.push(imp);
493
+ });
494
+ });
495
+ debugHmrV("resource importer analysis", {
496
+ file: ctx.file,
497
+ fileModuleCount: fileModules.length,
498
+ importerCount: fileModules.reduce((count, mod) => count + mod.importers.size, 0),
499
+ updates,
500
+ mods: mods.map((mod) => mod.id)
501
+ });
502
+ pendingCompilation = performCompilation(resolvedConfig, [...mods.map((mod) => mod.id).filter(Boolean), ...updates]);
503
+ if (updates.length > 0) {
504
+ await pendingCompilation;
505
+ pendingCompilation = null;
506
+ debugHmr("resource importer component updates", {
507
+ file: ctx.file,
508
+ updateCount: updates.length
509
+ });
510
+ updates.forEach((updateId) => {
511
+ const impRelativeFileId = `${normalizePath(relative(process.cwd(), updateId))}@${classNames.get(updateId)}`;
512
+ sendHMRComponentUpdate(ctx.server, impRelativeFileId);
513
+ });
514
+ return fileModules.map((mod) => {
515
+ if (mod.id === ctx.file) return markModuleSelfAccepting(mod);
516
+ return mod;
517
+ });
518
+ }
519
+ return mods;
520
+ }
521
+ debugHmr("full reload — unrecognized file type", { file: ctx.file });
522
+ classNames.clear();
523
+ return ctx.modules;
524
+ },
525
+ resolveId(id, importer) {
526
+ if (id.startsWith("virtual:@analogjs/vite-plugin-angular:raw:")) return `\0${id}`;
527
+ if (jit && id.startsWith("angular:jit:")) {
528
+ const filePath = normalizePath(resolve(dirname(importer), id.split(";")[1]));
529
+ if (id.includes(":style")) {
530
+ markStylePathSafe(resolvedConfig, filePath);
531
+ return filePath + "?inline";
532
+ }
533
+ return toVirtualRawId(filePath);
534
+ }
535
+ const rawRewrite = rewriteHtmlRawImport(id, importer);
536
+ if (rawRewrite) return rawRewrite;
537
+ if (/\.(css|scss|sass|less)\?inline$/.test(id) && importer) {
538
+ const filePath = id.split("?")[0];
539
+ const resolved = isAbsolute(filePath) ? normalizePath(filePath) : normalizePath(resolve(dirname(importer), filePath));
540
+ markStylePathSafe(resolvedConfig, resolved);
541
+ return resolved + "?inline";
542
+ }
543
+ if (isComponentStyleSheet(id)) {
544
+ const filename = getFilenameFromPath(id);
545
+ const search = new URL(id, "http://localhost").search;
546
+ const servedSourcePath = stylesheetRegistry?.getServedSourcePath(filename);
547
+ if (servedSourcePath) {
548
+ debugStylesV("resolveId: mapped served stylesheet to source", {
549
+ filename,
550
+ resolvedPath: servedSourcePath
551
+ });
552
+ return servedSourcePath + search;
553
+ }
554
+ if (stylesheetRegistry?.hasServed(filename)) {
555
+ debugStylesV("resolveId: kept preprocessed ID", { filename });
556
+ return id;
557
+ }
558
+ const componentStyles = stylesheetRegistry?.resolveExternalSource(filename);
559
+ if (componentStyles) {
560
+ debugStylesV("resolveId: mapped external stylesheet", {
561
+ filename,
562
+ resolvedPath: componentStyles
563
+ });
564
+ return componentStyles + new URL(id, "http://localhost").search;
565
+ }
566
+ debugStyles("resolveId: component stylesheet NOT FOUND in either map", {
567
+ filename,
568
+ inlineMapSize: stylesheetRegistry?.servedCount ?? 0,
569
+ externalMapSize: stylesheetRegistry?.externalCount ?? 0
570
+ });
571
+ }
572
+ },
573
+ async load(id) {
574
+ const rawModule = await loadVirtualRawModule(this, id);
575
+ if (rawModule !== void 0) return rawModule;
576
+ if (/\.(css|scss|sass|less)\?inline$/.test(id)) markStylePathSafe(resolvedConfig, id.split("?")[0]);
577
+ if (isComponentStyleSheet(id)) {
578
+ const filename = getFilenameFromPath(id);
579
+ const componentStyles = stylesheetRegistry?.getServedContent(filename);
580
+ if (componentStyles) {
581
+ stylesheetRegistry?.registerActiveRequest(id);
582
+ debugHmrV("stylesheet active request registered", {
583
+ requestId: id,
584
+ filename,
585
+ sourcePath: stylesheetRegistry?.resolveExternalSource(filename) ?? stylesheetRegistry?.resolveExternalSource(filename.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(filename) ?? stylesheetRegistry?.getServedSourcePath(filename.replace(/^\//, "")),
586
+ trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(stylesheetRegistry?.resolveExternalSource(filename) ?? stylesheetRegistry?.resolveExternalSource(filename.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(filename) ?? stylesheetRegistry?.getServedSourcePath(filename.replace(/^\//, "")) ?? "") ?? []
587
+ });
588
+ debugStylesV("load: served inline component stylesheet", {
589
+ filename,
590
+ length: componentStyles.length,
591
+ requestId: id,
592
+ ...describeStylesheetContent(componentStyles)
593
+ });
594
+ return componentStyles;
595
+ }
596
+ }
597
+ },
598
+ transform: {
599
+ filter: { id: {
600
+ include: [TS_EXT_REGEX],
601
+ exclude: [
602
+ /node_modules/,
603
+ "type=script",
604
+ "@ng/component"
605
+ ]
606
+ } },
607
+ async handler(code, id) {
608
+ /**
609
+ * Check for options.transformFilter
610
+ */
611
+ if (options?.transformFilter && !(options?.transformFilter(code, id) ?? true)) return;
612
+ if (pluginOptions.useAngularCompilationAPI) {
613
+ if (!ANGULAR_DECORATOR_CALL_RE.test(code)) return;
614
+ }
615
+ /**
616
+ * Skip transforming content files
617
+ */
618
+ if (id.includes("?") && id.includes("analog-content-")) return;
619
+ if (id.includes(".ts?")) id = id.replace(/\?(.*)/, "");
620
+ fileTransformMap.set(id, code);
621
+ /**
622
+ * Re-analyze on each transform
623
+ * for test(Vitest)
624
+ */
625
+ if (isTest) {
626
+ if (isVitestVscode && !initialCompilation) {
627
+ pendingCompilation = performCompilation(resolvedConfig);
628
+ initialCompilation = true;
629
+ }
630
+ const tsMod = viteServer?.moduleGraph.getModuleById(id);
631
+ if (tsMod) {
632
+ const invalidated = tsMod.lastInvalidationTimestamp;
633
+ if (testWatchMode && invalidated) pendingCompilation = performCompilation(resolvedConfig, [id]);
634
+ }
635
+ }
636
+ const hasComponent = code.includes("@Component");
637
+ debugCompilerV("transform", {
638
+ id,
639
+ codeLength: code.length,
640
+ hasComponent
641
+ });
642
+ const resolveResourceUrls = hasComponent && (watchMode || jit);
643
+ const templateUrls = resolveResourceUrls ? templateUrlsResolver.resolve(code, id) : [];
644
+ const styleUrls = resolveResourceUrls ? styleUrlsResolver.resolve(code, id) : [];
645
+ if (resolveResourceUrls && watchMode) for (const urlSet of [...templateUrls, ...styleUrls]) {
646
+ const [, absoluteFileUrl] = urlSet.split("|");
647
+ this.addWatchFile(absoluteFileUrl);
648
+ }
649
+ if (pendingCompilation) {
650
+ await pendingCompilation;
651
+ pendingCompilation = null;
652
+ }
653
+ const typescriptResult = fileEmitter(id);
654
+ if (!typescriptResult) {
655
+ debugCompilerV("transform skip (file not emitted by Angular)", { id });
656
+ const isAngular = !id.includes("@ng/component") && /(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
657
+ debugEmit("transform emit miss", {
658
+ id,
659
+ normalizedId: normalizeEmitterLookupId(id),
660
+ knownOutputCount: outputFiles.size,
661
+ hasOutputFileHook: !!outputFile,
662
+ isAngular
663
+ });
664
+ if (isAngular) this.warn(`[@analogjs/vite-plugin-angular]: "${id}" contains Angular decorators but is not in the TypeScript program. Ensure it is included in your tsconfig.`);
665
+ return;
666
+ }
667
+ if (typescriptResult.warnings && typescriptResult.warnings.length > 0) this.warn(`${typescriptResult.warnings.join("\n")}`);
668
+ if (typescriptResult.errors && typescriptResult.errors.length > 0) this.error(`${typescriptResult.errors.join("\n")}`);
669
+ let data = typescriptResult.content ?? "";
670
+ debugEmitV("transform emit hit", {
671
+ id,
672
+ normalizedId: normalizeEmitterLookupId(id),
673
+ ...describeEmitMarkers(data),
674
+ errorCount: typescriptResult.errors?.length ?? 0,
675
+ warningCount: typescriptResult.warnings?.length ?? 0
676
+ });
677
+ if (jit && data.includes("angular:jit:")) {
678
+ data = data.replace(/angular:jit:style:inline;([A-Za-z0-9+/=]*)/g, (_match, encodedStyles) => toJitInlineStyleId(encodedStyles));
679
+ templateUrls.forEach((templateUrlSet) => {
680
+ const [templateFile, resolvedTemplateUrl] = templateUrlSet.split("|");
681
+ data = data.replace(`angular:jit:template:file;${templateFile}`, toVirtualRawId(resolvedTemplateUrl));
682
+ });
683
+ styleUrls.forEach((styleUrlSet) => {
684
+ const [styleFile, resolvedStyleUrl] = styleUrlSet.split("|");
685
+ markStylePathSafe(resolvedConfig, resolvedStyleUrl);
686
+ data = data.replace(`angular:jit:style:file;${styleFile}`, resolvedStyleUrl + "?inline");
687
+ });
688
+ }
689
+ if (data.includes("HmrLoad")) {
690
+ const hasMetaUrl = data.includes("getReplaceMetadataURL");
691
+ debugHmrV("vite-ignore injection", {
692
+ id,
693
+ dataLength: data.length,
694
+ hasMetaUrl
695
+ });
696
+ if (hasMetaUrl) {
697
+ const patched = injectViteIgnoreForHmrMetadata(data);
698
+ if (patched !== data && !patched.includes("@vite-ignore")) debugHmrV("vite-ignore regex fallback", { id });
699
+ data = patched;
700
+ }
701
+ }
702
+ if (typescriptResult.map) data = data.replace(/\s*\/\/# sourceMappingURL=[^\r\n]*\s*$/, "");
703
+ return {
704
+ code: data,
705
+ map: typescriptResult.map ?? null
706
+ };
707
+ }
708
+ },
709
+ closeBundle() {
710
+ declarationFiles.forEach(({ declarationFileDir, declarationPath, data }) => {
711
+ mkdirSync(declarationFileDir, { recursive: true });
712
+ writeFileSync(declarationPath, data, "utf-8");
713
+ });
714
+ }
715
+ };
716
+ }
717
+ const compilationPlugin = pluginOptions.useAngularCompilationAPI ? compilationAPIPlugin({
718
+ tsconfigGetter: pluginOptions.tsconfigGetter,
719
+ workspaceRoot: pluginOptions.workspaceRoot,
720
+ inlineStylesExtension: pluginOptions.inlineStylesExtension,
721
+ jit,
722
+ liveReload: pluginOptions.liveReload,
723
+ disableTypeChecking: pluginOptions.disableTypeChecking,
724
+ supportedBrowsers: pluginOptions.supportedBrowsers,
725
+ transformFilter: options?.transformFilter,
726
+ fileReplacements: pluginOptions.fileReplacements,
727
+ stylePreprocessor: pluginOptions.stylePreprocessor,
728
+ stylePipeline: options?.stylePipeline,
729
+ hasTailwindCss: pluginOptions.hasTailwindCss,
730
+ tailwindCss: pluginOptions.tailwindCss,
731
+ isTest,
732
+ isAstroIntegration,
733
+ include: pluginOptions.include,
734
+ additionalContentDirs: pluginOptions.additionalContentDirs,
735
+ debug: options?.debug
736
+ }) : pluginOptions.fastCompile ? fastCompilePlugin({
737
+ tsconfigGetter: pluginOptions.tsconfigGetter,
738
+ workspaceRoot: pluginOptions.workspaceRoot,
739
+ inlineStylesExtension: pluginOptions.inlineStylesExtension,
740
+ jit,
741
+ liveReload: pluginOptions.liveReload,
742
+ supportedBrowsers: pluginOptions.supportedBrowsers,
743
+ transformFilter: options?.transformFilter,
744
+ isTest,
745
+ isAstroIntegration,
746
+ fastCompileMode: pluginOptions.fastCompileMode
747
+ }) : angularPlugin();
748
+ return [
749
+ cssExtensionStyleResolverPlugin(),
750
+ replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
751
+ virtualModulesPlugin({ jit }),
752
+ pluginOptions.hasTailwindCss && tailwindReferencePlugin({ tailwindCss: pluginOptions.tailwindCss }),
753
+ pluginOptions.liveReload && liveReloadPlugin({
754
+ classNames,
755
+ fileEmitter
756
+ }),
757
+ compilationPlugin,
758
+ !pluginOptions.fastCompile && pluginOptions.liveReload && liveReloadPlugin({
759
+ classNames,
760
+ fileEmitter
761
+ }),
762
+ ...isTest && !isStackBlitz ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map) : [],
763
+ jit && jitPlugin({ inlineStylesExtension: pluginOptions.inlineStylesExtension }),
764
+ buildOptimizerPlugin({
765
+ supportedBrowsers: pluginOptions.supportedBrowsers,
766
+ jit
767
+ }),
768
+ routerPlugin(),
769
+ angularFullVersion < 190004 && pendingTasksPlugin(),
770
+ nxFolderPlugin(),
771
+ encapsulationPlugin(shouldExternalizeStyles)
772
+ ].filter(Boolean);
773
+ function resolveTsConfigPath() {
774
+ const tsconfigValue = pluginOptions.tsconfigGetter();
775
+ return getTsConfigPath(tsConfigResolutionContext.root, tsconfigValue, tsConfigResolutionContext.isProd, isTest, tsConfigResolutionContext.isLib, pluginOptions.workspaceRoot);
776
+ }
777
+ async function performCompilation(config, ids) {
778
+ let resolve;
779
+ const previousLock = compilationLock;
780
+ compilationLock = new Promise((r) => {
781
+ resolve = r;
782
+ });
783
+ try {
784
+ await previousLock;
785
+ pluginOptions.stylePreprocessor = await resolveStylePreprocessor(config, configuredStylePreprocessor);
786
+ await _doPerformCompilation(config, ids);
787
+ } finally {
788
+ resolve();
789
+ }
790
+ }
791
+ /**
792
+ * This method share mutable state and performs the actual compilation work.
793
+ * It should not be called concurrently. Use `performCompilation` which wraps this method in a lock to ensure only one compilation runs at a time.
794
+ */
795
+ async function _doPerformCompilation(config, ids) {
796
+ const isProd = config.mode === "production";
797
+ const modifiedFiles = new Set(ids ?? []);
798
+ sourceFileCache$1.invalidate(modifiedFiles);
799
+ if (ids?.length) for (const id of ids || []) fileTransformMap.delete(id);
800
+ const resolvedTsConfigPath = resolveTsConfigPath();
801
+ const cached = tsconfigResolver.getCachedTsconfigOptions(resolvedTsConfigPath, config);
802
+ const tsCompilerOptions = { ...cached.options };
803
+ let rootNames = [...cached.rootNames];
804
+ if (shouldExternalizeStyles()) tsCompilerOptions["externalRuntimeStyles"] = true;
805
+ if (shouldEnableLiveReload()) {
806
+ tsCompilerOptions["_enableHmr"] = true;
807
+ tsCompilerOptions["supportTestBed"] = true;
808
+ }
809
+ debugCompiler("tsCompilerOptions (NgtscProgram path)", {
810
+ liveReload: pluginOptions.liveReload,
811
+ viteHmr: hasViteHmrTransport(),
812
+ shouldExternalize: shouldExternalizeStyles(),
813
+ externalRuntimeStyles: !!tsCompilerOptions["externalRuntimeStyles"],
814
+ hmrEnabled: !!tsCompilerOptions["_enableHmr"]
815
+ });
816
+ if (tsCompilerOptions["compilationMode"] === "partial") {
817
+ tsCompilerOptions["supportTestBed"] = true;
818
+ tsCompilerOptions["supportJitMode"] = true;
819
+ }
820
+ if (!isTest && config.build?.lib) {
821
+ tsCompilerOptions["declaration"] = true;
822
+ tsCompilerOptions["declarationMap"] = watchMode;
823
+ tsCompilerOptions["inlineSources"] = true;
824
+ }
825
+ if (isTest) tsCompilerOptions["supportTestBed"] = true;
826
+ const replacements = pluginOptions.fileReplacements.map((rp) => join(pluginOptions.workspaceRoot, rp.ssr || rp.with));
827
+ rootNames = union(rootNames, tsconfigResolver.ensureIncludeCache(), replacements);
828
+ const hostKey = JSON.stringify(tsCompilerOptions);
829
+ let host;
830
+ if (cachedHost && cachedHostKey === hostKey) host = cachedHost;
831
+ else {
832
+ host = ts.createIncrementalCompilerHost(tsCompilerOptions, {
833
+ ...ts.sys,
834
+ readFile(path, encoding) {
835
+ if (fileTransformMap.has(path)) return fileTransformMap.get(path);
836
+ const file = ts.sys.readFile.call(null, path, encoding);
837
+ if (file) fileTransformMap.set(path, file);
838
+ return file;
839
+ }
840
+ });
841
+ cachedHost = host;
842
+ cachedHostKey = hostKey;
843
+ if (watchMode) augmentHostWithCaching(host, sourceFileCache$1);
844
+ }
845
+ if (!jit) {
846
+ const externalizeStyles = !!tsCompilerOptions["externalRuntimeStyles"];
847
+ stylesheetRegistry = externalizeStyles ? new AnalogStylesheetRegistry() : void 0;
848
+ if (stylesheetRegistry) configureStylePipelineRegistry(pluginOptions.stylePipeline, stylesheetRegistry, { workspaceRoot: pluginOptions.workspaceRoot });
849
+ debugStyles("stylesheet registry initialized (NgtscProgram path)", { externalizeStyles });
850
+ augmentHostWithResources(host, styleTransform, {
851
+ inlineStylesExtension: pluginOptions.inlineStylesExtension,
852
+ isProd,
853
+ stylesheetRegistry,
854
+ sourceFileCache: sourceFileCache$1,
855
+ stylePreprocessor: pluginOptions.stylePreprocessor
856
+ });
857
+ }
858
+ /**
859
+ * Creates a new NgtscProgram to analyze/re-analyze
860
+ * the source files and create a file emitter.
861
+ * This is shared between an initial build and a hot update.
862
+ */
863
+ let typeScriptProgram;
864
+ let angularCompiler;
865
+ const oldBuilder = builder ?? ts.readBuilderProgram(tsCompilerOptions, host);
866
+ if (!jit) {
867
+ const angularProgram = new compilerCli.NgtscProgram(rootNames, tsCompilerOptions, host, nextProgram);
868
+ angularCompiler = angularProgram.compiler;
869
+ typeScriptProgram = angularProgram.compiler.getCurrentProgram();
870
+ augmentProgramWithVersioning(typeScriptProgram);
871
+ builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, host, oldBuilder);
872
+ nextProgram = angularProgram;
873
+ } else {
874
+ builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(rootNames, tsCompilerOptions, host, oldBuilder);
875
+ typeScriptProgram = builder.getProgram();
876
+ }
877
+ if (!watchMode) builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);
878
+ if (angularCompiler) await angularCompiler.analyzeAsync();
879
+ const transformers = mergeTransformers({ before: jit ? [compilerCli.constructorParametersDownlevelTransform(builder.getProgram()), cjt(() => builder.getProgram().getTypeChecker())] : [] }, jit ? {} : angularCompiler.prepareEmit().transformers);
880
+ const fileMetadata = getFileMetadata(builder, angularCompiler, pluginOptions.liveReload, pluginOptions.disableTypeChecking);
881
+ const writeFileCallback = (_filename, content, _a, _b, sourceFiles) => {
882
+ if (!sourceFiles?.length) return;
883
+ const filename = normalizePath(sourceFiles[0].fileName);
884
+ if (filename.includes("ngtypecheck.ts") || filename.includes(".d.") || _filename.endsWith(".d.ts") || _filename.endsWith(".d.mts") || _filename.endsWith(".d.cts")) return;
885
+ if (/\.[cm]?js\.map$/.test(_filename)) {
886
+ const existing = outputFiles.get(filename);
887
+ outputFiles.set(filename, {
888
+ ...existing ?? { dependencies: [] },
889
+ map: content
890
+ });
891
+ return;
892
+ }
893
+ const metadata = watchMode ? fileMetadata(filename) : {};
894
+ const existing = outputFiles.get(filename);
895
+ outputFiles.set(filename, {
896
+ ...existing ?? {},
897
+ content,
898
+ dependencies: [],
899
+ errors: metadata.errors,
900
+ warnings: metadata.warnings,
901
+ hmrUpdateCode: metadata.hmrUpdateCode,
902
+ hmrEligible: metadata.hmrEligible
903
+ });
904
+ debugEmitV("registered ngtsc output", {
905
+ filename,
906
+ ...describeEmitMarkers(content),
907
+ errorCount: metadata.errors?.length ?? 0,
908
+ warningCount: metadata.warnings?.length ?? 0,
909
+ hmrEligible: !!metadata.hmrEligible,
910
+ knownOutputCount: outputFiles.size
911
+ });
912
+ };
913
+ const writeOutputFile = (id) => {
914
+ const sourceFile = builder.getSourceFile(id);
915
+ if (!sourceFile) return;
916
+ let content = "";
917
+ let map;
918
+ let mapFilename;
919
+ builder.emit(sourceFile, (filename, data) => {
920
+ if (/\.[cm]?js$/.test(filename)) content = data;
921
+ if (/\.[cm]?js\.map$/.test(filename)) {
922
+ map = data;
923
+ mapFilename = filename;
924
+ }
925
+ if (!watchMode && !isTest && /\.d\.ts/.test(filename) && !filename.includes(".ngtypecheck.")) {
926
+ const declarationPath = resolve(config.root, config.build.outDir, relative(config.root, filename)).replace("/src/", "/");
927
+ const declarationFileDir = declarationPath.replace(basename(filename), "").replace("/src/", "/");
928
+ declarationFiles.push({
929
+ declarationFileDir,
930
+ declarationPath,
931
+ data
932
+ });
933
+ }
934
+ }, void 0, void 0, transformers);
935
+ writeFileCallback(id, content, false, void 0, [sourceFile]);
936
+ if (map !== void 0 && mapFilename !== void 0) writeFileCallback(mapFilename, map, false, void 0, [sourceFile]);
937
+ if (angularCompiler) angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);
938
+ };
939
+ if (watchMode) {
940
+ if (ids && ids.length > 0) ids.forEach((id) => writeOutputFile(id));
941
+ else if (isTest) while (builder.emitNextAffectedFile(writeFileCallback, void 0, void 0, transformers));
942
+ }
943
+ if (!isTest)
944
+ /**
945
+ * Perf: Output files on demand so the dev server
946
+ * isn't blocked when emitting files.
947
+ */
948
+ outputFile = writeOutputFile;
949
+ }
927
950
  }
928
- /**
929
- * Convert Analog/Angular CLI-style file replacements into the flat record
930
- * expected by `AngularHostOptions.fileReplacements`.
931
- *
932
- * Only browser replacements (`{ replace, with }`) are converted. SSR-only
933
- * replacements (`{ replace, ssr }`) are left for the Vite runtime plugin to
934
- * handle — they should not be baked into the Angular compilation host because
935
- * that would apply them to both browser and server builds.
936
- *
937
- * Relative paths are resolved against `workspaceRoot` so that the host
938
- * receives the same absolute paths it would get from the Angular CLI.
939
- */
940
- export function toAngularCompilationFileReplacements(replacements, workspaceRoot) {
941
- const mappedReplacements = replacements.flatMap((replacement) => {
942
- // Skip SSR-only entries — they use `ssr` instead of `with`.
943
- if (!('with' in replacement)) {
944
- return [];
945
- }
946
- return [
947
- [
948
- isAbsolute(replacement.replace)
949
- ? replacement.replace
950
- : resolve(workspaceRoot, replacement.replace),
951
- isAbsolute(replacement.with)
952
- ? replacement.with
953
- : resolve(workspaceRoot, replacement.with),
954
- ],
955
- ];
956
- });
957
- return mappedReplacements.length
958
- ? Object.fromEntries(mappedReplacements)
959
- : undefined;
951
+ function createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, performCompilation) {
952
+ return async () => {
953
+ invalidateFsCaches();
954
+ invalidateTsconfigCaches();
955
+ await performCompilation();
956
+ };
960
957
  }
961
958
  /**
962
- * Map Angular's `templateUpdates` (keyed by `encodedFilePath@ClassName`)
963
- * back to absolute file paths with their associated HMR code and component
964
- * class name.
965
- *
966
- * Angular's private Compilation API emits template update keys in the form
967
- * `encodeURIComponent(relativePath + '@' + className)`. We decode and resolve
968
- * them so the caller can look up updates by the same normalized absolute path
969
- * used elsewhere in the plugin (`outputFiles`, `classNames`, etc.).
970
- */
971
- export function mapTemplateUpdatesToFiles(templateUpdates) {
972
- const updatesByFile = new Map();
973
- templateUpdates?.forEach((code, encodedUpdateId) => {
974
- const [file, className = ''] = decodeURIComponent(encodedUpdateId).split('@');
975
- const resolvedFile = normalizePath(resolve(process.cwd(), file));
976
- updatesByFile.set(resolvedFile, {
977
- className,
978
- code,
979
- });
980
- });
981
- return updatesByFile;
959
+ * Returns every live Vite module that can legitimately represent a changed
960
+ * Angular resource file.
961
+ *
962
+ * For normal files, `getModulesByFile()` is enough. For Angular component
963
+ * stylesheets, it is not: the browser often holds virtual hashed requests
964
+ * (`/abc123.css?direct&ngcomp=...` and `/abc123.css?ngcomp=...`) that are no
965
+ * longer discoverable from the original source path alone. We therefore merge:
966
+ * - watcher event modules
967
+ * - module-graph modules by source file
968
+ * - registry-tracked live request ids resolved back through the module graph
969
+ */
970
+ async function getModulesForChangedFile(server, file, eventModules = [], stylesheetRegistry) {
971
+ const normalizedFile = normalizePath(file.split("?")[0]);
972
+ const modules = /* @__PURE__ */ new Map();
973
+ for (const mod of eventModules) if (mod.id) modules.set(mod.id, mod);
974
+ server.moduleGraph.getModulesByFile(normalizedFile)?.forEach((mod) => {
975
+ if (mod.id) modules.set(mod.id, mod);
976
+ });
977
+ const stylesheetRequestIds = stylesheetRegistry?.getRequestIdsForSource(normalizedFile) ?? [];
978
+ const requestIdHits = [];
979
+ for (const requestId of stylesheetRequestIds) {
980
+ const candidates = [requestId, requestId.startsWith("/") ? requestId : `/${requestId}`];
981
+ for (const candidate of candidates) {
982
+ const mod = await server.moduleGraph.getModuleByUrl(candidate) ?? server.moduleGraph.getModuleById(candidate);
983
+ requestIdHits.push({
984
+ requestId,
985
+ candidate,
986
+ via: mod?.url === candidate ? "url" : "id",
987
+ moduleId: mod?.id
988
+ });
989
+ if (mod?.id) modules.set(mod.id, mod);
990
+ }
991
+ }
992
+ debugHmrV("getModulesForChangedFile registry lookup", {
993
+ file: normalizedFile,
994
+ stylesheetRequestIds,
995
+ requestIdHits,
996
+ resolvedModuleIds: [...modules.keys()]
997
+ });
998
+ return [...modules.values()];
982
999
  }
983
- function sendHMRComponentUpdate(server, id) {
984
- server.ws.send('angular:component-update', {
985
- id: encodeURIComponent(id),
986
- timestamp: Date.now(),
987
- });
988
- classNames.delete(id);
1000
+ function isModuleForChangedResource(mod, changedFile, stylesheetRegistry) {
1001
+ const normalizedChangedFile = normalizePath(changedFile.split("?")[0]);
1002
+ if (normalizePath((mod.file ?? "").split("?")[0]) === normalizedChangedFile) return true;
1003
+ if (!mod.id) return false;
1004
+ const requestPath = getFilenameFromPath(mod.id);
1005
+ return normalizePath((stylesheetRegistry?.resolveExternalSource(requestPath) ?? stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(requestPath) ?? stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\//, "")) ?? "").split("?")[0]) === normalizedChangedFile;
989
1006
  }
990
- export function getFileMetadata(program, angularCompiler, liveReload, disableTypeChecking) {
991
- const ts = require('typescript');
992
- return (file) => {
993
- const sourceFile = program.getSourceFile(file);
994
- if (!sourceFile) {
995
- return {};
996
- }
997
- const diagnostics = getDiagnosticsForSourceFile(sourceFile, !!disableTypeChecking, program, angularCompiler);
998
- const errors = diagnostics
999
- .filter((d) => d.category === ts.DiagnosticCategory?.Error)
1000
- .map((d) => typeof d.messageText === 'object'
1001
- ? d.messageText.messageText
1002
- : d.messageText);
1003
- const warnings = diagnostics
1004
- .filter((d) => d.category === ts.DiagnosticCategory?.Warning)
1005
- .map((d) => d.messageText);
1006
- let hmrUpdateCode = undefined;
1007
- let hmrEligible = false;
1008
- if (liveReload) {
1009
- for (const node of sourceFile.statements) {
1010
- if (ts.isClassDeclaration(node) && node.name != null) {
1011
- hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node);
1012
- if (hmrUpdateCode) {
1013
- classNames.set(file, node.name.getText());
1014
- hmrEligible = true;
1015
- }
1016
- }
1017
- }
1018
- }
1019
- return { errors, warnings, hmrUpdateCode, hmrEligible };
1020
- };
1007
+ function diagnoseComponentStylesheetPipeline(changedFile, directModule, stylesheetRegistry, wrapperModules, stylePreprocessor) {
1008
+ const normalizedFile = normalizePath(changedFile.split("?")[0]);
1009
+ const sourceExists = existsSync(normalizedFile);
1010
+ const sourceCode = sourceExists ? readFileSync(normalizedFile, "utf-8") : void 0;
1011
+ const directRequestPath = directModule.id ? getFilenameFromPath(directModule.id) : void 0;
1012
+ const sourcePath = directRequestPath ? stylesheetRegistry?.resolveExternalSource(directRequestPath) ?? stylesheetRegistry?.resolveExternalSource(directRequestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(directRequestPath) ?? stylesheetRegistry?.getServedSourcePath(directRequestPath.replace(/^\//, "")) : normalizedFile;
1013
+ const registryCode = directRequestPath ? stylesheetRegistry?.getServedContent(directRequestPath) : void 0;
1014
+ const trackedRequestIds = stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? "") ?? [];
1015
+ const dependencies = stylesheetRegistry?.getDependenciesForSource(sourcePath ?? "") ?? [];
1016
+ const diagnostics = stylesheetRegistry?.getDiagnosticsForSource(sourcePath ?? "") ?? [];
1017
+ const tags = stylesheetRegistry?.getTagsForSource(sourcePath ?? "") ?? [];
1018
+ const anomalies = [];
1019
+ const hints = [];
1020
+ if (!sourceExists) {
1021
+ anomalies.push("source_file_missing");
1022
+ hints.push("The stylesheet watcher fired for a file that no longer exists on disk.");
1023
+ }
1024
+ if (!registryCode) {
1025
+ anomalies.push("registry_content_missing");
1026
+ hints.push("The stylesheet registry has no served content for the direct module request path.");
1027
+ }
1028
+ if (sourceCode && registryCode) {
1029
+ let expectedRegistryCode = preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor);
1030
+ expectedRegistryCode = rewriteRelativeCssImports(expectedRegistryCode, normalizedFile);
1031
+ if (describeStylesheetContent(expectedRegistryCode).digest !== describeStylesheetContent(registryCode).digest) {
1032
+ anomalies.push("source_registry_mismatch");
1033
+ hints.push("The source file changed, but the served stylesheet content in the registry is still stale.");
1034
+ }
1035
+ }
1036
+ if (trackedRequestIds.length === 0) {
1037
+ anomalies.push("no_tracked_requests");
1038
+ hints.push("No live stylesheet requests are tracked for this source file, so HMR has no browser-facing target.");
1039
+ }
1040
+ if (trackedRequestIds.some((id) => id.includes("?ngcomp=")) && wrapperModules.length === 0) {
1041
+ anomalies.push("tracked_wrapper_missing_from_module_graph");
1042
+ hints.push("A wrapper request id is known, but Vite did not expose a live wrapper module during this HMR pass.");
1043
+ }
1044
+ if (trackedRequestIds.every((id) => !id.includes("?ngcomp=")) && wrapperModules.length === 0) {
1045
+ anomalies.push("wrapper_not_yet_tracked");
1046
+ hints.push("Only direct stylesheet requests were tracked during this HMR pass; the wrapper request may be appearing too late.");
1047
+ }
1048
+ return {
1049
+ file: changedFile,
1050
+ sourcePath,
1051
+ source: sourceCode ? describeStylesheetContent(rewriteRelativeCssImports(preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor), normalizedFile)) : void 0,
1052
+ registry: registryCode ? describeStylesheetContent(registryCode) : void 0,
1053
+ dependencies,
1054
+ diagnostics,
1055
+ tags,
1056
+ directModuleId: directModule.id,
1057
+ directModuleUrl: directModule.url,
1058
+ trackedRequestIds,
1059
+ wrapperCount: wrapperModules.length,
1060
+ anomalies,
1061
+ hints
1062
+ };
1021
1063
  }
1022
- function getDiagnosticsForSourceFile(sourceFile, disableTypeChecking, program, angularCompiler) {
1023
- const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);
1024
- if (disableTypeChecking) {
1025
- // Syntax errors are cheap to compute and the app will not run if there are any
1026
- // So always show these types of errors regardless if type checking is disabled
1027
- return syntacticDiagnostics;
1028
- }
1029
- const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);
1030
- const angularDiagnostics = angularCompiler
1031
- ? angularCompiler.getDiagnosticsForFile(sourceFile, 1)
1032
- : [];
1033
- return [
1034
- ...syntacticDiagnostics,
1035
- ...semanticDiagnostics,
1036
- ...angularDiagnostics,
1037
- ];
1064
+ async function findComponentStylesheetWrapperModules(server, changedFile, directModule, fileModules, stylesheetRegistry) {
1065
+ const wrapperModules = /* @__PURE__ */ new Map();
1066
+ for (const mod of fileModules) if (mod.id && mod.type === "js" && isComponentStyleSheet(mod.id) && isModuleForChangedResource(mod, changedFile, stylesheetRegistry)) wrapperModules.set(mod.id, mod);
1067
+ const directRequestIds = /* @__PURE__ */ new Set();
1068
+ if (directModule.id) directRequestIds.add(directModule.id);
1069
+ if (directModule.url) directRequestIds.add(directModule.url);
1070
+ const requestPath = directModule.id ? getFilenameFromPath(directModule.id) : void 0;
1071
+ const sourcePath = requestPath ? stylesheetRegistry?.resolveExternalSource(requestPath) ?? stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(requestPath) ?? stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\//, "")) : void 0;
1072
+ for (const requestId of stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? "") ?? []) if (requestId.includes("?ngcomp=")) directRequestIds.add(requestId);
1073
+ const candidateWrapperIds = [...directRequestIds].filter((id) => id.includes("?direct&ngcomp=")).map((id) => id.replace("?direct&ngcomp=", "?ngcomp="));
1074
+ const lookupHits = [];
1075
+ for (const candidate of candidateWrapperIds) {
1076
+ const mod = await server.moduleGraph.getModuleByUrl(candidate) ?? server.moduleGraph.getModuleById(candidate);
1077
+ lookupHits.push({
1078
+ candidate,
1079
+ via: mod?.url === candidate ? "url" : mod ? "id" : void 0,
1080
+ moduleId: mod?.id,
1081
+ moduleType: mod?.type
1082
+ });
1083
+ if (mod?.id && mod.type === "js" && isComponentStyleSheet(mod.id) && isModuleForChangedResource(mod, changedFile, stylesheetRegistry)) wrapperModules.set(mod.id, mod);
1084
+ }
1085
+ debugHmrV("component stylesheet wrapper lookup", {
1086
+ file: changedFile,
1087
+ sourcePath,
1088
+ directModuleId: directModule.id,
1089
+ directModuleUrl: directModule.url,
1090
+ candidateWrapperIds,
1091
+ lookupHits
1092
+ });
1093
+ if (wrapperModules.size === 0) debugHmrV("component stylesheet wrapper lookup empty", {
1094
+ file: changedFile,
1095
+ sourcePath,
1096
+ directModuleId: directModule.id,
1097
+ directModuleUrl: directModule.url,
1098
+ candidateWrapperIds
1099
+ });
1100
+ return [...wrapperModules.values()];
1038
1101
  }
1039
- function markModuleSelfAccepting(mod) {
1040
- // support Vite 6
1041
- if ('_clientModule' in mod) {
1042
- mod['_clientModule'].isSelfAccepting = true;
1043
- }
1044
- return {
1045
- ...mod,
1046
- isSelfAccepting: true,
1047
- };
1102
+ function sendHMRComponentUpdate(server, id) {
1103
+ debugHmrV("ws send: angular component update", {
1104
+ id,
1105
+ timestamp: Date.now()
1106
+ });
1107
+ server.ws.send("angular:component-update", {
1108
+ id: encodeURIComponent(id),
1109
+ timestamp: Date.now()
1110
+ });
1111
+ classNames.delete(id);
1112
+ }
1113
+ function sendCssUpdate(server, update) {
1114
+ const timestamp = Date.now();
1115
+ debugHmrV("ws send: css-update", {
1116
+ ...update,
1117
+ timestamp
1118
+ });
1119
+ server.ws.send({
1120
+ type: "update",
1121
+ updates: [{
1122
+ type: "css-update",
1123
+ timestamp,
1124
+ path: update.path,
1125
+ acceptedPath: update.acceptedPath
1126
+ }]
1127
+ });
1048
1128
  }
1049
- function isComponentStyleSheet(id) {
1050
- return id.includes('ngcomp=');
1129
+ function sendFullReload(server, details) {
1130
+ debugHmrV("ws send: full-reload", details);
1131
+ server.ws.send("analog:debug-full-reload", details);
1132
+ server.ws.send({ type: "full-reload" });
1051
1133
  }
1052
- function getComponentStyleSheetMeta(id) {
1053
- const params = new URL(id, 'http://localhost').searchParams;
1054
- const encapsulationMapping = {
1055
- '0': 'emulated',
1056
- '2': 'none',
1057
- '3': 'shadow',
1058
- };
1059
- return {
1060
- componentId: params.get('ngcomp'),
1061
- encapsulation: encapsulationMapping[params.get('e')],
1062
- };
1134
+ function logComponentStylesheetHmrOutcome(details) {
1135
+ const pitfalls = [];
1136
+ const rejectedPreferredPaths = [];
1137
+ const hints = [];
1138
+ if (details.encapsulation === "shadow") {
1139
+ pitfalls.push("shadow-encapsulation");
1140
+ rejectedPreferredPaths.push("css-update");
1141
+ hints.push("Shadow DOM styles cannot rely on Vite CSS patching because Angular applies them inside a shadow root.");
1142
+ }
1143
+ if (details.diagnosis.anomalies.includes("wrapper_not_yet_tracked")) {
1144
+ pitfalls.push("wrapper-not-yet-tracked");
1145
+ rejectedPreferredPaths.push("css-update");
1146
+ hints.push("The direct stylesheet module exists, but the browser-visible Angular wrapper module was not available in the live graph during this HMR pass.");
1147
+ }
1148
+ if (details.diagnosis.anomalies.includes("tracked_wrapper_missing_from_module_graph")) {
1149
+ pitfalls.push("tracked-wrapper-missing-from-module-graph");
1150
+ rejectedPreferredPaths.push("css-update");
1151
+ hints.push("A wrapper request id is known, but Vite could not resolve a live wrapper module for targeted CSS HMR.");
1152
+ }
1153
+ debugHmrV("component stylesheet hmr outcome", {
1154
+ file: details.file,
1155
+ outcome: details.outcome,
1156
+ encapsulation: details.encapsulation,
1157
+ directModuleId: details.directModuleId,
1158
+ wrapperIds: details.wrapperIds ?? [],
1159
+ preferredPath: details.encapsulation === "shadow" ? "full-reload" : "css-update",
1160
+ rejectedPreferredPaths: [...new Set(rejectedPreferredPaths)],
1161
+ pitfalls: [...new Set(pitfalls)],
1162
+ anomalies: details.diagnosis.anomalies,
1163
+ hints: [...new Set([...details.diagnosis.hints, ...hints])]
1164
+ });
1165
+ }
1166
+ function findTemplateOwnerModules(server, resourceFile) {
1167
+ const candidateTsFiles = [normalizePath(resourceFile.split("?")[0]).replace(/\.(html|htm)$/i, ".ts")];
1168
+ const modules = /* @__PURE__ */ new Map();
1169
+ for (const candidate of candidateTsFiles) server.moduleGraph.getModulesByFile(candidate)?.forEach((mod) => {
1170
+ if (mod.id) modules.set(mod.id, mod);
1171
+ });
1172
+ return [...modules.values()];
1063
1173
  }
1064
1174
  /**
1065
- * Removes leading / and query string from a url path
1066
- * e.g. /foo.scss?direct&ngcomp=ng-c3153525609&e=0 returns foo.scss
1067
- * @param id
1068
- */
1069
- function getFilenameFromPath(id) {
1070
- return new URL(id, 'http://localhost').pathname.replace(/^\//, '');
1175
+ * @internal
1176
+ */
1177
+ function getFileMetadata(program, angularCompiler, hmrEnabled, disableTypeChecking) {
1178
+ const ts = require("typescript");
1179
+ return (file) => {
1180
+ const sourceFile = program.getSourceFile(file);
1181
+ if (!sourceFile) return {};
1182
+ const diagnostics = getDiagnosticsForSourceFile(sourceFile, !!disableTypeChecking, program, angularCompiler);
1183
+ const errors = diagnostics.filter((d) => d.category === ts.DiagnosticCategory?.Error).map((d) => typeof d.messageText === "object" ? d.messageText.messageText : d.messageText);
1184
+ const warnings = diagnostics.filter((d) => d.category === ts.DiagnosticCategory?.Warning).map((d) => d.messageText);
1185
+ let hmrUpdateCode = void 0;
1186
+ let hmrEligible = false;
1187
+ if (hmrEnabled) {
1188
+ for (const node of sourceFile.statements) if (ts.isClassDeclaration(node) && node.name != null) {
1189
+ hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node);
1190
+ if (hmrUpdateCode) {
1191
+ const className = node.name.getText();
1192
+ classNames.set(file, className);
1193
+ hmrEligible = true;
1194
+ debugHmr("NgtscProgram emitHmrUpdateModule", {
1195
+ file,
1196
+ className
1197
+ });
1198
+ }
1199
+ }
1200
+ }
1201
+ return {
1202
+ errors,
1203
+ warnings,
1204
+ hmrUpdateCode,
1205
+ hmrEligible
1206
+ };
1207
+ };
1208
+ }
1209
+ function getDiagnosticsForSourceFile(sourceFile, disableTypeChecking, program, angularCompiler) {
1210
+ const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);
1211
+ if (disableTypeChecking) return syntacticDiagnostics;
1212
+ const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);
1213
+ const angularDiagnostics = angularCompiler ? angularCompiler.getDiagnosticsForFile(sourceFile, 1) : [];
1214
+ return [
1215
+ ...syntacticDiagnostics,
1216
+ ...semanticDiagnostics,
1217
+ ...angularDiagnostics
1218
+ ];
1219
+ }
1220
+ function markModuleSelfAccepting(mod) {
1221
+ if ("_clientModule" in mod) mod["_clientModule"].isSelfAccepting = true;
1222
+ return {
1223
+ ...mod,
1224
+ isSelfAccepting: true
1225
+ };
1071
1226
  }
1072
1227
  /**
1073
- * Checks for vitest run from the command line
1074
- * @returns boolean
1075
- */
1076
- export function isTestWatchMode(args = process.argv) {
1077
- // vitest --run
1078
- const hasRun = args.find((arg) => arg.includes('--run'));
1079
- if (hasRun) {
1080
- return false;
1081
- }
1082
- // vitest --no-run
1083
- const hasNoRun = args.find((arg) => arg.includes('--no-run'));
1084
- if (hasNoRun) {
1085
- return true;
1086
- }
1087
- // check for --watch=false or --no-watch
1088
- const hasWatch = args.find((arg) => arg.includes('watch'));
1089
- if (hasWatch && ['false', 'no'].some((neg) => hasWatch.includes(neg))) {
1090
- return false;
1091
- }
1092
- // check for --watch false
1093
- const watchIndex = args.findIndex((arg) => arg.includes('watch'));
1094
- const watchArg = args[watchIndex + 1];
1095
- if (watchArg && watchArg === 'false') {
1096
- return false;
1097
- }
1098
- return true;
1228
+ * Removes leading / and query string from a url path
1229
+ * e.g. /foo.scss?direct&ngcomp=ng-c3153525609&e=0 returns foo.scss
1230
+ * @param id
1231
+ */
1232
+ function getFilenameFromPath(id) {
1233
+ try {
1234
+ return new URL(id, "http://localhost").pathname.replace(/^\//, "");
1235
+ } catch {
1236
+ const queryIndex = id.indexOf("?");
1237
+ return (queryIndex >= 0 ? id.slice(0, queryIndex) : id).replace(/^\//, "");
1238
+ }
1099
1239
  }
1240
+ //#endregion
1241
+ export { angular };
1242
+
1100
1243
  //# sourceMappingURL=angular-vite-plugin.js.map