@analogjs/vite-plugin-angular 3.0.0-beta.4 → 3.0.0-beta.40

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