@analogjs/vite-plugin-angular 3.0.0-beta.5 → 3.0.0-beta.50

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 (133) hide show
  1. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js +2 -1
  2. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js.map +1 -1
  3. package/ngp/LICENSE +21 -0
  4. package/ngp/api.mjs +46806 -0
  5. package/ngp/build.json +4 -0
  6. package/ngp/ng_analyze.cjs +601 -0
  7. package/ngp/ng_analyze_bg.wasm +0 -0
  8. package/package.json +4 -1
  9. package/src/index.d.ts +2 -0
  10. package/src/index.js +3 -1
  11. package/src/index.js.map +1 -1
  12. package/src/lib/analog-plugin-interop.js +1 -1
  13. package/src/lib/angular-build-context.d.ts +215 -0
  14. package/src/lib/angular-build-context.js +361 -0
  15. package/src/lib/angular-build-context.js.map +1 -0
  16. package/src/lib/angular-build-optimizer-plugin.d.ts +6 -4
  17. package/src/lib/angular-build-optimizer-plugin.js +24 -9
  18. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  19. package/src/lib/angular-jit-plugin.d.ts +5 -3
  20. package/src/lib/angular-jit-plugin.js +14 -6
  21. package/src/lib/angular-jit-plugin.js.map +1 -1
  22. package/src/lib/angular-vite-plugin.d.ts +6 -109
  23. package/src/lib/angular-vite-plugin.js +8 -1249
  24. package/src/lib/angular-vite-plugin.js.map +1 -1
  25. package/src/lib/angular-vitest-plugin.d.ts +3 -2
  26. package/src/lib/angular-vitest-plugin.js +6 -3
  27. package/src/lib/angular-vitest-plugin.js.map +1 -1
  28. package/src/lib/companion-plugins.d.ts +7 -0
  29. package/src/lib/companion-plugins.js +38 -0
  30. package/src/lib/companion-plugins.js.map +1 -0
  31. package/src/lib/compilation-api/compilation-api-plugin.d.ts +11 -2
  32. package/src/lib/compilation-api/compilation-api-plugin.js +154 -282
  33. package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
  34. package/src/lib/compiler/compile.d.ts +1 -1
  35. package/src/lib/compiler/compile.js +190 -145
  36. package/src/lib/compiler/compile.js.map +1 -1
  37. package/src/lib/compiler/defer.d.ts +2 -3
  38. package/src/lib/compiler/defer.js +12 -14
  39. package/src/lib/compiler/defer.js.map +1 -1
  40. package/src/lib/compiler/dts-reader.d.ts +6 -1
  41. package/src/lib/compiler/dts-reader.js +19 -10
  42. package/src/lib/compiler/dts-reader.js.map +1 -1
  43. package/src/lib/compiler/hmr.d.ts +4 -0
  44. package/src/lib/compiler/hmr.js +7 -2
  45. package/src/lib/compiler/hmr.js.map +1 -1
  46. package/src/lib/compiler/index.d.ts +2 -2
  47. package/src/lib/compiler/index.js +4 -4
  48. package/src/lib/compiler/jit-metadata.d.ts +3 -1
  49. package/src/lib/compiler/jit-metadata.js +10 -8
  50. package/src/lib/compiler/jit-metadata.js.map +1 -1
  51. package/src/lib/compiler/jit-transform.js +2 -2
  52. package/src/lib/compiler/jit-transform.js.map +1 -1
  53. package/src/lib/compiler/js-emitter.d.ts +0 -3
  54. package/src/lib/compiler/js-emitter.js +3 -21
  55. package/src/lib/compiler/js-emitter.js.map +1 -1
  56. package/src/lib/compiler/registry.d.ts +7 -1
  57. package/src/lib/compiler/registry.js +23 -3
  58. package/src/lib/compiler/registry.js.map +1 -1
  59. package/src/lib/compiler/resource-inliner.d.ts +8 -9
  60. package/src/lib/compiler/resource-inliner.js +10 -18
  61. package/src/lib/compiler/resource-inliner.js.map +1 -1
  62. package/src/lib/compiler/style-ast.d.ts +9 -1
  63. package/src/lib/compiler/style-ast.js +26 -5
  64. package/src/lib/compiler/style-ast.js.map +1 -1
  65. package/src/lib/compiler/type-elision.d.ts +4 -3
  66. package/src/lib/compiler/type-elision.js +10 -11
  67. package/src/lib/compiler/type-elision.js.map +1 -1
  68. package/src/lib/compiler/utils.d.ts +9 -7
  69. package/src/lib/compiler/utils.js +49 -9
  70. package/src/lib/compiler/utils.js.map +1 -1
  71. package/src/lib/component-scanner.d.ts +74 -0
  72. package/src/lib/component-scanner.js +178 -0
  73. package/src/lib/component-scanner.js.map +1 -0
  74. package/src/lib/component-styles-plugin.d.ts +52 -0
  75. package/src/lib/component-styles-plugin.js +353 -0
  76. package/src/lib/component-styles-plugin.js.map +1 -0
  77. package/src/lib/compose-angular-plugins.d.ts +12 -0
  78. package/src/lib/compose-angular-plugins.js +31 -0
  79. package/src/lib/compose-angular-plugins.js.map +1 -0
  80. package/src/lib/dev-server-mode-plugin.d.ts +7 -0
  81. package/src/lib/dev-server-mode-plugin.js +23 -0
  82. package/src/lib/dev-server-mode-plugin.js.map +1 -0
  83. package/src/lib/fast-compile-api.d.ts +62 -0
  84. package/src/lib/fast-compile-api.js +12 -0
  85. package/src/lib/fast-compile-api.js.map +1 -0
  86. package/src/lib/fast-compile-plugin.d.ts +6 -1
  87. package/src/lib/fast-compile-plugin.js +167 -107
  88. package/src/lib/fast-compile-plugin.js.map +1 -1
  89. package/src/lib/host.d.ts +3 -0
  90. package/src/lib/host.js +4 -2
  91. package/src/lib/host.js.map +1 -1
  92. package/src/lib/live-reload-plugin.d.ts +6 -3
  93. package/src/lib/live-reload-plugin.js +13 -6
  94. package/src/lib/live-reload-plugin.js.map +1 -1
  95. package/src/lib/ngp-compile-api.d.ts +55 -0
  96. package/src/lib/ngp-compile-api.js +12 -0
  97. package/src/lib/ngp-compile-api.js.map +1 -0
  98. package/src/lib/ngp-compile-plugin.d.ts +4 -0
  99. package/src/lib/ngp-compile-plugin.js +662 -0
  100. package/src/lib/ngp-compile-plugin.js.map +1 -0
  101. package/src/lib/ngtsc-compile-plugin.d.ts +23 -0
  102. package/src/lib/ngtsc-compile-plugin.js +778 -0
  103. package/src/lib/ngtsc-compile-plugin.js.map +1 -0
  104. package/src/lib/nx-folder-plugin.d.ts +6 -5
  105. package/src/lib/nx-folder-plugin.js +12 -7
  106. package/src/lib/nx-folder-plugin.js.map +1 -1
  107. package/src/lib/plugins/file-replacements.plugin.d.ts +6 -0
  108. package/src/lib/plugins/file-replacements.plugin.js +1 -0
  109. package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
  110. package/src/lib/router-plugin.d.ts +5 -1
  111. package/src/lib/router-plugin.js +13 -4
  112. package/src/lib/router-plugin.js.map +1 -1
  113. package/src/lib/utils/compilation-shared.js +1 -1
  114. package/src/lib/utils/devkit.js +1 -1
  115. package/src/lib/utils/hmr-component-updates.d.ts +7 -0
  116. package/src/lib/utils/hmr-component-updates.js +87 -0
  117. package/src/lib/utils/hmr-component-updates.js.map +1 -0
  118. package/src/lib/utils/lsp-type-checker.d.ts +75 -0
  119. package/src/lib/utils/lsp-type-checker.js +531 -0
  120. package/src/lib/utils/lsp-type-checker.js.map +1 -0
  121. package/src/lib/utils/ngp-host-fs.d.ts +32 -0
  122. package/src/lib/utils/ngp-host-fs.js +104 -0
  123. package/src/lib/utils/ngp-host-fs.js.map +1 -0
  124. package/src/lib/utils/plugin-config.d.ts +15 -8
  125. package/src/lib/utils/plugin-config.js +18 -5
  126. package/src/lib/utils/plugin-config.js.map +1 -1
  127. package/src/lib/utils/stylesheet-warning.d.ts +2 -0
  128. package/src/lib/utils/stylesheet-warning.js +11 -0
  129. package/src/lib/utils/stylesheet-warning.js.map +1 -0
  130. package/src/lib/utils/tsconfig-resolver.js +1 -1
  131. package/src/lib/virtual-modules-plugin.d.ts +11 -3
  132. package/src/lib/virtual-modules-plugin.js +43 -12
  133. package/src/lib/virtual-modules-plugin.js.map +1 -1
