@analogjs/vite-plugin-angular 3.0.0-beta.37 → 3.0.0-beta.39

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 (64) hide show
  1. package/package.json +1 -1
  2. package/src/lib/analog-plugin-interop.js +1 -1
  3. package/src/lib/angular-build-context.d.ts +215 -0
  4. package/src/lib/angular-build-context.js +361 -0
  5. package/src/lib/angular-build-context.js.map +1 -0
  6. package/src/lib/angular-build-optimizer-plugin.d.ts +6 -4
  7. package/src/lib/angular-build-optimizer-plugin.js +4 -2
  8. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  9. package/src/lib/angular-jit-plugin.d.ts +5 -3
  10. package/src/lib/angular-jit-plugin.js +14 -6
  11. package/src/lib/angular-jit-plugin.js.map +1 -1
  12. package/src/lib/angular-vite-plugin.d.ts +6 -124
  13. package/src/lib/angular-vite-plugin.js +8 -1276
  14. package/src/lib/angular-vite-plugin.js.map +1 -1
  15. package/src/lib/angular-vitest-plugin.d.ts +3 -2
  16. package/src/lib/angular-vitest-plugin.js +5 -3
  17. package/src/lib/angular-vitest-plugin.js.map +1 -1
  18. package/src/lib/companion-plugins.d.ts +7 -0
  19. package/src/lib/companion-plugins.js +38 -0
  20. package/src/lib/companion-plugins.js.map +1 -0
  21. package/src/lib/compilation-api/compilation-api-plugin.d.ts +11 -2
  22. package/src/lib/compilation-api/compilation-api-plugin.js +154 -285
  23. package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
  24. package/src/lib/component-styles-plugin.d.ts +52 -0
  25. package/src/lib/component-styles-plugin.js +353 -0
  26. package/src/lib/component-styles-plugin.js.map +1 -0
  27. package/src/lib/compose-angular-plugins.d.ts +12 -0
  28. package/src/lib/compose-angular-plugins.js +31 -0
  29. package/src/lib/compose-angular-plugins.js.map +1 -0
  30. package/src/lib/dev-server-mode-plugin.d.ts +7 -0
  31. package/src/lib/dev-server-mode-plugin.js +23 -0
  32. package/src/lib/dev-server-mode-plugin.js.map +1 -0
  33. package/src/lib/fast-compile-plugin.d.ts +3 -1
  34. package/src/lib/fast-compile-plugin.js +93 -49
  35. package/src/lib/fast-compile-plugin.js.map +1 -1
  36. package/src/lib/host.js +3 -3
  37. package/src/lib/live-reload-plugin.d.ts +3 -1
  38. package/src/lib/live-reload-plugin.js +11 -5
  39. package/src/lib/live-reload-plugin.js.map +1 -1
  40. package/src/lib/ngp-compile-plugin.d.ts +2 -1
  41. package/src/lib/ngp-compile-plugin.js +90 -24
  42. package/src/lib/ngp-compile-plugin.js.map +1 -1
  43. package/src/lib/ngtsc-compile-plugin.d.ts +23 -0
  44. package/src/lib/ngtsc-compile-plugin.js +762 -0
  45. package/src/lib/ngtsc-compile-plugin.js.map +1 -0
  46. package/src/lib/nx-folder-plugin.d.ts +6 -5
  47. package/src/lib/nx-folder-plugin.js +12 -7
  48. package/src/lib/nx-folder-plugin.js.map +1 -1
  49. package/src/lib/plugins/file-replacements.plugin.d.ts +6 -0
  50. package/src/lib/plugins/file-replacements.plugin.js +1 -0
  51. package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
  52. package/src/lib/router-plugin.d.ts +5 -1
  53. package/src/lib/router-plugin.js +13 -4
  54. package/src/lib/router-plugin.js.map +1 -1
  55. package/src/lib/utils/compilation-shared.js +1 -1
  56. package/src/lib/utils/devkit.js +1 -1
  57. package/src/lib/utils/lsp-type-checker.js +1 -1
  58. package/src/lib/utils/plugin-config.d.ts +6 -8
  59. package/src/lib/utils/plugin-config.js +8 -4
  60. package/src/lib/utils/plugin-config.js.map +1 -1
  61. package/src/lib/utils/tsconfig-resolver.js +1 -1
  62. package/src/lib/virtual-modules-plugin.d.ts +11 -3
  63. package/src/lib/virtual-modules-plugin.js +43 -12
  64. package/src/lib/virtual-modules-plugin.js.map +1 -1
@@ -1,100 +1,53 @@
1
- import { SourceFileCache, angularFullVersion, createAngularCompilation } from "../utils/devkit.js";
2
- import { activateDeferredDebug, applyDebugOption, debugCompilationApi, debugCompiler, debugEmit, debugHmr, debugHmrV, debugStyles, debugStylesV } from "../utils/debug.js";
3
- import { warnStylesheetError } from "../utils/stylesheet-warning.js";
4
- import { createCompilerPlugin, createRolldownCompilerPlugin } from "../compiler-plugin.js";
5
- import { TS_EXT_REGEX, createTsConfigGetter, getTsConfigPath } from "../utils/plugin-config.js";
6
- import { TsconfigResolver } from "../utils/tsconfig-resolver.js";
7
- import { isRolldown } from "../utils/rolldown.js";
8
1
  import { normalizeStylesheetDependencies } from "../style-preprocessor.js";
9
- import { AnalogStylesheetRegistry, preprocessStylesheetResult, registerStylesheetContent, rewriteRelativeCssImports } from "../stylesheet-registry.js";
10
- import { discoverAnalogIntegrations } from "../analog-plugin-interop.js";
11
- import { DiagnosticModes, getBrowserModeCliOverride, injectViteIgnoreForHmrMetadata, isIgnoredHmrFile, isTestWatchMode, mapTemplateUpdatesToFiles, refreshStylesheetRegistryForFile, toAngularCompilationFileReplacements } from "../utils/compilation-shared.js";
2
+ import { activateDeferredDebug, debugCompilationApi, debugCompiler, debugEmit, debugHmr, debugStyles } from "../utils/debug.js";
3
+ import { preprocessStylesheetResult, rewriteRelativeCssImports } from "../stylesheet-registry.js";
4
+ import { DiagnosticModes, injectViteIgnoreForHmrMetadata, mapTemplateUpdatesToFiles, toAngularCompilationFileReplacements } from "../utils/compilation-shared.js";
5
+ import { SourceFileCache, angularFullVersion, createAngularCompilation } from "../utils/devkit.js";
6
+ import { TS_EXT_REGEX, createDepOptimizerConfig } from "../utils/plugin-config.js";
7
+ import { createAngularBuildContext, isAngularBuildContext } from "../angular-build-context.js";
8
+ import { markModuleSelfAccepting } from "../component-styles-plugin.js";
9
+ import { loadAngularVirtualModule, resolveAngularVirtualId } from "../virtual-modules-plugin.js";
10
+ import { composeWithCompanions } from "../companion-plugins.js";
12
11
  import { createHotUpdateBatcher } from "../hot-update-batch.js";
13
- import { angularVitestPlugins } from "../angular-vitest-plugin.js";
14
- import { buildOptimizerPlugin } from "../angular-build-optimizer-plugin.js";
15
- import { jitPlugin } from "../angular-jit-plugin.js";
16
- import { liveReloadPlugin } from "../live-reload-plugin.js";
17
- import { virtualModulesPlugin } from "../virtual-modules-plugin.js";
18
- import { encapsulationPlugin } from "../encapsulation-plugin.js";
19
- import { nxFolderPlugin } from "../nx-folder-plugin.js";
20
- import { routerPlugin } from "../router-plugin.js";
21
- import { replaceFiles } from "../plugins/file-replacements.plugin.js";
22
- import { cssExtensionStyleResolverPlugin } from "../utils/css-extension-resolver.js";
23
- import { loadVirtualRawModule } from "../utils/virtual-resources.js";
24
12
  import { union } from "es-toolkit";
25
13
  import { createHash } from "node:crypto";
26
14
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
27
- import { basename, isAbsolute, join, relative, resolve } from "node:path";
28
15
  import { createRequire } from "node:module";
29
- import { normalizePath, preprocessCSS } from "vite";
16
+ import { basename, isAbsolute, join, resolve } from "node:path";
17
+ import { normalizePath } from "vite";
30
18
  //#region packages/vite-plugin-angular/src/lib/compilation-api/compilation-api-plugin.ts
31
- var ts = createRequire(import.meta.url)("typescript");
19
+ var require = createRequire(import.meta.url);
20
+ function assertSupportedCompilationApi() {
21
+ if (angularFullVersion < 200100 || typeof createAngularCompilation !== "function") throw new Error("[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.");
22
+ }
32
23
  /**
33
- * Compiles Angular applications using Angular's private Compilation API.
24
+ * Single-responsibility compiler plugin backed by Angular's `@angular/build`
25
+ * Compilation API. Can be composed with custom pipelines via `AngularBuildContext`
26
+ * or mounted with default companions via `angularCompilationPlugin()`.
34
27
  *
35
28
  * @experimental This plugin may change in future releases.
36
29
  */