@@ -0,0 +1,662 @@
1
+ import { discoverAnalogIntegrations } from "./analog-plugin-interop.js";
2
+ import { preprocessStylesheet } from "./stylesheet-registry.js";
3
+ import { isIgnoredHmrFile } from "./utils/compilation-shared.js";
4
+ import { angularFullVersion } from "./utils/devkit.js";
5
+ import { isRolldown } from "./utils/rolldown.js";
6
+ import { TS_EXT_REGEX, createDepOptimizerConfig, getTsConfigPath, isProdMode } from "./utils/plugin-config.js";
7
+ import { createAngularBuildContext, isAngularBuildContext } from "./angular-build-context.js";
8
+ import { releaseCssPreprocessorWorkers } from "./utils/css-preprocessor-workers.js";
9
+ import { loadAngularVirtualModule, resolveAngularVirtualId } from "./virtual-modules-plugin.js";
10
+ import { ComponentScanner } from "./component-scanner.js";
11
+ import { findHmrComponentUpdates } from "./utils/hmr-component-updates.js";
12
+ import { LspTypeChecker } from "./utils/lsp-type-checker.js";
13
+ import { canonicalPath, createNgpHostFs } from "./utils/ngp-host-fs.js";
14
+ import { existsSync, promises, realpathSync } from "node:fs";
15
+ import { createRequire } from "node:module";
16
+ import { dirname, resolve } from "node:path";
17
+ import * as vite from "vite";
18
+ import * as compilerCli from "@angular/compiler-cli";
19
+ import { glob } from "tinyglobby";
20
+ import { fileURLToPath, pathToFileURL } from "node:url";
21
+ //#region packages/vite-plugin-angular/src/lib/ngp-compile-plugin.ts
22
+ /** NGP's `FileUpdateType`. */
23
+ var FILE_CREATED = 0;
24
+ var FILE_DELETED = 1;
25
+ var FILE_CHANGED = 2;
26
+ function isFastCompileOptions(value) {
27
+ return typeof value === "object" && value !== null && !isAngularBuildContext(value) && "tsconfigGetter" in value && typeof value.tsconfigGetter === "function";
28
+ }
29
+ var BUNDLED_NGP = new URL("../../ngp/", "" + import.meta.url);
30
+ /**
31
+ * @param needsHostFs Whether source formats are registered, which only the
32
+ * WebAssembly backend can read through `hostFs`.
33
+ */
34
+ async function loadNgp(tsconfig, needsHostFs) {
35
+ const nativeBinding = process.env["ANALOG_NGP_NATIVE_BINDING"];
36
+ if (nativeBinding && needsHostFs) throw new Error("[@analogjs/vite-plugin-angular]: Source formats such as TSRX can't be compiled with a native NGP analyzer build. Unset ANALOG_NGP_NATIVE_BINDING to use NGP's default WebAssembly analyzer.");
37
+ let modulePath = process.env["ANALOG_NGP_COMPILER"];
38
+ if (!modulePath) try {
39
+ modulePath = createRequire(tsconfig).resolve("@angular/ngp");
40
+ } catch {
41
+ if (angularFullVersion < 220200) throw new Error("[@analogjs/vite-plugin-angular]: compilation: 'ngp' requires Angular v22.2 or later.");
42
+ return {
43
+ api: await import(new URL("api.mjs", BUNDLED_NGP).href),
44
+ analyzerOptions: nativeBinding ? { nativeBinding } : {
45
+ backend: "wasm",
46
+ wasmBinding: fileURLToPath(new URL("ng_analyze.cjs", BUNDLED_NGP))
47
+ }
48
+ };
49
+ }
50
+ return {
51
+ api: await import(pathToFileURL(resolve(modulePath)).href),
52
+ analyzerOptions: nativeBinding ? { nativeBinding } : needsHostFs ? { backend: "wasm" } : {}
53
+ };
54
+ }
55
+ function transpile(source, filePath, map) {
56
+ return vite.transformWithOxc ? vite.transformWithOxc(source, filePath, {
57
+ lang: "ts",
58
+ sourcemap: true
59
+ }, map) : vite.transformWithEsbuild(source, filePath, {
60
+ loader: "ts",
61
+ sourcemap: true
62
+ }, map);
63
+ }
64
+ function ngpCompilePlugin(optionsOrCtx) {
65
+ const sharedCtx = isAngularBuildContext(optionsOrCtx) ? optionsOrCtx : isFastCompileOptions(optionsOrCtx) ? void 0 : createAngularBuildContext({
66
+ jit: false,
67
+ ...optionsOrCtx,
68
+ compilationBackend: "ngp"
69
+ });
70
+ const options = sharedCtx ? sharedCtx.options : optionsOrCtx;
71
+ if (options.jit || options.fastCompileMode === "partial") throw new Error("compilation: 'ngp' requires jit: false and fastCompileMode: 'full'.");
72
+ let configContext;
73
+ let resolvedConfig;
74
+ let transformFilter;
75
+ let componentRegistries = [];
76
+ let stylePreprocessor;
77
+ let watchMode = false;
78
+ let hmr = false;
79
+ let activeBuilds = 0;
80
+ let analyzer;
81
+ let compiler;
82
+ let typeChecker;
83
+ let api;
84
+ const filesByPath = /* @__PURE__ */ new Map();
85
+ const chunkContexts = /* @__PURE__ */ new Map();
86
+ const output = /* @__PURE__ */ new Map();
87
+ const emittedMaps = /* @__PURE__ */ new Map();
88
+ const sources = /* @__PURE__ */ new Map();
89
+ const dependents = /* @__PURE__ */ new Map();
90
+ const hmrUpdateCode = /* @__PURE__ */ new Map();
91
+ const classNames = sharedCtx ? sharedCtx.hmr.classNames : /* @__PURE__ */ new Map();
92
+ const fileEmitter = (file, className) => ({ hmrUpdateCode: hmrUpdateCode.get(`${file}@${className}`) });
93
+ sharedCtx?.hmr.setFileEmitter(fileEmitter);
94
+ const componentUpdates = {
95
+ classNames,
96
+ fileEmitter
97
+ };
98
+ let pending = Promise.resolve();
99
+ const excluded = [
100
+ /node_modules/,
101
+ /[?&]raw\b/,
102
+ /type=script/,
103
+ /@ng\/component/
104
+ ];
105
+ const filter = vite.createFilter(TS_EXT_REGEX, excluded);
106
+ const sourceFilter = vite.createFilter(null, excluded);
107
+ const sourceFormats = [];
108
+ const scanner = new ComponentScanner();
109
+ const sourceModules = /* @__PURE__ */ new Map();
110
+ const removals = /* @__PURE__ */ new Map();
111
+ const analyzed = /* @__PURE__ */ new Map();
112
+ const includes = /* @__PURE__ */ new Map();
113
+ const moduleFormatOf = (file) => sourceFormats.find((format) => format.test(file) && includes.get(format)?.(file));
114
+ let devServer;
115
+ const reloweredByChange = /* @__PURE__ */ new Map();
116
+ const programFileOf = (file) => {
117
+ const programFile = `${file}.ts`;
118
+ return sourceModules.has(programFile) ? programFile : void 0;
119
+ };
120
+ const sourceFileOf = (file) => sourceModules.get(file)?.sourceFile ?? file;
121
+ function resolveTsConfigPath() {
122
+ if (sharedCtx) return sharedCtx.resolveTsConfigPath();
123
+ const ctx = configContext ?? {
124
+ root: resolvedConfig?.root || ".",
125
+ isProd: isProdMode(resolvedConfig?.mode),
126
+ isLib: !!resolvedConfig?.build?.lib
127
+ };
128
+ return getTsConfigPath(ctx.root, options.tsconfigGetter(), ctx.isProd, options.isTest, ctx.isLib, options.workspaceRoot);
129
+ }
130
+ const compilerApi = {
131
+ angularCompiler: true,
132
+ getTsConfigPath: resolveTsConfigPath,
133
+ getSourceMap: (id) => emittedMaps.get(vite.normalizePath(id)),
134
+ hasEmitted: (id) => filesByPath.has(vite.normalizePath(id)),
135
+ output,
136
+ ready: () => pending,
137
+ componentUpdates,
138
+ ngp: { registerSourceFormat(format) {
139
+ if (!sourceFormats.includes(format)) {
140
+ sourceFormats.push(format);
141
+ scanner.registerSourceFormat(format);
142
+ }
143
+ } }
144
+ };
145
+ /** Lowers a module of a source format. Returns whether its TypeScript changed. */
146
+ async function lowerSourceModule(sourceFile, source, format, resolve) {
147
+ const programFile = `${sourceFile}.ts`;
148
+ if (existsSync(programFile)) throw new Error(`[@analogjs/vite-plugin-angular]: ${programFile} has the name NGP compiles ${sourceFile} as. Rename one of them.`);
149
+ const removed = removals.get(programFile);
150
+ const lowered = await format.lower(source, sourceFile, {
151
+ scanImports: (specifiers) => scanner.scanImports(specifiers, sourceFile, resolve),
152
+ resolveSelector: (className) => scanner.lookupSelector(className, sharedCtx?.componentRegistries ?? componentRegistries)
153
+ });
154
+ if (removals.get(programFile) !== removed) return false;
155
+ const changed = sourceModules.get(programFile)?.lowered.code !== lowered.code;
156
+ sourceModules.set(programFile, {
157
+ sourceFile,
158
+ source,
159
+ format,
160
+ lowered
161
+ });
162
+ return changed;
163
+ }
164
+ /** Lowers every module of the registered source formats under `root`. */
165
+ async function lowerSourceModules(root, resolve) {
166
+ scanner.reset(root);
167
+ sourceModules.clear();
168
+ const sourceRoot = vite.normalizePath(realpathSync(root));
169
+ await Promise.all(sourceFormats.map(async (format) => {
170
+ includes.set(format, vite.createFilter(format.include, "**/node_modules/**", { resolve: sourceRoot }));
171
+ const files = await glob(format.include, {
172
+ cwd: sourceRoot,
173
+ absolute: true,
174
+ ignore: ["**/node_modules/**"]
175
+ });
176
+ await Promise.all(files.map(async (file) => {
177
+ const sourceFile = canonicalPath(file);
178
+ await lowerSourceModule(sourceFile, await promises.readFile(sourceFile, "utf-8"), format, resolve);
179
+ }));
180
+ }));
181
+ analyzed.clear();
182
+ for (const [programFile, { lowered }] of sourceModules) analyzed.set(programFile, lowered.code);
183
+ }
184
+ /**
185
+ * Lowers the source modules a change to `file` affects again: the module
186
+ * itself, and those that looked up selectors in it. Returns the program
187
+ * files whose TypeScript changed.
188
+ */
189
+ async function relowerSourceModules(file, resolve) {
190
+ const affected = [file, ...scanner.importersByFile.get(file) ?? []].map(programFileOf).filter((programFile) => programFile !== void 0);
191
+ scanner.invalidate(file);
192
+ return (await Promise.all(affected.map(async (programFile) => {
193
+ const sourceModule = sourceModules.get(programFile);
194
+ if (!sourceModule) return [];
195
+ const { sourceFile, format } = sourceModule;
196
+ const source = await readSource(sourceFile);
197
+ if (source === void 0) return [];
198
+ return await lowerSourceModule(sourceFile, source, format, resolve) ? [programFile] : [];
199
+ }))).flat();
200
+ }
201
+ let sourceWork = Promise.resolve();
202
+ function withSourceLock(work) {
203
+ const run = sourceWork.catch(() => void 0).then(work);
204
+ sourceWork = run;
205
+ return run;
206
+ }
207
+ /** Sends the analyzer the lowered modules it doesn't have yet. */
208
+ async function syncProgramFiles() {
209
+ const updates = [...sourceModules].filter(([filePath, { lowered }]) => analyzed.get(filePath) !== lowered.code).map(([filePath, { lowered }]) => ({
210
+ filePath,
211
+ content: lowered.code
212
+ }));
213
+ if (updates.length === 0) return;
214
+ for (const { filePath, content } of updates) analyzed.set(filePath, content);
215
+ await enqueueIndex(() => analyzer.updateFileContent(updates));
216
+ }
217
+ /** Reads a source file, or `undefined` if it was removed. */
218
+ function readSource(file) {
219
+ return promises.readFile(file, "utf-8").catch((error) => {
220
+ if (error.code === "ENOENT") return void 0;
221
+ throw error;
222
+ });
223
+ }
224
+ /** Lowers a module added after the build started, if NGP compiles it. */
225
+ async function addSourceModule(sourceFile, format, source, resolve) {
226
+ const programFile = `${sourceFile}.ts`;
227
+ await lowerSourceModule(sourceFile, source, format, resolve);
228
+ const sourceModule = sourceModules.get(programFile);
229
+ if (!sourceModule) return;
230
+ analyzed.set(programFile, sourceModule.lowered.code);
231
+ await enqueueIndex(() => analyzer.invalidateFiles([{
232
+ filePath: programFile,
233
+ updateType: FILE_CREATED
234
+ }]));
235
+ }
236
+ /** Drops a removed module, and any lowering of it still in progress. */
237
+ async function removeSourceModule(sourceFile) {
238
+ const programFile = `${sourceFile}.ts`;
239
+ removals.set(programFile, (removals.get(programFile) ?? 0) + 1);
240
+ analyzed.delete(programFile);
241
+ if (!sourceModules.delete(programFile)) return;
242
+ await enqueueIndex(() => analyzer.invalidateFiles([{
243
+ filePath: programFile,
244
+ updateType: FILE_DELETED
245
+ }]));
246
+ }
247
+ /**
248
+ * Lowers a module for its transform, as fast compile does on every
249
+ * transform, so the selectors it looks up are current. A transform that
250
+ * started before a hot update can carry the previous code; it compiles the
251
+ * latest lowering instead.
252
+ */
253
+ async function lowerForTransform(sourceFile, format, code, resolve) {
254
+ const programFile = `${sourceFile}.ts`;
255
+ if (!sourceModules.has(programFile)) await addSourceModule(sourceFile, format, code, resolve);
256
+ else if (code === await readSource(sourceFile)) await lowerSourceModule(sourceFile, code, format, resolve);
257
+ return sourceModules.get(programFile)?.lowered;
258
+ }
259
+ /** Maps a type error in a program file to the source module's location. */
260
+ function toSourceLocation(location) {
261
+ const sourceModule = sourceModules.get(vite.normalizePath(location.file));
262
+ const mapped = sourceModule?.lowered.toSourceLocation(location.line - 1, location.character - 1);
263
+ return mapped ? {
264
+ file: sourceModule.sourceFile,
265
+ line: mapped.line + 1,
266
+ character: mapped.column + 1
267
+ } : location;
268
+ }
269
+ sharedCtx?.registerCompiler({
270
+ name: "@analogjs/vite-plugin-angular-ngp",
271
+ getTsConfigPath: compilerApi.getTsConfigPath,
272
+ getSourceMap: compilerApi.getSourceMap,
273
+ hasEmitted: compilerApi.hasEmitted
274
+ });
275
+ async function prepareResources(file, watch) {
276
+ watch(file.filePath);
277
+ const activeConfig = sharedCtx?.resolvedConfig ?? resolvedConfig;
278
+ const activeStylePreprocessor = sharedCtx?.stylePreprocessor ?? stylePreprocessor;
279
+ return {
280
+ ...file,
281
+ classes: await Promise.all(file.classes.map(async (metadata, classIndex) => {
282
+ const component = metadata.component;
283
+ if (!component) return metadata;
284
+ if (component.templateUrl) watch(component.templateUrl.resolvedPath);
285
+ for (const style of component.styleUrls ?? []) watch(style.resolvedPath);
286
+ const preprocess = async (content, path, order, inline) => {
287
+ const preprocessed = preprocessStylesheet(content, path, activeStylePreprocessor, {
288
+ filename: path,
289
+ containingFile: file.filePath,
290
+ resourceFile: inline ? void 0 : path,
291
+ className: metadata.className,
292
+ order,
293
+ inline
294
+ });
295
+ const result = await vite.preprocessCSS(preprocessed, path, activeConfig);
296
+ result.deps?.forEach(watch);
297
+ return result.code;
298
+ };
299
+ return {
300
+ ...metadata,
301
+ component: {
302
+ ...component,
303
+ styles: component.styles && await Promise.all(component.styles.map((style, index) => preprocess(style, `${file.filePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`, index, true))),
304
+ stylesFromUrls: component.stylesFromUrls && await Promise.all(component.stylesFromUrls.map((style, index) => preprocess(style, component.styleUrls[index].resolvedPath, index, false)))
305
+ }
306
+ };
307
+ }))
308
+ };
309
+ }
310
+ async function indexChunks(update) {
311
+ if (update) {
312
+ const invalidated = await update();
313
+ for (const filePath of invalidated) {
314
+ output.delete(vite.normalizePath(filePath));
315
+ compiler.fileCache.delete(filePath);
316
+ }
317
+ chunkContexts.clear();
318
+ } else {
319
+ filesByPath.clear();
320
+ chunkContexts.clear();
321
+ output.clear();
322
+ const angularOptions = compilerCli.readConfiguration(resolveTsConfigPath()).options;
323
+ compiler = new api.HybridCompiler(analyzer, {
324
+ ...angularOptions,
325
+ optimize: true,
326
+ enableHmr: hmr,
327
+ tcbConfig: api.buildTypeCheckingConfig(angularOptions)
328
+ });
329
+ }
330
+ const chunks = update ? compiler.analyzeOptimizedDelta() : compiler.analyzeOptimized();
331
+ for await (const chunk of chunks) {
332
+ for (const file of chunk.files) {
333
+ const normPath = vite.normalizePath(file.filePath);
334
+ filesByPath.set(normPath, {
335
+ file,
336
+ chunk
337
+ });
338
+ output.delete(normPath);
339
+ compiler.fileCache.delete(file.filePath);
340
+ }
341
+ for (const removed of chunk.removedFiles ?? []) {
342
+ const normPath = vite.normalizePath(removed);
343
+ filesByPath.delete(normPath);
344
+ output.delete(normPath);
345
+ }
346
+ }
347
+ }
348
+ function enqueueIndex(update) {
349
+ pending = pending.catch(() => {}).then(() => indexChunks(update));
350
+ return pending;
351
+ }
352
+ function getChunkContext(chunk) {
353
+ let context = chunkContexts.get(chunk);
354
+ if (!context) {
355
+ context = compiler.prepareChunk(chunk);
356
+ chunkContexts.set(chunk, context);
357
+ }
358
+ return context;
359
+ }
360
+ async function checkTypes(filePath, sourceCode, tcbCode) {
361
+ typeChecker ??= new LspTypeChecker(resolveTsConfigPath(), options.typeChecker, {
362
+ inMemoryFiles: () => new Map([...sourceModules].map(([file, { lowered }]) => [file, lowered.code])),
363
+ mapLocation: toSourceLocation
364
+ });
365
+ typeChecker.queueFile(filePath, sourceCode, tcbCode);
366
+ if (!watchMode) return;
367
+ const typeErrors = await typeChecker.flushQueue(true);
368
+ if (typeErrors.length) throw new Error(typeErrors.join("\n"));
369
+ }
370
+ async function processFile(normPath, activeCompiler, watch) {
371
+ const { file: analyzed, chunk } = filesByPath.get(normPath);
372
+ const [file, context, content] = await Promise.all([
373
+ prepareResources(analyzed, (path) => {
374
+ const key = sourceFileOf(vite.normalizePath(path));
375
+ dependents.set(key, (dependents.get(key) ?? /* @__PURE__ */ new Set()).add(normPath));
376
+ watch(key);
377
+ }),
378
+ getChunkContext(chunk),
379
+ analyzer.getFileContent(analyzed.filePath)
380
+ ]);
381
+ sources.set(normPath, content);
382
+ return {
383
+ file,
384
+ content,
385
+ result: activeCompiler.processFile.length >= 5 ? await activeCompiler.processFile(file.filePath, content, void 0, file, context) : await activeCompiler.processFile(file.filePath, content, file, context)
386
+ };
387
+ }
388
+ function compileFile(normPath, watch) {
389
+ if (!filesByPath.has(normPath)) return void 0;
390
+ let task = output.get(normPath);
391
+ if (!task) {
392
+ task = (async () => {
393
+ await pending;
394
+ if (!filesByPath.has(normPath)) throw new Error(`${sourceFileOf(normPath)} was removed.`);
395
+ const { file, content, result } = await processFile(normPath, compiler, watch);
396
+ const errors = [...file.diagnostics ?? [], ...result.diagnostics ?? []].filter((diagnostic) => diagnostic.category === 1);
397
+ if (errors.length) throw new Error(`${sourceFileOf(normPath)}: ${errors.map((error) => error.messageText).join("\n")}`);
398
+ if (options.disableTypeChecking !== true) await checkTypes(file.filePath, content, result.tcb?.code);
399
+ return result;
400
+ })();
401
+ output.set(normPath, task);
402
+ }
403
+ return task;
404
+ }
405
+ function componentNames(normPath) {
406
+ return (filesByPath.get(normPath)?.file.classes ?? []).flatMap(({ className, component }) => component && className ? [className] : []);
407
+ }
408
+ async function findComponentUpdates(normPath, read) {
409
+ if (!TS_EXT_REGEX.test(normPath)) return [...dependents.get(normPath) ?? []].flatMap((file) => componentNames(file).map((className) => ({
410
+ file,
411
+ className
412
+ })));
413
+ const stale = sources.get(normPath);
414
+ if (stale === void 0) return [];
415
+ return (findHmrComponentUpdates(normPath, stale, await read(), new Set(componentNames(normPath))) ?? []).map((className) => ({
416
+ file: normPath,
417
+ className
418
+ }));
419
+ }
420
+ async function emitHmrUpdate(file, className) {
421
+ const { result } = await processFile(file, Object.assign(Object.create(Object.getPrototypeOf(compiler)), compiler, {
422
+ hmrUpdateTarget: className,
423
+ reuseProcessedFiles: false
424
+ }), () => {});
425
+ return result.hmrUpdateModule && (await transpile(result.hmrUpdateModule, file)).code;
426
+ }
427
+ async function sendComponentUpdates(updates, server) {
428
+ try {
429
+ for (const file of new Set(updates.map((update) => update.file))) await compileFile(file, () => {});
430
+ const codes = await Promise.all(updates.map(({ file, className }) => emitHmrUpdate(file, className)));
431
+ if (codes.some((code) => !code)) return false;
432
+ updates.forEach(({ file, className }, index) => {
433
+ const sourceFile = sourceModules.get(file)?.sourceFile;
434
+ const moduleFile = sourceFile ?? file;
435
+ hmrUpdateCode.set(`${moduleFile}@${className}`, codes[index]);
436
+ componentUpdates.classNames.set(moduleFile, className);
437
+ server.moduleGraph.getModulesByFile(moduleFile)?.forEach((mod) => server.moduleGraph.invalidateModule(mod));
438
+ server.ws.send("angular:component-update", {
439
+ id: encodeURIComponent(`${sourceFile ?? filesByPath.get(file).file.filePath}@${className}`),
440
+ timestamp: Date.now()
441
+ });
442
+ });
443
+ return true;
444
+ } catch {
445
+ return false;
446
+ }
447
+ }
448
+ return {
449
+ name: "@analogjs/vite-plugin-angular-ngp",
450
+ enforce: "pre",
451
+ api: compilerApi,
452
+ config(config, { command, mode }) {
453
+ watchMode = command === "serve";
454
+ const isProd = isProdMode(config.mode);
455
+ if (sharedCtx) sharedCtx.initConfig(config, {
456
+ command,
457
+ mode
458
+ });
459
+ else configContext = {
460
+ root: config.root || ".",
461
+ isProd,
462
+ isLib: !!config.build?.lib
463
+ };
464
+ const depOptimizer = createDepOptimizerConfig({
465
+ tsconfig: resolveTsConfigPath(),
466
+ isProd,
467
+ jit: false,
468
+ watchMode,
469
+ isTest: options.isTest,
470
+ isAstroIntegration: options.isAstroIntegration
471
+ });
472
+ return {
473
+ ...isRolldown() ? { oxc: {} } : { esbuild: false },
474
+ ...depOptimizer
475
+ };
476
+ },
477
+ async configResolved(config) {
478
+ resolvedConfig = config;
479
+ hmr = watchMode && options.liveReload && !options.isTest && config.server.hmr !== false;
480
+ const integrations = sharedCtx ? await sharedCtx.resolveConfig(config) : await discoverAnalogIntegrations(config);
481
+ transformFilter = integrations.transformFilter;
482
+ componentRegistries = integrations.componentRegistries;
483
+ stylePreprocessor = integrations.stylePreprocessor;
484
+ },
485
+ configureServer(server) {
486
+ const changeTypes = {
487
+ add: 1,
488
+ change: 2,
489
+ unlink: 3
490
+ };
491
+ devServer = server;
492
+ server.watcher.on("all", (event, path) => {
493
+ const type = changeTypes[event];
494
+ if (type) typeChecker?.notifyFileChanged(path, type);
495
+ });
496
+ server.httpServer?.on("close", () => {
497
+ typeChecker?.close();
498
+ typeChecker = void 0;
499
+ analyzer?.close();
500
+ analyzer = void 0;
501
+ compiler = void 0;
502
+ });
503
+ },
504
+ async watchChange(id, { event }) {
505
+ if (!analyzer || sourceFormats.length === 0) return;
506
+ const file = canonicalPath(id);
507
+ const resolve = (spec, importer) => this.resolve(spec, importer, { skipSelf: true });
508
+ await withSourceLock(async () => {
509
+ scanner.invalidate(file);
510
+ const format = moduleFormatOf(file);
511
+ if (event === "update") reloweredByChange.set(file, await relowerSourceModules(file, resolve));
512
+ else if (event === "delete") await removeSourceModule(file);
513
+ else if (event === "create" && format && !sourceModules.has(`${file}.ts`)) {
514
+ const source = await readSource(file);
515
+ if (source !== void 0) await addSourceModule(file, format, source, resolve);
516
+ }
517
+ await syncProgramFiles();
518
+ });
519
+ for (const importer of scanner.importersByFile.get(file) ?? []) devServer?.moduleGraph.getModulesByFile(importer)?.forEach((mod) => devServer.moduleGraph.invalidateModule(mod));
520
+ },
521
+ async buildStart() {
522
+ activeBuilds++;
523
+ if (!analyzer) {
524
+ const tsconfig = resolveTsConfigPath();
525
+ const hasSourceFormats = sourceFormats.length > 0;
526
+ const ngp = await loadNgp(tsconfig, hasSourceFormats);
527
+ api = ngp.api;
528
+ if (hasSourceFormats) await lowerSourceModules(dirname(tsconfig), (specifier, importer) => this.resolve(specifier, importer, { skipSelf: true }));
529
+ analyzer = await api.createAnalyzer(tsconfig, {
530
+ ...ngp.analyzerOptions,
531
+ enableHmr: hmr,
532
+ hostFs: hasSourceFormats ? createNgpHostFs((path) => sourceModules.get(path)?.lowered.code) : void 0
533
+ });
534
+ pending = indexChunks();
535
+ }
536
+ await pending;
537
+ for (const path of dependents.keys()) this.addWatchFile(path);
538
+ },
539
+ resolveId(id, importer) {
540
+ return resolveAngularVirtualId(id, importer, {
541
+ jit: false,
542
+ resolvedConfig: sharedCtx?.resolvedConfig ?? resolvedConfig
543
+ });
544
+ },
545
+ async load(id) {
546
+ return loadAngularVirtualModule(this, id, sharedCtx?.resolvedConfig ?? resolvedConfig);
547
+ },
548
+ async transform(code, id) {
549
+ const activeTransformFilter = sharedCtx?.transformFilter ?? transformFilter;
550
+ const filePath = vite.normalizePath(id.split("?")[0]);
551
+ const sourceFormat = scanner.sourceFormatOf(filePath);
552
+ if (!(sourceFormat ? sourceFilter(id) : filter(id)) || activeTransformFilter?.(code, id) === false) return;
553
+ await pending;
554
+ let lowered;
555
+ let compiledFile = filePath;
556
+ if (sourceFormat) {
557
+ const sourceFile = canonicalPath(filePath);
558
+ const format = moduleFormatOf(sourceFile);
559
+ if (!format) this.error(`${filePath} is outside ${dirname(resolveTsConfigPath())}, where '${sourceFormat.name}' modules are compiled from.`);
560
+ lowered = await withSourceLock(async () => {
561
+ const result = await lowerForTransform(sourceFile, format, code, (spec, importer) => this.resolve(spec, importer, { skipSelf: true }));
562
+ await syncProgramFiles();
563
+ return result;
564
+ });
565
+ if (!lowered) this.error(`${filePath} was removed while it was compiled.`);
566
+ if (lowered.error) this.error({
567
+ message: lowered.error.message,
568
+ id: filePath,
569
+ loc: lowered.error.loc && {
570
+ file: filePath,
571
+ ...lowered.error.loc
572
+ }
573
+ });
574
+ compiledFile = `${sourceFile}.ts`;
575
+ for (const dependency of scanner.dependenciesOf(sourceFile)) this.addWatchFile(dependency);
576
+ }
577
+ const compiledCode = lowered ? lowered.code : code;
578
+ const watch = (path) => this.addWatchFile(path);
579
+ let result;
580
+ try {
581
+ result = await compileFile(compiledFile, watch);
582
+ } catch (error) {
583
+ if (!sources.has(compiledFile) || sources.get(compiledFile) === compiledCode) throw error;
584
+ }
585
+ if (filesByPath.has(compiledFile) && sources.get(compiledFile) !== compiledCode) {
586
+ if (lowered) analyzed.set(compiledFile, compiledCode);
587
+ await enqueueIndex(() => analyzer.updateFileContent([{
588
+ filePath: compiledFile,
589
+ content: compiledCode
590
+ }]));
591
+ result = await compileFile(compiledFile, watch);
592
+ } else if (!result && lowered) this.error(`${filePath} is not part of the TypeScript program of ${resolveTsConfigPath()}. Import it, or add it to the tsconfig's \`include\`.`);
593
+ else if (!result && options.disableTypeChecking !== true) await checkTypes(filePath, code);
594
+ let source = result?.magicString.toString() ?? code;
595
+ if (lowered && result) source = source.replaceAll(encodeURIComponent(`${filesByPath.get(compiledFile).file.filePath}@`), encodeURIComponent(`${filePath}@`));
596
+ const map = result?.magicString.generateMap({
597
+ source: compiledFile,
598
+ includeContent: true,
599
+ hires: true
600
+ });
601
+ const transpiled = await transpile(source, compiledFile, map);
602
+ const outputMap = lowered && transpiled.map ? lowered.mapToSource(JSON.stringify(transpiled.map)) : transpiled.map;
603
+ if (outputMap) emittedMaps.set(filePath, typeof outputMap === "string" ? outputMap : JSON.stringify(outputMap));
604
+ return {
605
+ code: transpiled.code,
606
+ map: outputMap
607
+ };
608
+ },
609
+ async handleHotUpdate(ctx) {
610
+ if (sharedCtx ? sharedCtx.hmr.isIgnoredFile(ctx.file) : isIgnoredHmrFile(ctx.file)) return [];
611
+ const normPath = vite.normalizePath(ctx.file);
612
+ const sourceFile = canonicalPath(ctx.file);
613
+ const programFile = programFileOf(sourceFile);
614
+ const updates = await withSourceLock(async () => {
615
+ const relowered = reloweredByChange.get(sourceFile) ?? [];
616
+ reloweredByChange.delete(sourceFile);
617
+ const lowered = programFile ? sourceModules.get(programFile)?.lowered : void 0;
618
+ const componentUpdates = hmr && !lowered?.error && relowered.every((file) => file === programFile) ? await findComponentUpdates(programFile ?? normPath, lowered ? () => lowered.code : ctx.read) : [];
619
+ if (!programFile) await enqueueIndex(() => analyzer.invalidateFiles([{
620
+ filePath: ctx.file,
621
+ updateType: FILE_CHANGED
622
+ }]));
623
+ await syncProgramFiles();
624
+ return componentUpdates;
625
+ });
626
+ if (updates.length && await sendComponentUpdates(updates, ctx.server)) return [];
627
+ hmrUpdateCode.clear();
628
+ componentUpdates.classNames.clear();
629
+ ctx.server.moduleGraph.invalidateAll();
630
+ ctx.server.ws.send({ type: "full-reload" });
631
+ return [];
632
+ },
633
+ async buildEnd(error) {
634
+ if (error || watchMode || !typeChecker) return;
635
+ const typeErrors = await typeChecker.flushQueue();
636
+ if (typeErrors.length) throw new Error(typeErrors.join("\n"));
637
+ },
638
+ async closeBundle() {
639
+ activeBuilds = Math.max(0, activeBuilds - 1);
640
+ if (watchMode || activeBuilds > 0) return;
641
+ await pending.catch(() => {});
642
+ typeChecker?.close();
643
+ typeChecker = void 0;
644
+ analyzer?.close();
645
+ analyzer = void 0;
646
+ compiler = void 0;
647
+ filesByPath.clear();
648
+ chunkContexts.clear();
649
+ output.clear();
650
+ emittedMaps.clear();
651
+ sources.clear();
652
+ dependents.clear();
653
+ sourceModules.clear();
654
+ analyzed.clear();
655
+ releaseCssPreprocessorWorkers();
656
+ }
657
+ };
658
+ }
659
+ //#endregion
660
+ export { ngpCompilePlugin };
661
+
662
+ //# sourceMappingURL=ngp-compile-plugin.js.map