37
- function angularCompilationPlugin(options = {}) {
38
- if (angularFullVersion < 200100 || typeof createAngularCompilation !== "function") throw new Error("[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.");
39
- applyDebugOption(options.debug, options.workspaceRoot);
40
- const isTest = process.env.NODE_ENV === "test" || !!process.env["VITEST"];
41
- const isStackBlitz = !!process.versions["webcontainer"];
42
- const pluginOptions = {
43
- tsconfigGetter: createTsConfigGetter(options.tsconfig),
44
- workspaceRoot: options.workspaceRoot ?? process.env["NX_WORKSPACE_ROOT"] ?? process.cwd(),
45
- inlineStylesExtension: options.inlineStylesExtension ?? "css",
46
- jit: options.jit ?? isTest,
47
- liveReload: options.liveReload ?? true,
48
- disableTypeChecking: options.disableTypeChecking ?? true,
49
- supportedBrowsers: options.supportedBrowsers ?? ["safari 15"],
50
- fileReplacements: options.fileReplacements ?? [],
51
- include: options.include ?? [],
52
- isAstroIntegration: process.env["ANALOG_ASTRO"] === "true"
53
- };
54
- let resolvedConfig;
55
- let tsConfigResolutionContext = null;
56
- let watchMode = false;
57
- let stylePreprocessor;
58
- let transformFilter;
59
- let externalizeStylesRequested = false;
30
+ function compilationApiPlugin(ctxOrOptions) {
31
+ assertSupportedCompilationApi();
32
+ const ctx = isAngularBuildContext(ctxOrOptions) ? ctxOrOptions : createAngularBuildContext({
33
+ ...ctxOrOptions,
34
+ compilationBackend: "compilation-api"
35
+ });
36
+ const ts = require("typescript");
37
+ const { isTest } = ctx.options;
60
38
  let angularCompilation;
61
39
  const sourceFileCache = new SourceFileCache();
62
40
  const outputFiles = /* @__PURE__ */ new Map();
63
- const classNames = /* @__PURE__ */ new Map();
64
- let stylesheetRegistry;
65
41
  let compilationLock = Promise.resolve();
66
42
  let pendingCompilation = null;
67
43
  let initialCompilation = false;
68
44
  let viteServer;
69
- const hotUpdates = createHotUpdateBatcher((ids) => performCompilation(resolvedConfig, ids));
70
- const tsconfigResolver = new TsconfigResolver({
71
- workspaceRoot: pluginOptions.workspaceRoot,
72
- include: pluginOptions.include,
73
- liveReload: pluginOptions.liveReload,
74
- isTest
75
- });
76
- const isVitestVscode = !!process.env["VITEST_VSCODE"];
77
- let deferInitialCompilation = isVitestVscode;
78
- let testWatchMode = isTestWatchMode();
79
- function hasViteHmrTransport() {
80
- return resolvedConfig ? resolvedConfig.server.hmr !== false : true;
81
- }
82
- function shouldEnableLiveReload() {
83
- return !!((isTest ? testWatchMode : watchMode) && pluginOptions.liveReload && hasViteHmrTransport());
84
- }
85
- function shouldExternalizeStyles() {
86
- if (!(isTest ? testWatchMode : watchMode)) return false;
87
- return !!(shouldEnableLiveReload() || externalizeStylesRequested);
88
- }
89
- function resolveTsConfigPath() {
90
- const tsconfigValue = pluginOptions.tsconfigGetter();
91
- return getTsConfigPath(tsConfigResolutionContext.root, tsconfigValue, tsConfigResolutionContext.isProd, isTest, tsConfigResolutionContext.isLib);
92
- }
45
+ const hotUpdates = createHotUpdateBatcher((ids) => performCompilation(ctx.resolvedConfig, ids));
93
46
  function resolveCompilationApiTsConfigPath(resolvedTsConfigPath, config) {
94
- const includedFiles = tsconfigResolver.ensureIncludeCache();
95
- const cached = tsconfigResolver.getCachedTsconfigOptions(resolvedTsConfigPath, config);
96
- const expandedGraphRoots = tsconfigResolver.collectExpandedTsconfigRoots(resolvedTsConfigPath, config);
97
- const mergedRootNames = union(cached.rootNames, expandedGraphRoots, includedFiles).map((file) => normalizePath(file));
47
+ const includedFiles = ctx.tsconfigResolver.ensureIncludeCache();
48
+ const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(resolvedTsConfigPath, config);
49
+ const expandedGraphRoots = ctx.tsconfigResolver.collectExpandedTsconfigRoots(resolvedTsConfigPath, config);
50
+ const mergedRootNames = union(union(cached.rootNames, expandedGraphRoots), includedFiles).map((file) => normalizePath(file));
98
51
  if (mergedRootNames.length === cached.rootNames.length) return resolvedTsConfigPath;
99
52
  const resolvedCacheDir = isAbsolute(config.cacheDir) ? config.cacheDir : resolve(config.root, config.cacheDir);
100
53
  const wrapperDir = join(resolvedCacheDir, "analog-angular", "compilation-api");
@@ -126,15 +79,29 @@ function angularCompilationPlugin(options = {}) {
126
79
  const normalizedFile = normalizeEmitterLookupId(file);
127
80
  return outputFiles.get(normalizedFile);
128
81
  };
82
+ ctx.hmr.setFileEmitter((file) => fileEmitter(file));
83
+ const compilerApi = {
84
+ angularCompiler: true,
85
+ getTsConfigPath: () => ctx.resolveTsConfigPath(),
86
+ getSourceMap: (id) => outputFiles.get(normalizePath(id))?.map,
87
+ hasEmitted: (id) => outputFiles.has(normalizeEmitterLookupId(id))
88
+ };
89
+ ctx.registerCompiler({
90
+ name: "@analogjs/vite-plugin-angular-compilation-api",
91
+ getTsConfigPath: compilerApi.getTsConfigPath,
92
+ getSourceMap: compilerApi.getSourceMap,
93
+ hasEmitted: compilerApi.hasEmitted
94
+ });
129
95
  async function performAngularCompilation(config, ids) {
130
- const compilation = angularCompilation ??= await createAngularCompilation(!!pluginOptions.jit, false);
96
+ const stylesheetRegistry = ctx.styles.ensureRegistry();
97
+ const compilation = angularCompilation ??= await createAngularCompilation(!!ctx.options.jit, false);
131
98
  const modifiedFiles = ids?.length ? new Set(ids.map((file) => normalizePath(file))) : void 0;
132
99
  if (modifiedFiles?.size) sourceFileCache.invalidate(modifiedFiles);
133
100
  if (modifiedFiles?.size && compilation.update) {
134
101
  debugCompilationApi("incremental update", { files: [...modifiedFiles] });
135
102
  await compilation.update(modifiedFiles);
136
103
  }
137
- const resolvedTsConfigPath = resolveTsConfigPath();
104
+ const resolvedTsConfigPath = ctx.resolveTsConfigPath();
138
105
  const compilationApiTsConfigPath = resolveCompilationApiTsConfigPath(resolvedTsConfigPath, config);
139
106
  debugEmit("compilation initialize", {
140
107
  resolvedTsConfigPath,
@@ -142,17 +109,17 @@ function angularCompilationPlugin(options = {}) {
142
109
  modifiedFileCount: modifiedFiles?.size ?? 0
143
110
  });
144
111
  const transformCompilerOptions = (tsCompilerOptions) => {
145
- if (shouldExternalizeStyles()) tsCompilerOptions["externalRuntimeStyles"] = true;
146
- if (shouldEnableLiveReload()) {
112
+ if (ctx.shouldExternalizeStyles()) tsCompilerOptions["externalRuntimeStyles"] = true;
113
+ if (ctx.shouldEnableLiveReload()) {
147
114
  tsCompilerOptions["_enableHmr"] = true;
148
115
  tsCompilerOptions["supportTestBed"] = true;
149
116
  }
150
117
  debugCompiler("tsCompilerOptions (compilation API)", {
151
- liveReload: pluginOptions.liveReload,
152
- viteHmr: hasViteHmrTransport(),
153
- externalizeStylesRequested,
154
- watchMode,
155
- shouldExternalize: shouldExternalizeStyles(),
118
+ liveReload: ctx.options.liveReload,
119
+ viteHmr: ctx.hasViteHmrTransport(),
120
+ externalizeStylesRequested: ctx.externalizeStylesRequested,
121
+ watchMode: ctx.watchMode,
122
+ shouldExternalize: ctx.shouldExternalizeStyles(),
156
123
  externalRuntimeStyles: !!tsCompilerOptions["externalRuntimeStyles"],
157
124
  hmrEnabled: !!tsCompilerOptions["_enableHmr"]
158
125
  });
@@ -160,77 +127,41 @@ function angularCompilationPlugin(options = {}) {
160
127
  tsCompilerOptions["supportTestBed"] = true;
161
128
  tsCompilerOptions["supportJitMode"] = true;
162
129
  }
163
- if (!isTest && resolvedConfig.build?.lib) {
130
+ if (!isTest && config.build?.lib) {
164
131
  tsCompilerOptions["declaration"] = true;
165
- tsCompilerOptions["declarationMap"] = watchMode;
132
+ tsCompilerOptions["declarationMap"] = ctx.watchMode;
166
133
  tsCompilerOptions["inlineSources"] = true;
167
134
  }
168
135
  if (isTest) tsCompilerOptions["supportTestBed"] = true;
169
136
  return tsCompilerOptions;
170
137
  };
171
138
  const compilationResult = await compilation.initialize(compilationApiTsConfigPath, {
172
- fileReplacements: toAngularCompilationFileReplacements(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
139
+ fileReplacements: toAngularCompilationFileReplacements(ctx.options.fileReplacements, ctx.options.workspaceRoot),
173
140
  modifiedFiles,
174
141
  async transformStylesheet(data, containingFile, resourceFile, order, className) {
175
- if (resourceFile && !data) data = readFileSync(resourceFile, "utf-8");
176
- const filename = resourceFile ?? containingFile.replace(".ts", `.${pluginOptions.inlineStylesExtension}`);
177
- const preprocessed = preprocessStylesheetResult(data, filename, stylePreprocessor, {
178
- filename,
142
+ if (ctx.shouldEnableLiveReload() && className && containingFile) ctx.hmr.classNames.set(normalizePath(containingFile), className);
143
+ return (await ctx.styles.transformStylesheet({
144
+ data,
179
145
  containingFile,
180
146
  resourceFile,
181
- className,
182
147
  order,
183
- inline: !resourceFile
184
- });
185
- if (shouldEnableLiveReload() && className && containingFile) classNames.set(normalizePath(containingFile), className);
186
- if (shouldExternalizeStyles()) {
187
- const stylesheetId = registerStylesheetContent(stylesheetRegistry, {
188
- code: preprocessed.code,
189
- dependencies: normalizeStylesheetDependencies(preprocessed.dependencies),
190
- diagnostics: preprocessed.diagnostics,
191
- tags: preprocessed.tags,
192
- containingFile,
193
- className,
194
- order,
195
- inlineStylesExtension: pluginOptions.inlineStylesExtension,
196
- resourceFile: resourceFile ?? void 0
197
- });
198
- debugStyles("stylesheet deferred to Vite pipeline", {
199
- stylesheetId,
200
- resourceFile: resourceFile ?? "(inline)"
201
- });
202
- return stylesheetId;
203
- }
204
- debugStyles("stylesheet processed inline via preprocessCSS", {
205
- filename,
206
- resourceFile: resourceFile ?? "(inline)",
207
- dataLength: preprocessed.code.length
208
- });
209
- let stylesheetResult;
210
- try {
211
- stylesheetResult = await preprocessCSS(preprocessed.code, `${filename}?direct`, resolvedConfig);
212
- } catch (e) {
213
- debugStyles("preprocessCSS error", {
214
- filename,
215
- resourceFile: resourceFile ?? "(inline)",
216
- error: String(e)
217
- });
218
- warnStylesheetError(resolvedConfig.logger, filename, e);
219
- }
220
- return stylesheetResult?.code || "";
148
+ className,
149
+ readMissingResource: true,
150
+ logger: config.logger
151
+ }))?.content || "";
221
152
  },
222
153
  processWebWorker(workerFile) {
223
154
  return workerFile;
224
155
  }
225
156
  }, angularFullVersion >= 220200 ? {
226
- enableHmr: shouldEnableLiveReload(),
227
- externalRuntimeStyles: shouldExternalizeStyles(),
228
- includeTestMetadata: isTest || shouldEnableLiveReload(),
157
+ enableHmr: ctx.shouldEnableLiveReload(),
158
+ externalRuntimeStyles: ctx.shouldExternalizeStyles(),
159
+ includeTestMetadata: isTest || ctx.shouldEnableLiveReload(),
229
160
  instrumentForCoverage: !isTest
230
161
  } : transformCompilerOptions);
231
162
  debugStyles("external stylesheets from compilation API", {
232
163
  count: compilationResult.externalStylesheets?.size ?? 0,
233
- hasPreprocessor: !!stylePreprocessor,
164
+ hasPreprocessor: !!ctx.stylePreprocessor,
234
165
  hasInlineMap: !!stylesheetRegistry
235
166
  });
236
167
  const preprocessStats = {
@@ -242,10 +173,10 @@ function angularCompilationPlugin(options = {}) {
242
173
  for (const [key, value] of compilationResult.externalStylesheets ?? []) {
243
174
  preprocessStats.total++;
244
175
  const angularHash = `${value}.css`;
245
- stylesheetRegistry?.registerExternalRequest(angularHash, key);
246
- if (stylesheetRegistry && stylePreprocessor && existsSync(key)) try {
176
+ stylesheetRegistry.registerExternalRequest(angularHash, key);
177
+ if (ctx.stylePreprocessor && existsSync(key)) try {
247
178
  const rawCss = readFileSync(key, "utf-8");
248
- const preprocessed = preprocessStylesheetResult(rawCss, key, stylePreprocessor);
179
+ const preprocessed = preprocessStylesheetResult(rawCss, key, ctx.stylePreprocessor);
249
180
  const servedCss = rewriteRelativeCssImports(preprocessed.code, key);
250
181
  stylesheetRegistry.registerServedStylesheet({
251
182
  publicId: angularHash,
@@ -270,7 +201,7 @@ function angularCompilationPlugin(options = {}) {
270
201
  else preprocessStats.skipped++;
271
202
  }
272
203
  debugStyles("external stylesheet preprocessing complete", preprocessStats);
273
- const diagnostics = await compilation.diagnoseFiles(pluginOptions.disableTypeChecking ? DiagnosticModes.All & ~DiagnosticModes.Semantic : DiagnosticModes.All);
204
+ const diagnostics = await compilation.diagnoseFiles(ctx.options.disableTypeChecking ? DiagnosticModes.All & ~DiagnosticModes.Semantic : DiagnosticModes.All);
274
205
  const errors = diagnostics.errors?.length ? diagnostics.errors : [];
275
206
  const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];
276
207
  const templateUpdates = mapTemplateUpdatesToFiles(compilationResult.templateUpdates);
@@ -278,7 +209,7 @@ function angularCompilationPlugin(options = {}) {
278
209
  count: templateUpdates.size,
279
210
  files: [...templateUpdates.keys()]
280
211
  });
281
- const affectedFiles = await compilation.emitAffectedFiles();
212
+ const affectedFiles = Array.from(await compilation.emitAffectedFiles());
282
213
  debugEmit("emitAffectedFiles summary", {
283
214
  count: affectedFiles.length,
284
215
  templateUpdateCount: templateUpdates.size,
@@ -287,7 +218,7 @@ function angularCompilationPlugin(options = {}) {
287
218
  for (const file of affectedFiles) {
288
219
  const normalizedFilename = normalizePath(file.filename);
289
220
  const templateUpdate = templateUpdates.get(normalizedFilename);
290
- if (templateUpdate) classNames.set(normalizedFilename, templateUpdate.className);
221
+ if (templateUpdate) ctx.hmr.classNames.set(normalizedFilename, templateUpdate.className);
291
222
  outputFiles.set(normalizedFilename, {
292
223
  content: file.contents,
293
224
  dependencies: [],
@@ -297,189 +228,130 @@ function angularCompilationPlugin(options = {}) {
297
228
  hmrEligible: !!templateUpdate?.code
298
229
  });
299
230
  }
300
- if (!watchMode && !isTest) {
231
+ if (!ctx.watchMode && !isTest) {
301
232
  await compilation.close?.();
302
233
  angularCompilation = void 0;
303
234
  }
304
235
  }
305
236
  async function performCompilation(config, ids) {
306
- let resolve;
237
+ let releaseLock;
307
238
  const previousLock = compilationLock;
308
239
  compilationLock = new Promise((r) => {
309
- resolve = r;
240
+ releaseLock = r;
310
241
  });
311
242
  try {
312
243
  await previousLock;
313
- const integrations = await discoverAnalogIntegrations(config);
314
- stylePreprocessor = integrations.stylePreprocessor;
315
- transformFilter = integrations.transformFilter;
316
- tsconfigResolver.setIntegrationIncludes(integrations.include);
317
- externalizeStylesRequested = integrations.externalizeStyles;
244
+ await ctx.refreshIntegrations(config);
318
245
  await performAngularCompilation(config, ids);
319
246
  } finally {
320
- resolve();
247
+ releaseLock();
321
248
  }
322
249
  }
323
- function isComponentStyleSheet(id) {
324
- return id.includes("ngcomp=");
325
- }
326
- function getFilenameFromPath(id) {
327
- try {
328
- return new URL(id, "http://localhost").pathname.replace(/^\//, "");
329
- } catch {
330
- const queryIndex = id.indexOf("?");
331
- return (queryIndex >= 0 ? id.slice(0, queryIndex) : id).replace(/^\//, "");
332
- }
333
- }
334
- function sendHMRComponentUpdate(server, id) {
335
- debugHmrV("ws send: angular component update", {
336
- id,
337
- timestamp: Date.now()
338
- });
339
- server.ws.send("angular:component-update", {
340
- id: encodeURIComponent(id),
341
- timestamp: Date.now()
342
- });
343
- classNames.delete(id);
344
- }
345
- const compilerPlugin = {
250
+ return {
346
251
  name: "@analogjs/vite-plugin-angular-compilation-api",
347
- api: { getTsConfigPath: resolveTsConfigPath },
252
+ api: compilerApi,
348
253
  enforce: "pre",
349
- async config(config, { command }) {
254
+ async config(config, { command, mode }) {
350
255
  activateDeferredDebug(command);
351
- watchMode = command === "serve";
352
- const isProd = config.mode === "production" || process.env.NODE_ENV === "production";
353
- tsConfigResolutionContext = {
354
- root: config.root || ".",
355
- isProd,
356
- isLib: !!config?.build?.lib
357
- };
256
+ const resolution = ctx.initConfig(config, {
257
+ command,
258
+ mode
259
+ });
358
260
  debugCompilationApi("enabled (Angular %s)", angularFullVersion);
359
261
  debugCompilationApi("esbuild/oxc disabled, Angular handles transforms");
360
- const useRolldown = isRolldown();
361
- const compilerPluginOptions = {
362
- tsconfig: resolveTsConfigPath(),
363
- sourcemap: !isProd,
364
- advancedOptimizations: isProd,
365
- jit: pluginOptions.jit,
366
- incremental: watchMode
367
- };
262
+ const preliminaryTsConfigPath = ctx.resolveTsConfigPath();
368
263
  return {
369
264
  esbuild: void 0,
370
265
  oxc: void 0,
371
- optimizeDeps: {
372
- include: [
373
- "rxjs/operators",
374
- "rxjs",
375
- "tslib"
376
- ],
377
- exclude: ["@angular/platform-server"],
378
- ...useRolldown ? { rolldownOptions: { plugins: [createRolldownCompilerPlugin(compilerPluginOptions, !pluginOptions.isAstroIntegration)] } } : { esbuildOptions: { plugins: [createCompilerPlugin(compilerPluginOptions, isTest, !pluginOptions.isAstroIntegration)] } }
379
- }
266
+ ...createDepOptimizerConfig({
267
+ tsconfig: preliminaryTsConfigPath,
268
+ isProd: resolution.isProd,
269
+ jit: ctx.options.jit,
270
+ watchMode: ctx.watchMode,
271
+ isTest: ctx.options.isTest,
272
+ isAstroIntegration: ctx.options.isAstroIntegration
273
+ })
380
274
  };
381
275
  },
382
276
  async configResolved(config) {
383
- resolvedConfig = config;
384
- stylesheetRegistry = new AnalogStylesheetRegistry();
385
- (await discoverAnalogIntegrations(config)).configureStylesheetRegistry?.(stylesheetRegistry, { workspaceRoot: pluginOptions.workspaceRoot });
277
+ await ctx.resolveConfig(config);
278
+ ctx.styles.resetRegistry(true);
386
279
  debugStyles("stylesheet registry initialized (Angular Compilation API)");
387
- if (isTest) {
388
- const browser = config.test?.browser;
389
- deferInitialCompilation = isVitestVscode || !!browser && (getBrowserModeCliOverride() ?? browser.enabled) === true;
390
- testWatchMode = !(config.server.watch === null) || config.test?.watch === true || testWatchMode;
391
- }
392
280
  },
393
281
  configureServer(server) {
394
282
  viteServer = server;
395
283
  hotUpdates.configureServer(server);
396
284
  const invalidateCompilation = async () => {
397
- tsconfigResolver.invalidateAll();
398
- await performCompilation(resolvedConfig);
285
+ ctx.tsconfigResolver.invalidateAll();
286
+ await performCompilation(ctx.resolvedConfig);
399
287
  };
400
288
  server.watcher.on("add", invalidateCompilation);
401
289
  server.watcher.on("unlink", invalidateCompilation);
402
290
  server.watcher.on("change", (file) => {
403
- if (file.includes("tsconfig")) tsconfigResolver.invalidateTsconfigCaches();
291
+ if (file.includes("tsconfig")) ctx.tsconfigResolver.invalidateTsconfigCaches();
404
292
  });
405
293
  },
406
294
  async buildStart() {
407
- if (!deferInitialCompilation) {
408
- pendingCompilation = performCompilation(resolvedConfig);
295
+ if (!ctx.deferInitialCompilation) {
296
+ pendingCompilation = performCompilation(ctx.resolvedConfig);
409
297
  await pendingCompilation;
410
298
  pendingCompilation = null;
411
299
  initialCompilation = true;
412
300
  }
413
301
  },
414
- async handleHotUpdate(ctx) {
415
- if (isIgnoredHmrFile(ctx.file)) {
416
- debugHmr("ignored file change", { file: ctx.file });
302
+ async handleHotUpdate(hmrCtx) {
303
+ if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {
304
+ debugHmr("ignored file change", { file: hmrCtx.file });
417
305
  return [];
418
306
  }
419
- if (TS_EXT_REGEX.test(ctx.file)) {
420
- const [fileId] = ctx.file.split("?");
307
+ if (TS_EXT_REGEX.test(hmrCtx.file)) {
308
+ const [fileId] = hmrCtx.file.split("?");
421
309
  debugHmr("TS file changed", {
422
- file: ctx.file,
310
+ file: hmrCtx.file,
423
311
  fileId
424
312
  });
425
- await hotUpdates.schedule(ctx.file, [fileId]);
313
+ await hotUpdates.schedule(hmrCtx.file, [fileId]);
426
314
  let result;
427
- if (shouldEnableLiveReload()) {
315
+ if (ctx.shouldEnableLiveReload()) {
428
316
  result = fileEmitter(fileId);
429
317
  debugHmr("TS file emitted", {
430
318
  fileId,
431
319
  hmrEligible: !!result?.hmrEligible,
432
- hasClassName: !!classNames.get(fileId)
320
+ hasClassName: !!ctx.hmr.classNames.get(fileId)
433
321
  });
434
322
  }
435
- if (shouldEnableLiveReload() && result?.hmrEligible && classNames.get(fileId)) {
436
- const relativeFileId = `${normalizePath(relative(process.cwd(), fileId))}@${classNames.get(fileId)}`;
323
+ if (ctx.shouldEnableLiveReload() && result?.hmrEligible && ctx.hmr.classNames.get(fileId)) {
324
+ const relativeFileId = ctx.hmr.toComponentUpdateId(fileId);
437
325
  debugHmr("sending component update", { relativeFileId });
438
- sendHMRComponentUpdate(ctx.server, relativeFileId);
439
- return ctx.modules.map((mod) => {
440
- if (mod.id === ctx.file) mod.isSelfAccepting = true;
326
+ ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);
327
+ return hmrCtx.modules.map((mod) => {
328
+ if (mod.id === hmrCtx.file) return markModuleSelfAccepting(mod);
441
329
  return mod;
442
330
  });
443
331
  }
444
332
  }
445
- if (/\.(html|htm)$/.test(ctx.file)) {
446
- debugHmr("template file changed", { file: ctx.file });
447
- pendingCompilation = performCompilation(resolvedConfig);
333
+ if (/\.(html|htm)$/.test(hmrCtx.file)) {
334
+ debugHmr("template file changed", { file: hmrCtx.file });
335
+ pendingCompilation = performCompilation(ctx.resolvedConfig);
448
336
  }
449
- if (/\.(css|less|sass|scss)$/.test(ctx.file)) {
450
- debugHmr("stylesheet file changed", { file: ctx.file });
451
- refreshStylesheetRegistryForFile(ctx.file, stylesheetRegistry, stylePreprocessor);
337
+ if (/\.(css|less|sass|scss)$/.test(hmrCtx.file)) {
338
+ debugHmr("stylesheet file changed", { file: hmrCtx.file });
339
+ ctx.styles.refreshForFile(hmrCtx.file);
452
340
  }
453
- return ctx.modules;
341
+ return hmrCtx.modules;
454
342
  },
455
- resolveId(id) {
456
- if (isComponentStyleSheet(id)) {
457
- const filename = getFilenameFromPath(id);
458
- const search = new URL(id, "http://localhost").search;
459
- const servedSourcePath = stylesheetRegistry?.getServedSourcePath(filename);
460
- if (servedSourcePath) {
461
- debugStylesV("resolveId: mapped served stylesheet to source", {
462
- filename,
463
- resolvedPath: servedSourcePath
464
- });
465
- return servedSourcePath + search;
466
- }
467
- if (stylesheetRegistry?.hasServed(filename)) return id;
468
- const componentStyles = stylesheetRegistry?.resolveExternalSource(filename);
469
- if (componentStyles) return componentStyles + new URL(id, "http://localhost").search;
470
- }
343
+ resolveId(id, importer) {
344
+ const virtualId = resolveAngularVirtualId(id, importer, {
345
+ jit: ctx.options.jit,
346
+ resolvedConfig: ctx.resolvedConfig
347
+ });
348
+ if (virtualId !== void 0) return virtualId;
349
+ return ctx.styles.resolveComponentStyleId(id);
471
350
  },
472
351
  async load(id) {
473
- const rawModule = await loadVirtualRawModule(this, id);
474
- if (rawModule !== void 0) return rawModule;
475
- if (isComponentStyleSheet(id)) {
476
- const filename = getFilenameFromPath(id);
477
- const componentStyles = stylesheetRegistry?.getServedContent(filename);
478
- if (componentStyles) {
479
- stylesheetRegistry?.registerActiveRequest(id);
480
- return componentStyles;
481
- }
482
- }
352
+ const virtualModule = await loadAngularVirtualModule(this, id, ctx.resolvedConfig);
353
+ if (virtualModule !== void 0) return virtualModule;
354
+ return ctx.styles.loadComponentStyle(id);
483
355
  },
484
356
  transform: {
485
357
  filter: { id: {
@@ -493,18 +365,18 @@ function angularCompilationPlugin(options = {}) {
493
365
  } },
494
366
  async handler(code, id) {
495
367
  if (/[?&]raw\b/.test(id)) return;
496
- if (transformFilter && !transformFilter(code, id)) return;
368
+ if (ctx.transformFilter && !ctx.transformFilter(code, id)) return;
497
369
  const isAngular = /(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
498
370
  if (id.includes(".ts?")) id = id.replace(/\?(.*)/, "");
499
371
  if (isTest) {
500
- if (deferInitialCompilation && !initialCompilation) {
501
- pendingCompilation = performCompilation(resolvedConfig);
372
+ if (ctx.deferInitialCompilation && !initialCompilation) {
373
+ pendingCompilation = performCompilation(ctx.resolvedConfig);
502
374
  initialCompilation = true;
503
375
  }
504
376
  const tsMod = viteServer?.moduleGraph.getModuleById(id);
505
377
  if (tsMod) {
506
378
  const invalidated = tsMod.lastInvalidationTimestamp;
507
- if (testWatchMode && invalidated) pendingCompilation = performCompilation(resolvedConfig, [id]);
379
+ if (ctx.testWatchMode && invalidated) pendingCompilation = performCompilation(ctx.resolvedConfig, [id]);
508
380
  }
509
381
  }
510
382
  if (pendingCompilation) {
@@ -536,32 +408,29 @@ function angularCompilationPlugin(options = {}) {
536
408
  await angularCompilation?.close?.();
537
409
  angularCompilation = void 0;
538
410
  outputFiles.clear();
539
- classNames.clear();
411
+ ctx.hmr.clear();
540
412
  sourceFileCache.clear();
541
- tsconfigResolver.invalidateAll();
542
- stylesheetRegistry = void 0;
413
+ ctx.tsconfigResolver.invalidateAll();
414
+ ctx.styles.clear();
543
415
  pendingCompilation = null;
544
416
  initialCompilation = false;
545
417
  }
546
418
  };
547
- return [
548
- cssExtensionStyleResolverPlugin(),
549
- replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
550
- virtualModulesPlugin({ jit: pluginOptions.jit }),
551
- compilerPlugin,
552
- pluginOptions.liveReload && liveReloadPlugin({
553
- classNames,
554
- fileEmitter
555
- }),
556
- ...isTest && !isStackBlitz ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map) : [],
557
- pluginOptions.jit && jitPlugin({ inlineStylesExtension: pluginOptions.inlineStylesExtension }),
558
- buildOptimizerPlugin({ jit: pluginOptions.jit }),
559
- routerPlugin(),
560
- nxFolderPlugin(),
561
- encapsulationPlugin()
562
- ].filter(Boolean);
419
+ }
420
+ /**
421
+ * Compiles Angular applications using Angular's private Compilation API.
422
+ *
423
+ * @experimental This plugin may change in future releases.
424
+ */
425
+ function angularCompilationPlugin(options = {}) {
426
+ assertSupportedCompilationApi();
427
+ const ctx = createAngularBuildContext({
428
+ ...options,
429
+ compilationBackend: "compilation-api"
430
+ });
431
+ return composeWithCompanions(ctx, compilationApiPlugin(ctx));
563
432
  }
564
433
  //#endregion
565
- export { angularCompilationPlugin };
434
+ export { angularCompilationPlugin, compilationApiPlugin };
566
435
 
567
436
  //# sourceMappingURL=compilation-api-plugin.js.map