@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 +1 @@
1
- {"version":3,"file":"compilation-api-plugin.js","names":[],"sources":["../../../../src/lib/compilation-api/compilation-api-plugin.ts"],"sourcesContent":["import { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';\nimport { union } from 'es-toolkit';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, isAbsolute, join, relative, resolve } from 'node:path';\nimport { createRequire } from 'node:module';\nimport {\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularCompilation,\n SourceFileCache,\n angularFullVersion,\n} from '../utils/devkit.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugCompilationApi,\n debugCompiler,\n debugEmit,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n type DebugOption,\n} from '../utils/debug.js';\nimport { warnStylesheetError } from '../utils/stylesheet-warning.js';\nimport {\n getTsConfigPath,\n createTsConfigGetter,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from '../utils/plugin-config.js';\nimport { TsconfigResolver } from '../utils/tsconfig-resolver.js';\nimport { isRolldown } from '../utils/rolldown.js';\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from '../compiler-plugin.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheetResult,\n registerStylesheetContent,\n rewriteRelativeCssImports,\n} from '../stylesheet-registry.js';\nimport { normalizeStylesheetDependencies } from '../style-preprocessor.js';\nimport type { StylePreprocessor } from '../style-preprocessor.js';\nimport {\n discoverAnalogIntegrations,\n type TransformFilter,\n} from '../analog-plugin-interop.js';\nimport { type FileReplacement } from '../plugins/file-replacements.plugin.js';\nimport type { EmitFileResult } from '../models.js';\nimport type { SourceFileCache as SourceFileCacheType } from '../utils/source-file-cache.js';\nimport {\n injectViteIgnoreForHmrMetadata,\n isIgnoredHmrFile,\n toAngularCompilationFileReplacements,\n mapTemplateUpdatesToFiles,\n refreshStylesheetRegistryForFile,\n DiagnosticModes,\n isTestWatchMode,\n getBrowserModeCliOverride,\n} from '../utils/compilation-shared.js';\nimport { createHotUpdateBatcher } from '../hot-update-batch.js';\nimport { angularVitestPlugins } from '../angular-vitest-plugin.js';\nimport { buildOptimizerPlugin } from '../angular-build-optimizer-plugin.js';\nimport { jitPlugin } from '../angular-jit-plugin.js';\nimport { liveReloadPlugin } from '../live-reload-plugin.js';\nimport { virtualModulesPlugin } from '../virtual-modules-plugin.js';\nimport { encapsulationPlugin } from '../encapsulation-plugin.js';\nimport { nxFolderPlugin } from '../nx-folder-plugin.js';\nimport { routerPlugin } from '../router-plugin.js';\nimport { replaceFiles } from '../plugins/file-replacements.plugin.js';\nimport { cssExtensionStyleResolverPlugin } from '../utils/css-extension-resolver.js';\nimport { loadVirtualRawModule } from '../utils/virtual-resources.js';\n\nconst require = createRequire(import.meta.url);\nconst ts = require('typescript');\n\n/**\n * @experimental The Angular Compilation API plugin may change in future releases.\n */\nexport interface AngularCompilationPluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n supportedBrowsers?: string[];\n fileReplacements?: FileReplacement[];\n include?: string[];\n debug?: DebugOption;\n}\n\n/**\n * Compiles Angular applications using Angular's private Compilation API.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function angularCompilationPlugin(\n options: AngularCompilationPluginOptions = {},\n): Plugin[] {\n if (\n angularFullVersion < 200100 ||\n typeof createAngularCompilation !== 'function'\n ) {\n throw new Error(\n '[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.',\n );\n }\n\n applyDebugOption(options.debug, options.workspaceRoot);\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const pluginOptions = {\n tsconfigGetter: createTsConfigGetter(options.tsconfig),\n workspaceRoot:\n options.workspaceRoot ??\n process.env['NX_WORKSPACE_ROOT'] ??\n process.cwd(),\n inlineStylesExtension: options.inlineStylesExtension ?? 'css',\n jit: options.jit ?? isTest,\n liveReload: options.liveReload ?? true,\n disableTypeChecking: options.disableTypeChecking ?? true,\n supportedBrowsers: options.supportedBrowsers ?? ['safari 15'],\n fileReplacements: options.fileReplacements ?? [],\n include: options.include ?? [],\n isAstroIntegration: process.env['ANALOG_ASTRO'] === 'true',\n };\n let resolvedConfig: ResolvedConfig;\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n let watchMode = false;\n let stylePreprocessor: StylePreprocessor | undefined;\n let transformFilter: TransformFilter | undefined;\n let externalizeStylesRequested = false;\n\n // Persistent compilation instance — kept alive across rebuilds so Angular\n // can diff prior state and emit `templateUpdates` for HMR.\n let angularCompilation:\n | Awaited<ReturnType<typeof createAngularCompilationType>>\n | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const outputFiles = new Map<string, EmitFileResult>();\n const classNames = new Map<string, string>();\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n let compilationLock = Promise.resolve();\n let pendingCompilation: Promise<void> | null = null;\n let initialCompilation = false;\n let viteServer: ViteDevServer | undefined;\n const hotUpdates = createHotUpdateBatcher((ids) =>\n performCompilation(resolvedConfig, ids),\n );\n\n const tsconfigResolver = new TsconfigResolver({\n workspaceRoot: pluginOptions.workspaceRoot,\n include: pluginOptions.include,\n liveReload: pluginOptions.liveReload,\n isTest,\n });\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n let deferInitialCompilation = isVitestVscode;\n let testWatchMode = isTestWatchMode();\n\n function hasViteHmrTransport(): boolean {\n return resolvedConfig ? resolvedConfig.server.hmr !== false : true;\n }\n\n function shouldEnableLiveReload(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n return !!(\n effectiveWatchMode &&\n pluginOptions.liveReload &&\n hasViteHmrTransport()\n );\n }\n\n function shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n if (!effectiveWatchMode) return false;\n return !!(shouldEnableLiveReload() || externalizeStylesRequested);\n }\n\n function resolveTsConfigPath() {\n const tsconfigValue = pluginOptions.tsconfigGetter();\n return getTsConfigPath(\n tsConfigResolutionContext!.root,\n tsconfigValue,\n tsConfigResolutionContext!.isProd,\n isTest,\n tsConfigResolutionContext!.isLib,\n );\n }\n\n function resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath: string,\n config: ResolvedConfig,\n ): string {\n const includedFiles = tsconfigResolver.ensureIncludeCache();\n const cached = tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n const expandedGraphRoots = tsconfigResolver.collectExpandedTsconfigRoots(\n resolvedTsConfigPath,\n config,\n );\n const mergedRootNames = union(\n cached.rootNames,\n expandedGraphRoots,\n includedFiles,\n ).map((file) => normalizePath(file));\n\n if (mergedRootNames.length === cached.rootNames.length) {\n return resolvedTsConfigPath;\n }\n\n const resolvedCacheDir = isAbsolute(config.cacheDir)\n ? config.cacheDir\n : resolve(config.root, config.cacheDir);\n const wrapperDir = join(\n resolvedCacheDir,\n 'analog-angular',\n 'compilation-api',\n );\n const rawTsconfig = (ts.readConfigFile(\n resolvedTsConfigPath,\n ts.sys.readFile,\n ).config ?? {}) as { references?: unknown[] };\n const wrapperPayload = {\n extends: normalizePath(resolvedTsConfigPath),\n files: [...mergedRootNames].sort(),\n ...(rawTsconfig.references ? { references: rawTsconfig.references } : {}),\n };\n const wrapperHash = createHash('sha1')\n .update(JSON.stringify(wrapperPayload))\n .digest('hex')\n .slice(0, 12);\n const wrapperPath = join(\n wrapperDir,\n `tsconfig.includes.${wrapperHash}.json`,\n );\n\n mkdirSync(wrapperDir, { recursive: true });\n if (!existsSync(wrapperPath)) {\n writeFileSync(\n wrapperPath,\n `${JSON.stringify(wrapperPayload, null, 2)}\\n`,\n 'utf-8',\n );\n }\n\n debugCompilationApi('generated include wrapper tsconfig', {\n originalTsconfig: resolvedTsConfigPath,\n wrapperTsconfig: wrapperPath,\n includeCount: includedFiles.length,\n rootNameCount: mergedRootNames.length,\n });\n\n return wrapperPath;\n }\n\n const normalizeEmitterLookupId = (file: string) => {\n const normalizedFile = normalizePath(file);\n if (!normalizedFile.startsWith('/@fs/')) return normalizedFile;\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n return normalizePath(fsPath);\n };\n\n let outputFile: ((file: string) => void) | undefined;\n const fileEmitter = (file: string) => {\n const normalizedFile = normalizeEmitterLookupId(file);\n outputFile?.(normalizedFile);\n return outputFiles.get(normalizedFile);\n };\n\n async function performAngularCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ) {\n const compilation = (angularCompilation ??= await (\n createAngularCompilation as typeof createAngularCompilationType\n )(!!pluginOptions.jit, false));\n const modifiedFiles = ids?.length\n ? new Set(ids.map((file) => normalizePath(file)))\n : undefined;\n if (modifiedFiles?.size) {\n sourceFileCache.invalidate(modifiedFiles);\n }\n if (modifiedFiles?.size && compilation.update) {\n debugCompilationApi('incremental update', {\n files: [...modifiedFiles],\n });\n await compilation.update(modifiedFiles);\n }\n\n const resolvedTsConfigPath = resolveTsConfigPath();\n const compilationApiTsConfigPath = resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath,\n config,\n );\n debugEmit('compilation initialize', {\n resolvedTsConfigPath,\n compilationApiTsConfigPath,\n modifiedFileCount: modifiedFiles?.size ?? 0,\n });\n const transformCompilerOptions = (\n tsCompilerOptions: Record<string, unknown>,\n ) => {\n if (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (compilation API)', {\n liveReload: pluginOptions.liveReload,\n viteHmr: hasViteHmrTransport(),\n externalizeStylesRequested,\n watchMode,\n shouldExternalize: shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && resolvedConfig.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n return tsCompilerOptions;\n };\n const compilationResult = await compilation.initialize(\n compilationApiTsConfigPath,\n {\n fileReplacements: toAngularCompilationFileReplacements(\n pluginOptions.fileReplacements,\n pluginOptions.workspaceRoot,\n ),\n modifiedFiles,\n async transformStylesheet(\n data: string,\n containingFile: string,\n resourceFile: string | null,\n order: number,\n className: string | null,\n ) {\n // @angular/build >= 22.2.4 no longer reads external stylesheets in readResource\n if (resourceFile && !data) {\n data = readFileSync(resourceFile, 'utf-8');\n }\n\n const filename =\n resourceFile ??\n containingFile.replace(\n '.ts',\n `.${pluginOptions.inlineStylesExtension}`,\n );\n\n const preprocessed = preprocessStylesheetResult(\n data,\n filename,\n stylePreprocessor,\n {\n filename,\n containingFile,\n resourceFile,\n className,\n order,\n inline: !resourceFile,\n },\n );\n\n if (shouldEnableLiveReload() && className && containingFile) {\n classNames.set(normalizePath(containingFile), className as string);\n }\n\n if (shouldExternalizeStyles()) {\n const stylesheetId = registerStylesheetContent(\n stylesheetRegistry!,\n {\n code: preprocessed.code,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n containingFile,\n className: className as string | undefined,\n order,\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n resourceFile: resourceFile ?? undefined,\n },\n );\n\n debugStyles('stylesheet deferred to Vite pipeline', {\n stylesheetId,\n resourceFile: resourceFile ?? '(inline)',\n });\n\n return stylesheetId;\n }\n\n debugStyles('stylesheet processed inline via preprocessCSS', {\n filename,\n resourceFile: resourceFile ?? '(inline)',\n dataLength: preprocessed.code.length,\n });\n\n let stylesheetResult;\n try {\n stylesheetResult = await preprocessCSS(\n preprocessed.code,\n `${filename}?direct`,\n resolvedConfig,\n );\n } catch (e) {\n debugStyles('preprocessCSS error', {\n filename,\n resourceFile: resourceFile ?? '(inline)',\n error: String(e),\n });\n warnStylesheetError(resolvedConfig.logger, filename, e);\n }\n\n return stylesheetResult?.code || '';\n },\n processWebWorker(workerFile: string) {\n return workerFile;\n },\n },\n angularFullVersion >= 220200\n ? {\n enableHmr: shouldEnableLiveReload(),\n externalRuntimeStyles: shouldExternalizeStyles(),\n includeTestMetadata: isTest || shouldEnableLiveReload(),\n instrumentForCoverage: !isTest,\n }\n : (transformCompilerOptions as unknown as Parameters<\n typeof compilation.initialize\n >[2]),\n );\n\n // Preprocess external stylesheets for Tailwind CSS @reference\n debugStyles('external stylesheets from compilation API', {\n count: compilationResult.externalStylesheets?.size ?? 0,\n hasPreprocessor: !!stylePreprocessor,\n hasInlineMap: !!stylesheetRegistry,\n });\n const preprocessStats = { total: 0, injected: 0, skipped: 0, errors: 0 };\n for (const [key, value] of compilationResult.externalStylesheets ?? []) {\n preprocessStats.total++;\n const angularHash = `${value}.css`;\n stylesheetRegistry?.registerExternalRequest(angularHash, key);\n\n if (stylesheetRegistry && stylePreprocessor && existsSync(key)) {\n try {\n const rawCss = readFileSync(key, 'utf-8');\n const preprocessed = preprocessStylesheetResult(\n rawCss,\n key,\n stylePreprocessor,\n );\n const servedCss = rewriteRelativeCssImports(preprocessed.code, key);\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId: angularHash,\n sourcePath: key,\n originalCode: rawCss,\n normalizedCode: servedCss,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n },\n [key, normalizePath(key), basename(key), key.replace(/^\\//, '')],\n );\n\n if (servedCss && servedCss !== rawCss) {\n preprocessStats.injected++;\n } else {\n preprocessStats.skipped++;\n }\n } catch (e) {\n preprocessStats.errors++;\n console.warn(\n `[@analogjs/vite-plugin-angular] failed to preprocess external stylesheet: ${key}: ${e}`,\n );\n }\n } else {\n preprocessStats.skipped++;\n }\n }\n debugStyles('external stylesheet preprocessing complete', preprocessStats);\n\n const diagnostics = await compilation.diagnoseFiles(\n pluginOptions.disableTypeChecking\n ? DiagnosticModes.All & ~DiagnosticModes.Semantic\n : DiagnosticModes.All,\n );\n\n const errors = diagnostics.errors?.length ? diagnostics.errors : [];\n const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];\n\n const templateUpdates = mapTemplateUpdatesToFiles(\n compilationResult.templateUpdates,\n );\n if (templateUpdates.size > 0) {\n debugHmr('compilation API template updates', {\n count: templateUpdates.size,\n files: [...templateUpdates.keys()],\n });\n }\n\n const affectedFiles = await compilation.emitAffectedFiles();\n debugEmit('emitAffectedFiles summary', {\n count: affectedFiles.length,\n templateUpdateCount: templateUpdates.size,\n knownOutputCountBefore: outputFiles.size,\n });\n\n for (const file of affectedFiles) {\n const normalizedFilename = normalizePath(file.filename);\n const templateUpdate = templateUpdates.get(normalizedFilename);\n\n if (templateUpdate) {\n classNames.set(normalizedFilename, templateUpdate.className);\n }\n\n outputFiles.set(normalizedFilename, {\n content: file.contents,\n dependencies: [],\n errors: errors.map((error: { text?: string }) => error.text || ''),\n warnings: warnings.map(\n (warning: { text?: string }) => warning.text || '',\n ),\n hmrUpdateCode: templateUpdate?.code,\n hmrEligible: !!templateUpdate?.code,\n });\n }\n\n // Free the compilation before chunks render; `transform` still reads `outputFiles`.\n if (!watchMode && !isTest) {\n await compilation.close?.();\n angularCompilation = undefined;\n }\n }\n\n async function performCompilation(config: ResolvedConfig, ids?: string[]) {\n let resolve: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n resolve = r;\n });\n try {\n await previousLock;\n const integrations = await discoverAnalogIntegrations(config);\n stylePreprocessor = integrations.stylePreprocessor;\n transformFilter = integrations.transformFilter;\n tsconfigResolver.setIntegrationIncludes(integrations.include);\n externalizeStylesRequested = integrations.externalizeStyles;\n await performAngularCompilation(config, ids);\n } finally {\n resolve!();\n }\n }\n\n function isComponentStyleSheet(id: string): boolean {\n return id.includes('ngcomp=');\n }\n\n function getFilenameFromPath(id: string): string {\n try {\n return new URL(id, 'http://localhost').pathname.replace(/^\\//, '');\n } catch {\n const queryIndex = id.indexOf('?');\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id;\n return pathname.replace(/^\\//, '');\n }\n }\n\n function sendHMRComponentUpdate(server: ViteDevServer, id: string) {\n debugHmrV('ws send: angular component update', {\n id,\n timestamp: Date.now(),\n });\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(id),\n timestamp: Date.now(),\n });\n classNames.delete(id);\n }\n\n const compilerPlugin: Plugin = {\n name: '@analogjs/vite-plugin-angular-compilation-api',\n api: { getTsConfigPath: resolveTsConfigPath },\n enforce: 'pre' as const,\n async config(config, { command }) {\n activateDeferredDebug(command);\n watchMode = command === 'serve';\n const isProd =\n config.mode === 'production' ||\n process.env['NODE_ENV'] === 'production';\n\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n debugCompilationApi('enabled (Angular %s)', angularFullVersion);\n\n // Angular Compilation API handles TypeScript transforms — disable\n // esbuild/oxc so they don't compete.\n debugCompilationApi('esbuild/oxc disabled, Angular handles transforms');\n\n // The compilation API owns user-source transforms, but deps\n // optimization still bundles partial-compiled Angular libs from\n // node_modules (`ɵɵngDeclareInjectable/Factory`). Without the\n // linker plugin, those declarations reach the browser unprocessed\n // and Angular tries to JIT-compile them at runtime. Mirror the\n // deps-optimizer wiring from `angular-vite-plugin.ts` so the\n // linker runs on `.[cm]?js` deps under both rolldown and esbuild.\n const useRolldown = isRolldown();\n const preliminaryTsConfigPath = resolveTsConfigPath();\n const compilerPluginOptions = {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit: pluginOptions.jit,\n incremental: watchMode,\n };\n\n // No `resolve.conditions` extension here: the `style` condition is\n // scoped to `.css`-extension requests by\n // `cssExtensionStyleResolverPlugin`, registered once at the\n // `angularCompilationPlugin()` factory level. Adding `style` globally caused\n // Tailwind v4's JS plugin resolver to pick the `style` exports of\n // packages such as `tailwindcss-primeui`, which then crashed Node's\n // ESM loader when it tried to import the resulting `.css` file.\n return {\n esbuild: undefined,\n oxc: undefined,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown\n ? {\n rolldownOptions: {\n plugins: [\n createRolldownCompilerPlugin(\n compilerPluginOptions,\n !pluginOptions.isAstroIntegration,\n ),\n ],\n },\n }\n : {\n esbuildOptions: {\n plugins: [\n createCompilerPlugin(\n compilerPluginOptions,\n isTest,\n !pluginOptions.isAstroIntegration,\n ),\n ],\n },\n }),\n },\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n\n stylesheetRegistry = new AnalogStylesheetRegistry();\n const integrations = await discoverAnalogIntegrations(config);\n integrations.configureStylesheetRegistry?.(stylesheetRegistry, {\n workspaceRoot: pluginOptions.workspaceRoot,\n });\n debugStyles('stylesheet registry initialized (Angular Compilation API)');\n\n if (isTest) {\n const browser = (config as any).test?.browser;\n deferInitialCompilation =\n isVitestVscode ||\n (!!browser &&\n (getBrowserModeCliOverride() ?? browser.enabled) === true);\n\n testWatchMode =\n !(config.server.watch === null) ||\n (config as any).test?.watch === true ||\n testWatchMode;\n }\n },\n configureServer(server) {\n viteServer = server;\n hotUpdates.configureServer(server);\n\n const invalidateCompilation = async () => {\n tsconfigResolver.invalidateAll();\n await performCompilation(resolvedConfig);\n };\n server.watcher.on('add', invalidateCompilation);\n server.watcher.on('unlink', invalidateCompilation);\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n tsconfigResolver.invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n if (!deferInitialCompilation) {\n pendingCompilation = performCompilation(resolvedConfig);\n await pendingCompilation;\n pendingCompilation = null;\n initialCompilation = true;\n }\n },\n async handleHotUpdate(ctx) {\n if (isIgnoredHmrFile(ctx.file)) {\n debugHmr('ignored file change', { file: ctx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n debugHmr('TS file changed', { file: ctx.file, fileId });\n\n await hotUpdates.schedule(ctx.file, [fileId]);\n\n let result;\n\n if (shouldEnableLiveReload()) {\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n });\n }\n\n if (\n shouldEnableLiveReload() &&\n result?.hmrEligible &&\n classNames.get(fileId)\n ) {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), fileId),\n )}@${classNames.get(fileId)}`;\n\n debugHmr('sending component update', { relativeFileId });\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n\n return ctx.modules.map((mod) => {\n if (mod.id === ctx.file) {\n mod.isSelfAccepting = true;\n }\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm)$/.test(ctx.file)) {\n debugHmr('template file changed', { file: ctx.file });\n // Recompile to pick up template changes\n pendingCompilation = performCompilation(resolvedConfig);\n }\n\n if (/\\.(css|less|sass|scss)$/.test(ctx.file)) {\n debugHmr('stylesheet file changed', { file: ctx.file });\n refreshStylesheetRegistryForFile(\n ctx.file,\n stylesheetRegistry,\n stylePreprocessor,\n );\n }\n\n return ctx.modules;\n },\n resolveId(id) {\n // Map angular component stylesheets\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const search = new URL(id, 'http://localhost').search;\n const servedSourcePath =\n stylesheetRegistry?.getServedSourcePath(filename);\n\n if (servedSourcePath) {\n debugStylesV('resolveId: mapped served stylesheet to source', {\n filename,\n resolvedPath: servedSourcePath,\n });\n return servedSourcePath + search;\n }\n\n if (stylesheetRegistry?.hasServed(filename)) {\n return id;\n }\n\n const componentStyles =\n stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n return componentStyles + new URL(id, 'http://localhost').search;\n }\n }\n\n return undefined;\n },\n async load(id) {\n // Virtual raw ids back JIT-emitted templateUrl/styleUrl imports.\n // virtual-modules-plugin resolves them; this plugin is the active\n // compilation plugin in compilation-API mode, so load must read the\n // backing file (jit=true is the test-mode default).\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Serve component stylesheets from registry\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const componentStyles = stylesheetRegistry?.getServedContent(filename);\n if (componentStyles) {\n stylesheetRegistry?.registerActiveRequest(id);\n return componentStyles;\n }\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (/[?&]raw\\b/.test(id)) return;\n if (transformFilter && !transformFilter(code, id)) {\n return;\n }\n\n // Angular emits every file in the program, not only files with\n // Angular decorators, and `@analogjs/platform` excludes `.ts` from\n // Vite's own transform. So serve Angular's output for any emitted\n // file; only the \"not emitted\" warning below is decorator-specific.\n const isAngular =\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n\n if (isTest) {\n if (deferInitialCompilation && !initialCompilation) {\n pendingCompilation = performCompilation(resolvedConfig);\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n if (testWatchMode && invalidated) {\n pendingCompilation = performCompilation(resolvedConfig, [id]);\n }\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n await hotUpdates.wait();\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilationApi('transform skip (file not emitted)', { id });\n if (isAngular) {\n this.warn(\n `[@analogjs/vite-plugin-angular]: \"${id}\" contains Angular decorators but is not in the TypeScript program. ` +\n `Ensure it is included in your tsconfig.`,\n );\n }\n return;\n }\n\n if (typescriptResult.warnings && typescriptResult.warnings.length > 0) {\n this.warn(`${typescriptResult.warnings.join('\\n')}`);\n }\n\n if (typescriptResult.errors && typescriptResult.errors.length > 0) {\n this.error(`${typescriptResult.errors.join('\\n')}`);\n }\n\n let data = typescriptResult.content ?? '';\n\n // Re-inject @vite-ignore for Angular HMR dynamic imports\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n if (hasMetaUrl) {\n data = injectViteIgnoreForHmrMetadata(data);\n }\n }\n\n return {\n code: data,\n map: null,\n };\n },\n },\n async closeBundle() {\n hotUpdates.close();\n await compilationLock;\n await angularCompilation?.close?.();\n angularCompilation = undefined;\n outputFiles.clear();\n classNames.clear();\n sourceFileCache.clear();\n tsconfigResolver.invalidateAll();\n stylesheetRegistry = undefined;\n pendingCompilation = null;\n initialCompilation = false;\n },\n };\n\n return [\n cssExtensionStyleResolverPlugin(),\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n virtualModulesPlugin({ jit: pluginOptions.jit }),\n compilerPlugin,\n pluginOptions.liveReload && liveReloadPlugin({ classNames, fileEmitter }),\n ...(isTest && !isStackBlitz\n ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map)\n : []),\n pluginOptions.jit &&\n jitPlugin({ inlineStylesExtension: pluginOptions.inlineStylesExtension }),\n buildOptimizerPlugin({\n jit: pluginOptions.jit,\n }),\n routerPlugin(),\n nxFolderPlugin(),\n encapsulationPlugin(),\n ].filter(Boolean) as Plugin[];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,IAAM,KADU,cAAc,YAAY,GAC/B,CAAA,CAAQ,YAAY;;;;;;AAuB/B,SAAgB,yBACd,UAA2C,CAAC,GAClC;CACV,IACE,qBAAqB,UACrB,OA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oB;CACtB,CAAC,CAAC,OAAO,OAAO;AAClB"}
1
+ {"version":3,"file":"compilation-api-plugin.js","names":[],"sources":["../../../../src/lib/compilation-api/compilation-api-plugin.ts"],"sourcesContent":["import { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';\nimport { union } from 'es-toolkit';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { basename, isAbsolute, join, resolve } from 'node:path';\nimport {\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from '../angular-build-context.js';\nimport { composeWithCompanions } from '../companion-plugins.js';\nimport { markModuleSelfAccepting } from '../component-styles-plugin.js';\nimport { createHotUpdateBatcher } from '../hot-update-batch.js';\nimport type { EmitFileResult } from '../models.js';\nimport { type FileReplacement } from '../plugins/file-replacements.plugin.js';\nimport { normalizeStylesheetDependencies } from '../style-preprocessor.js';\nimport {\n preprocessStylesheetResult,\n rewriteRelativeCssImports,\n} from '../stylesheet-registry.js';\nimport {\n DiagnosticModes,\n injectViteIgnoreForHmrMetadata,\n mapTemplateUpdatesToFiles,\n toAngularCompilationFileReplacements,\n} from '../utils/compilation-shared.js';\nimport {\n activateDeferredDebug,\n debugCompilationApi,\n debugCompiler,\n debugEmit,\n debugHmr,\n debugStyles,\n type DebugOption,\n} from '../utils/debug.js';\nimport {\n angularFullVersion,\n createAngularCompilation,\n SourceFileCache,\n} from '../utils/devkit.js';\nimport {\n createDepOptimizerConfig,\n TS_EXT_REGEX,\n} from '../utils/plugin-config.js';\nimport type { SourceFileCache as SourceFileCacheType } from '../utils/source-file-cache.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from '../virtual-modules-plugin.js';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * @experimental The Angular Compilation API plugin may change in future releases.\n */\nexport interface AngularCompilationPluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n supportedBrowsers?: string[];\n fileReplacements?: FileReplacement[];\n include?: string[];\n debug?: DebugOption;\n}\n\nfunction assertSupportedCompilationApi(): void {\n if (\n angularFullVersion < 200100 ||\n typeof createAngularCompilation !== 'function'\n ) {\n throw new Error(\n '[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.',\n );\n }\n}\n\n/**\n * Single-responsibility compiler plugin backed by Angular's `@angular/build`\n * Compilation API. Can be composed with custom pipelines via `AngularBuildContext`\n * or mounted with default companions via `angularCompilationPlugin()`.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function compilationApiPlugin(\n ctxOrOptions?:\n | AngularBuildContext\n | AngularCompilationPluginOptions\n | AngularBuildContextOptions,\n): Plugin {\n assertSupportedCompilationApi();\n\n const ctx = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions\n : createAngularBuildContext({\n ...ctxOrOptions,\n compilationBackend: 'compilation-api',\n });\n\n const ts = require('typescript') as typeof import('typescript');\n const { isTest } = ctx.options;\n\n // Persistent compilation instance — kept alive across rebuilds so Angular\n // can diff prior state and emit `templateUpdates` for HMR.\n let angularCompilation:\n | Awaited<ReturnType<typeof createAngularCompilationType>>\n | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const outputFiles = new Map<string, EmitFileResult>();\n let compilationLock = Promise.resolve();\n let pendingCompilation: Promise<void> | null = null;\n let initialCompilation = false;\n let viteServer: ViteDevServer | undefined;\n const hotUpdates = createHotUpdateBatcher((ids) =>\n performCompilation(ctx.resolvedConfig!, ids),\n );\n\n function resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath: string,\n config: ResolvedConfig,\n ): string {\n const includedFiles = ctx.tsconfigResolver.ensureIncludeCache();\n const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n const expandedGraphRoots =\n ctx.tsconfigResolver.collectExpandedTsconfigRoots(\n resolvedTsConfigPath,\n config,\n );\n const mergedRootNames = union(\n union(cached.rootNames, expandedGraphRoots),\n includedFiles,\n ).map((file) => normalizePath(file));\n\n if (mergedRootNames.length === cached.rootNames.length) {\n return resolvedTsConfigPath;\n }\n\n const resolvedCacheDir = isAbsolute(config.cacheDir)\n ? config.cacheDir\n : resolve(config.root, config.cacheDir);\n const wrapperDir = join(\n resolvedCacheDir,\n 'analog-angular',\n 'compilation-api',\n );\n const rawTsconfig = (ts.readConfigFile(\n resolvedTsConfigPath,\n ts.sys.readFile,\n ).config ?? {}) as { references?: unknown[] };\n const wrapperPayload = {\n extends: normalizePath(resolvedTsConfigPath),\n files: [...mergedRootNames].sort(),\n ...(rawTsconfig.references ? { references: rawTsconfig.references } : {}),\n };\n const wrapperHash = createHash('sha1')\n .update(JSON.stringify(wrapperPayload))\n .digest('hex')\n .slice(0, 12);\n const wrapperPath = join(\n wrapperDir,\n `tsconfig.includes.${wrapperHash}.json`,\n );\n\n mkdirSync(wrapperDir, { recursive: true });\n if (!existsSync(wrapperPath)) {\n writeFileSync(\n wrapperPath,\n `${JSON.stringify(wrapperPayload, null, 2)}\\n`,\n 'utf-8',\n );\n }\n\n debugCompilationApi('generated include wrapper tsconfig', {\n originalTsconfig: resolvedTsConfigPath,\n wrapperTsconfig: wrapperPath,\n includeCount: includedFiles.length,\n rootNameCount: mergedRootNames.length,\n });\n\n return wrapperPath;\n }\n\n const normalizeEmitterLookupId = (file: string): string => {\n const normalizedFile = normalizePath(file);\n if (!normalizedFile.startsWith('/@fs/')) return normalizedFile;\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n return normalizePath(fsPath);\n };\n\n let outputFile: ((file: string) => void) | undefined;\n const fileEmitter = (file: string): EmitFileResult | undefined => {\n const normalizedFile = normalizeEmitterLookupId(file);\n outputFile?.(normalizedFile);\n return outputFiles.get(normalizedFile);\n };\n\n ctx.hmr.setFileEmitter((file) => fileEmitter(file));\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: (): string => ctx.resolveTsConfigPath(),\n getSourceMap: (id: string): string | undefined =>\n outputFiles.get(normalizePath(id))?.map,\n hasEmitted: (id: string): boolean =>\n outputFiles.has(normalizeEmitterLookupId(id)),\n };\n\n ctx.registerCompiler({\n name: '@analogjs/vite-plugin-angular-compilation-api',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n async function performAngularCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n const stylesheetRegistry = ctx.styles.ensureRegistry();\n const compilation = (angularCompilation ??= await (\n createAngularCompilation as typeof createAngularCompilationType\n )(!!ctx.options.jit, false));\n const modifiedFiles = ids?.length\n ? new Set(ids.map((file) => normalizePath(file)))\n : undefined;\n if (modifiedFiles?.size) {\n sourceFileCache.invalidate(modifiedFiles);\n }\n if (modifiedFiles?.size && compilation.update) {\n debugCompilationApi('incremental update', {\n files: [...modifiedFiles],\n });\n await compilation.update(modifiedFiles);\n }\n\n const resolvedTsConfigPath = ctx.resolveTsConfigPath();\n const compilationApiTsConfigPath = resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath,\n config,\n );\n debugEmit('compilation initialize', {\n resolvedTsConfigPath,\n compilationApiTsConfigPath,\n modifiedFileCount: modifiedFiles?.size ?? 0,\n });\n const transformCompilerOptions = (\n tsCompilerOptions: Record<string, unknown>,\n ) => {\n if (ctx.shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (ctx.shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (compilation API)', {\n liveReload: ctx.options.liveReload,\n viteHmr: ctx.hasViteHmrTransport(),\n externalizeStylesRequested: ctx.externalizeStylesRequested,\n watchMode: ctx.watchMode,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = ctx.watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n return tsCompilerOptions;\n };\n const compilationResult = await compilation.initialize(\n compilationApiTsConfigPath,\n {\n fileReplacements: toAngularCompilationFileReplacements(\n ctx.options.fileReplacements,\n ctx.options.workspaceRoot,\n ),\n modifiedFiles,\n async transformStylesheet(\n data: string,\n containingFile: string,\n resourceFile?: string | null,\n order?: number,\n className?: string | null,\n ) {\n if (ctx.shouldEnableLiveReload() && className && containingFile) {\n ctx.hmr.classNames.set(normalizePath(containingFile), className);\n }\n\n const result = await ctx.styles.transformStylesheet({\n data,\n containingFile,\n resourceFile,\n order,\n className,\n readMissingResource: true,\n logger: config.logger,\n });\n\n return result?.content || '';\n },\n processWebWorker(workerFile: string) {\n return workerFile;\n },\n },\n angularFullVersion >= 220200\n ? {\n enableHmr: ctx.shouldEnableLiveReload(),\n externalRuntimeStyles: ctx.shouldExternalizeStyles(),\n includeTestMetadata: isTest || ctx.shouldEnableLiveReload(),\n instrumentForCoverage: !isTest,\n }\n : (transformCompilerOptions as unknown as Parameters<\n typeof compilation.initialize\n >[2]),\n );\n\n // Preprocess external stylesheets for Tailwind CSS @reference\n debugStyles('external stylesheets from compilation API', {\n count: compilationResult.externalStylesheets?.size ?? 0,\n hasPreprocessor: !!ctx.stylePreprocessor,\n hasInlineMap: !!stylesheetRegistry,\n });\n const preprocessStats = { total: 0, injected: 0, skipped: 0, errors: 0 };\n for (const [key, value] of compilationResult.externalStylesheets ?? []) {\n preprocessStats.total++;\n const angularHash = `${value}.css`;\n stylesheetRegistry.registerExternalRequest(angularHash, key);\n\n if (ctx.stylePreprocessor && existsSync(key)) {\n try {\n const rawCss = readFileSync(key, 'utf-8');\n const preprocessed = preprocessStylesheetResult(\n rawCss,\n key,\n ctx.stylePreprocessor,\n );\n const servedCss = rewriteRelativeCssImports(preprocessed.code, key);\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId: angularHash,\n sourcePath: key,\n originalCode: rawCss,\n normalizedCode: servedCss,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n },\n [key, normalizePath(key), basename(key), key.replace(/^\\//, '')],\n );\n\n if (servedCss && servedCss !== rawCss) {\n preprocessStats.injected++;\n } else {\n preprocessStats.skipped++;\n }\n } catch (e) {\n preprocessStats.errors++;\n console.warn(\n `[@analogjs/vite-plugin-angular] failed to preprocess external stylesheet: ${key}: ${e}`,\n );\n }\n } else {\n preprocessStats.skipped++;\n }\n }\n debugStyles('external stylesheet preprocessing complete', preprocessStats);\n\n const diagnostics = await compilation.diagnoseFiles(\n ctx.options.disableTypeChecking\n ? DiagnosticModes.All & ~DiagnosticModes.Semantic\n : DiagnosticModes.All,\n );\n\n const errors = diagnostics.errors?.length ? diagnostics.errors : [];\n const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];\n\n const templateUpdates = mapTemplateUpdatesToFiles(\n compilationResult.templateUpdates,\n );\n if (templateUpdates.size > 0) {\n debugHmr('compilation API template updates', {\n count: templateUpdates.size,\n files: [...templateUpdates.keys()],\n });\n }\n\n const affectedFiles = Array.from(await compilation.emitAffectedFiles());\n debugEmit('emitAffectedFiles summary', {\n count: affectedFiles.length,\n templateUpdateCount: templateUpdates.size,\n knownOutputCountBefore: outputFiles.size,\n });\n\n for (const file of affectedFiles) {\n const normalizedFilename = normalizePath(file.filename);\n const templateUpdate = templateUpdates.get(normalizedFilename);\n\n if (templateUpdate) {\n ctx.hmr.classNames.set(normalizedFilename, templateUpdate.className);\n }\n\n outputFiles.set(normalizedFilename, {\n content: file.contents,\n dependencies: [],\n errors: errors.map((error: { text?: string }) => error.text || ''),\n warnings: warnings.map(\n (warning: { text?: string }) => warning.text || '',\n ),\n hmrUpdateCode: templateUpdate?.code,\n hmrEligible: !!templateUpdate?.code,\n });\n }\n\n // Free the compilation before chunks render; `transform` still reads `outputFiles`.\n if (!ctx.watchMode && !isTest) {\n await compilation.close?.();\n angularCompilation = undefined;\n }\n }\n\n async function performCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n let releaseLock: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n releaseLock = r;\n });\n try {\n await previousLock;\n await ctx.refreshIntegrations(config);\n await performAngularCompilation(config, ids);\n } finally {\n releaseLock!();\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-compilation-api',\n api: compilerApi,\n enforce: 'pre' as const,\n async config(config, { command, mode }) {\n activateDeferredDebug(command);\n const resolution = ctx.initConfig(config, { command, mode });\n\n debugCompilationApi('enabled (Angular %s)', angularFullVersion);\n\n // Angular Compilation API handles TypeScript transforms — disable\n // esbuild/oxc so they don't compete.\n debugCompilationApi('esbuild/oxc disabled, Angular handles transforms');\n\n // The compilation API owns user-source transforms, but deps\n // optimization still bundles partial-compiled Angular libs from\n // node_modules (`ɵɵngDeclareInjectable/Factory`). Without the\n // linker plugin, those declarations reach the browser unprocessed\n // and Angular tries to JIT-compile them at runtime. Use the shared\n // `createDepOptimizerConfig` helper so the linker runs with identical\n // test/astro/cache arguments under both rolldown and esbuild.\n const preliminaryTsConfigPath = ctx.resolveTsConfigPath();\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd: resolution.isProd,\n jit: ctx.options.jit,\n watchMode: ctx.watchMode,\n isTest: ctx.options.isTest,\n isAstroIntegration: ctx.options.isAstroIntegration,\n });\n\n return {\n esbuild: undefined,\n oxc: undefined,\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n await ctx.resolveConfig(config);\n ctx.styles.resetRegistry(true);\n debugStyles('stylesheet registry initialized (Angular Compilation API)');\n },\n configureServer(server) {\n viteServer = server;\n hotUpdates.configureServer(server);\n\n const invalidateCompilation = async (): Promise<void> => {\n ctx.tsconfigResolver.invalidateAll();\n await performCompilation(ctx.resolvedConfig!);\n };\n server.watcher.on('add', invalidateCompilation);\n server.watcher.on('unlink', invalidateCompilation);\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n ctx.tsconfigResolver.invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n if (!ctx.deferInitialCompilation) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n await pendingCompilation;\n pendingCompilation = null;\n initialCompilation = true;\n }\n },\n async handleHotUpdate(hmrCtx) {\n if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {\n debugHmr('ignored file change', { file: hmrCtx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(hmrCtx.file)) {\n const [fileId] = hmrCtx.file.split('?');\n debugHmr('TS file changed', { file: hmrCtx.file, fileId });\n\n await hotUpdates.schedule(hmrCtx.file, [fileId]);\n\n let result: EmitFileResult | undefined;\n\n if (ctx.shouldEnableLiveReload()) {\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId),\n });\n }\n\n if (\n ctx.shouldEnableLiveReload() &&\n result?.hmrEligible &&\n ctx.hmr.classNames.get(fileId)\n ) {\n const relativeFileId = ctx.hmr.toComponentUpdateId(fileId);\n\n debugHmr('sending component update', { relativeFileId });\n ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);\n\n return hmrCtx.modules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm)$/.test(hmrCtx.file)) {\n debugHmr('template file changed', { file: hmrCtx.file });\n // Recompile to pick up template changes\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n }\n\n if (/\\.(css|less|sass|scss)$/.test(hmrCtx.file)) {\n debugHmr('stylesheet file changed', { file: hmrCtx.file });\n ctx.styles.refreshForFile(hmrCtx.file);\n }\n\n return hmrCtx.modules;\n },\n resolveId(id, importer) {\n const virtualId = resolveAngularVirtualId(id, importer, {\n jit: ctx.options.jit,\n resolvedConfig: ctx.resolvedConfig,\n });\n if (virtualId !== undefined) {\n return virtualId;\n }\n\n return ctx.styles.resolveComponentStyleId(id);\n },\n async load(id) {\n const virtualModule = await loadAngularVirtualModule(\n this,\n id,\n ctx.resolvedConfig,\n );\n if (virtualModule !== undefined) {\n return virtualModule;\n }\n\n return ctx.styles.loadComponentStyle(id);\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (/[?&]raw\\b/.test(id)) return;\n if (ctx.transformFilter && !ctx.transformFilter(code, id)) {\n return;\n }\n\n // Angular emits every file in the program, not only files with\n // Angular decorators, and `@analogjs/platform` excludes `.ts` from\n // Vite's own transform. So serve Angular's output for any emitted\n // file; only the \"not emitted\" warning below is decorator-specific.\n const isAngular =\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n\n if (isTest) {\n if (ctx.deferInitialCompilation && !initialCompilation) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n if (ctx.testWatchMode && invalidated) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!, [\n id,\n ]);\n }\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n await hotUpdates.wait();\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilationApi('transform skip (file not emitted)', { id });\n if (isAngular) {\n this.warn(\n `[@analogjs/vite-plugin-angular]: \"${id}\" contains Angular decorators but is not in the TypeScript program. ` +\n `Ensure it is included in your tsconfig.`,\n );\n }\n return;\n }\n\n if (typescriptResult.warnings && typescriptResult.warnings.length > 0) {\n this.warn(`${typescriptResult.warnings.join('\\n')}`);\n }\n\n if (typescriptResult.errors && typescriptResult.errors.length > 0) {\n this.error(`${typescriptResult.errors.join('\\n')}`);\n }\n\n let data = typescriptResult.content ?? '';\n\n // Re-inject @vite-ignore for Angular HMR dynamic imports\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n if (hasMetaUrl) {\n data = injectViteIgnoreForHmrMetadata(data);\n }\n }\n\n return {\n code: data,\n map: null,\n };\n },\n },\n async closeBundle() {\n hotUpdates.close();\n await compilationLock;\n await angularCompilation?.close?.();\n angularCompilation = undefined;\n outputFiles.clear();\n ctx.hmr.clear();\n sourceFileCache.clear();\n ctx.tsconfigResolver.invalidateAll();\n ctx.styles.clear();\n pendingCompilation = null;\n initialCompilation = false;\n },\n };\n}\n\n/**\n * Compiles Angular applications using Angular's private Compilation API.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function angularCompilationPlugin(\n options: AngularCompilationPluginOptions = {},\n): Plugin[] {\n assertSupportedCompilationApi();\n const ctx = createAngularBuildContext({\n ...options,\n compilationBackend: 'compilation-api',\n });\n return composeWithCompanions(ctx, compilationApiPlugin(ctx));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2DA,IAAM,UAAU,cAAc,YAAY,GAAG;AAkB7C,SAAS,gCAAsC;CAC7C,IACE,qBAAqB,UACrB,OAAO,6BAA6B,YAEpC,MAAM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,IAAI,iBAAiB,UAAU,iBAAiB,OAAO,SAAS,GAC9D,KAAK,MAAM,GAAG,iBAAiB,OAAO,KAAK,IAAI,GAAG;IAGpD,IAAI,OAAO,iBAAiB,WAAW;IAGvC,IAAI,KAAK,SAAS,SAAS,GACN;SAAA,KAAK,SAAS,uBAC7B,GACF,OAAO,+BAA+B,IAAI;IAAA;IAI9C,OAAO;KACL,MAAM;KACN,KAAK;IACP;GACF;EACF;EACA,MAAM,cAAc;GAClB,WAAW,MAAM;GACjB,MAAM;GACN,MAAM,oBAAoB,QAAQ;GAClC,qBAAqB,KAAA;GACrB,YAAY,MAAM;GAClB,IAAI,IAAI,MAAM;GACd,gBAAgB,MAAM;GACtB,IAAI,iBAAiB,cAAc;GACnC,IAAI,OAAO,MAAM;GACjB,qBAAqB;GACrB,qBAAqB;EACvB;CACF;AACF;;;;;;AAOA,SAAgB,yBACd,UAA2C,CAAC,GAClC;CACV,8BAA8B;CAC9B,MAAM,MAAM,0BAA0B;EACpC,GAAG;EACH,oBAAoB;CACtB,CAAC;CACD,OAAO,sBAAsB,KAAK,qBAAqB,GAAG,CAAC;AAC7D"}
@@ -0,0 +1,52 @@
1
+ import { type ModuleNode, type Plugin, type ViteDevServer } from "vite";
2
+ import { type AngularBuildContext, type AngularBuildContextOptions } from "./angular-build-context.js";
3
+ import type { StylePreprocessor, StylesheetDependency } from "./style-preprocessor.js";
4
+ import { AnalogStylesheetRegistry } from "./stylesheet-registry.js";
5
+ import { describeStylesheetContent } from "./utils/compilation-shared.js";
6
+ export interface ComponentStylesheetPipelineDiagnosis {
7
+ file: string;
8
+ sourcePath?: string;
9
+ source?: ReturnType<typeof describeStylesheetContent>;
10
+ registry?: ReturnType<typeof describeStylesheetContent>;
11
+ dependencies: StylesheetDependency[];
12
+ diagnostics: ReturnType<AnalogStylesheetRegistry["getDiagnosticsForSource"]>;
13
+ tags: string[];
14
+ directModuleId?: string;
15
+ directModuleUrl?: string;
16
+ trackedRequestIds: string[];
17
+ wrapperCount: number;
18
+ anomalies: string[];
19
+ hints: string[];
20
+ }
21
+ /**
22
+ * Self-contained Vite plugin that resolves and serves externalized Angular
23
+ * component stylesheets (`?ngcomp=...`) from the shared `AngularBuildContext`
24
+ * stylesheet registry and refreshes served records on source CSS edits.
25
+ */
26
+ export declare function componentStylesPlugin(ctxOrOptions?: AngularBuildContext | AngularBuildContextOptions): Plugin;
27
+ export declare function markModuleSelfAccepting(mod: ModuleNode): ModuleNode;
28
+ /**
29
+ * Returns every live Vite module that can legitimately represent a changed
30
+ * Angular resource file.
31
+ *
32
+ * For normal files, `getModulesByFile()` is enough. For Angular component
33
+ * stylesheets, it is not: the browser often holds virtual hashed requests
34
+ * (`/abc123.css?direct&ngcomp=...` and `/abc123.css?ngcomp=...`) that are no
35
+ * longer discoverable from the original source path alone. We therefore merge:
36
+ * - watcher event modules
37
+ * - module-graph modules by source file
38
+ * - registry-tracked live request ids resolved back through the module graph
39
+ */
40
+ export declare function getModulesForChangedFile(server: ViteDevServer, file: string, eventModules?: readonly ModuleNode[], stylesheetRegistry?: AnalogStylesheetRegistry): Promise<ModuleNode[]>;
41
+ export declare function isModuleForChangedResource(mod: ModuleNode, changedFile: string, stylesheetRegistry?: AnalogStylesheetRegistry): boolean;
42
+ export declare function diagnoseComponentStylesheetPipeline(changedFile: string, directModule: ModuleNode, stylesheetRegistry: AnalogStylesheetRegistry | undefined, wrapperModules: ModuleNode[], stylePreprocessor?: StylePreprocessor): ComponentStylesheetPipelineDiagnosis;
43
+ export declare function findComponentStylesheetWrapperModules(server: ViteDevServer, changedFile: string, directModule: ModuleNode, fileModules: ModuleNode[], stylesheetRegistry?: AnalogStylesheetRegistry): Promise<ModuleNode[]>;
44
+ export declare function findTemplateOwnerModules(server: ViteDevServer, resourceFile: string): ModuleNode[];
45
+ export declare function handleDirectComponentStyleHmr(options: {
46
+ server: ViteDevServer;
47
+ file: string;
48
+ directModule: ModuleNode;
49
+ fileModules: ModuleNode[];
50
+ stylesheetRegistry?: AnalogStylesheetRegistry;
51
+ stylePreprocessor?: StylePreprocessor;
52
+ }): Promise<ModuleNode[]>;
@@ -0,0 +1,353 @@
1
+ import { debugHmr, debugHmrV, debugStylesV } from "./utils/debug.js";
2
+ import { getComponentStyleSheetMeta, isComponentStyleSheet } from "./encapsulation-plugin.js";
3
+ import { preprocessStylesheet, rewriteRelativeCssImports } from "./stylesheet-registry.js";
4
+ import { describeStylesheetContent } from "./utils/compilation-shared.js";
5
+ import { ensureAngularBuildContext, getFilenameFromPath } from "./angular-build-context.js";
6
+ import { union } from "es-toolkit";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { normalizePath } from "vite";
9
+ //#region packages/vite-plugin-angular/src/lib/component-styles-plugin.ts
10
+ /**
11
+ * Self-contained Vite plugin that resolves and serves externalized Angular
12
+ * component stylesheets (`?ngcomp=...`) from the shared `AngularBuildContext`
13
+ * stylesheet registry and refreshes served records on source CSS edits.
14
+ */
15
+ function componentStylesPlugin(ctxOrOptions) {
16
+ const ctx = ensureAngularBuildContext(ctxOrOptions);
17
+ return {
18
+ name: "@analogjs/vite-plugin-angular:component-styles",
19
+ enforce: "pre",
20
+ async configResolved(config) {
21
+ await ctx.resolveConfig(config);
22
+ },
23
+ resolveId(id) {
24
+ return ctx.styles.resolveComponentStyleId(id);
25
+ },
26
+ load(id) {
27
+ return ctx.styles.loadComponentStyle(id);
28
+ },
29
+ handleHotUpdate(hmrCtx) {
30
+ if (/\.(css|less|sass|scss)$/.test(hmrCtx.file)) {
31
+ debugHmr("stylesheet file changed", { file: hmrCtx.file });
32
+ ctx.styles.refreshForFile(hmrCtx.file);
33
+ }
34
+ }
35
+ };
36
+ }
37
+ function markModuleSelfAccepting(mod) {
38
+ if ("_clientModule" in mod) mod["_clientModule"].isSelfAccepting = true;
39
+ return {
40
+ ...mod,
41
+ isSelfAccepting: true
42
+ };
43
+ }
44
+ /**
45
+ * Returns every live Vite module that can legitimately represent a changed
46
+ * Angular resource file.
47
+ *
48
+ * For normal files, `getModulesByFile()` is enough. For Angular component
49
+ * stylesheets, it is not: the browser often holds virtual hashed requests
50
+ * (`/abc123.css?direct&ngcomp=...` and `/abc123.css?ngcomp=...`) that are no
51
+ * longer discoverable from the original source path alone. We therefore merge:
52
+ * - watcher event modules
53
+ * - module-graph modules by source file
54
+ * - registry-tracked live request ids resolved back through the module graph
55
+ */
56
+ async function getModulesForChangedFile(server, file, eventModules = [], stylesheetRegistry) {
57
+ const normalizedFile = normalizePath(file.split("?")[0]);
58
+ const modules = /* @__PURE__ */ new Map();
59
+ for (const mod of eventModules) if (mod.id) modules.set(mod.id, mod);
60
+ server.moduleGraph.getModulesByFile(normalizedFile)?.forEach((mod) => {
61
+ if (mod.id) modules.set(mod.id, mod);
62
+ });
63
+ const stylesheetRequestIds = stylesheetRegistry?.getRequestIdsForSource(normalizedFile) ?? [];
64
+ const requestIdHits = [];
65
+ for (const requestId of stylesheetRequestIds) {
66
+ const candidates = [requestId, requestId.startsWith("/") ? requestId : `/${requestId}`];
67
+ for (const candidate of candidates) {
68
+ const mod = await server.moduleGraph.getModuleByUrl(candidate) ?? server.moduleGraph.getModuleById(candidate);
69
+ requestIdHits.push({
70
+ requestId,
71
+ candidate,
72
+ via: mod?.url === candidate ? "url" : "id",
73
+ moduleId: mod?.id ?? void 0
74
+ });
75
+ if (mod?.id) modules.set(mod.id, mod);
76
+ }
77
+ }
78
+ debugHmrV("getModulesForChangedFile registry lookup", {
79
+ file: normalizedFile,
80
+ stylesheetRequestIds,
81
+ requestIdHits,
82
+ resolvedModuleIds: [...modules.keys()]
83
+ });
84
+ return [...modules.values()];
85
+ }
86
+ function isModuleForChangedResource(mod, changedFile, stylesheetRegistry) {
87
+ const normalizedChangedFile = normalizePath(changedFile.split("?")[0]);
88
+ if (normalizePath((mod.file ?? "").split("?")[0]) === normalizedChangedFile) return true;
89
+ if (!mod.id) return false;
90
+ const requestPath = getFilenameFromPath(mod.id);
91
+ const sourcePath = stylesheetRegistry?.resolveExternalSource(requestPath) ?? stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(requestPath) ?? stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\//, ""));
92
+ return normalizePath((sourcePath ?? "").split("?")[0]) === normalizedChangedFile;
93
+ }
94
+ function resolveDirectStylesheetSourcePath(normalizedFile, directModule, stylesheetRegistry) {
95
+ const directRequestPath = directModule.id ? getFilenameFromPath(directModule.id) : void 0;
96
+ return {
97
+ directRequestPath,
98
+ sourcePath: directRequestPath ? stylesheetRegistry?.resolveExternalSource(directRequestPath) ?? stylesheetRegistry?.resolveExternalSource(directRequestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(directRequestPath) ?? stylesheetRegistry?.getServedSourcePath(directRequestPath.replace(/^\//, "")) : normalizedFile
99
+ };
100
+ }
101
+ function diagnoseComponentStylesheetPipeline(changedFile, directModule, stylesheetRegistry, wrapperModules, stylePreprocessor) {
102
+ const normalizedFile = normalizePath(changedFile.split("?")[0]);
103
+ const sourceExists = existsSync(normalizedFile);
104
+ const sourceCode = sourceExists ? readFileSync(normalizedFile, "utf-8") : void 0;
105
+ const { directRequestPath, sourcePath } = resolveDirectStylesheetSourcePath(normalizedFile, directModule, stylesheetRegistry);
106
+ const registryCode = directRequestPath ? stylesheetRegistry?.getServedContent(directRequestPath) : void 0;
107
+ const trackedRequestIds = stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? "") ?? [];
108
+ const dependencies = stylesheetRegistry?.getDependenciesForSource(sourcePath ?? "") ?? [];
109
+ const diagnostics = stylesheetRegistry?.getDiagnosticsForSource(sourcePath ?? "") ?? [];
110
+ const tags = stylesheetRegistry?.getTagsForSource(sourcePath ?? "") ?? [];
111
+ const anomalies = [];
112
+ const hints = [];
113
+ if (!sourceExists) {
114
+ anomalies.push("source_file_missing");
115
+ hints.push("The stylesheet watcher fired for a file that no longer exists on disk.");
116
+ }
117
+ if (!registryCode) {
118
+ anomalies.push("registry_content_missing");
119
+ hints.push("The stylesheet registry has no served content for the direct module request path.");
120
+ }
121
+ const registryDescription = registryCode ? describeStylesheetContent(registryCode) : void 0;
122
+ let sourceDescription;
123
+ if (sourceCode !== void 0) try {
124
+ let expectedRegistryCode = preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor);
125
+ expectedRegistryCode = rewriteRelativeCssImports(expectedRegistryCode, normalizedFile);
126
+ sourceDescription = describeStylesheetContent(expectedRegistryCode);
127
+ } catch {
128
+ anomalies.push("source_preprocess_failed");
129
+ hints.push("Diagnostic preprocessing of the source stylesheet failed; falling back to raw source summary.");
130
+ sourceDescription = describeStylesheetContent(sourceCode);
131
+ }
132
+ if (sourceDescription && registryDescription && !anomalies.includes("source_preprocess_failed") && sourceDescription.digest !== registryDescription.digest) {
133
+ anomalies.push("source_registry_mismatch");
134
+ hints.push("The source file changed, but the served stylesheet content in the registry is still stale.");
135
+ }
136
+ if (trackedRequestIds.length === 0) {
137
+ anomalies.push("no_tracked_requests");
138
+ hints.push("No live stylesheet requests are tracked for this source file, so HMR has no browser-facing target.");
139
+ }
140
+ if (trackedRequestIds.some((id) => id.includes("?ngcomp=")) && wrapperModules.length === 0) {
141
+ anomalies.push("tracked_wrapper_missing_from_module_graph");
142
+ hints.push("A wrapper request id is known, but Vite did not expose a live wrapper module during this HMR pass.");
143
+ }
144
+ if (trackedRequestIds.every((id) => !id.includes("?ngcomp=")) && wrapperModules.length === 0) {
145
+ anomalies.push("wrapper_not_yet_tracked");
146
+ hints.push("Only direct stylesheet requests were tracked during this HMR pass; the wrapper request may be appearing too late.");
147
+ }
148
+ return {
149
+ file: changedFile,
150
+ sourcePath,
151
+ source: sourceDescription,
152
+ registry: registryDescription,
153
+ dependencies,
154
+ diagnostics,
155
+ tags,
156
+ directModuleId: directModule.id ?? void 0,
157
+ directModuleUrl: directModule.url,
158
+ trackedRequestIds,
159
+ wrapperCount: wrapperModules.length,
160
+ anomalies,
161
+ hints
162
+ };
163
+ }
164
+ async function findComponentStylesheetWrapperModules(server, changedFile, directModule, fileModules, stylesheetRegistry) {
165
+ const wrapperModules = /* @__PURE__ */ new Map();
166
+ for (const mod of fileModules) if (mod.id && mod.type === "js" && isComponentStyleSheet(mod.id) && isModuleForChangedResource(mod, changedFile, stylesheetRegistry)) wrapperModules.set(mod.id, mod);
167
+ const directRequestIds = /* @__PURE__ */ new Set();
168
+ if (directModule.id) directRequestIds.add(directModule.id);
169
+ if (directModule.url) directRequestIds.add(directModule.url);
170
+ const requestPath = directModule.id ? getFilenameFromPath(directModule.id) : void 0;
171
+ const sourcePath = requestPath ? stylesheetRegistry?.resolveExternalSource(requestPath) ?? stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(requestPath) ?? stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\//, "")) : void 0;
172
+ for (const requestId of stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? "") ?? []) if (requestId.includes("?ngcomp=")) directRequestIds.add(requestId);
173
+ const candidateWrapperIds = [...directRequestIds].filter((id) => id.includes("?direct&ngcomp=")).map((id) => id.replace("?direct&ngcomp=", "?ngcomp="));
174
+ const lookupHits = [];
175
+ for (const candidate of candidateWrapperIds) {
176
+ const mod = await server.moduleGraph.getModuleByUrl(candidate) ?? server.moduleGraph.getModuleById(candidate);
177
+ lookupHits.push({
178
+ candidate,
179
+ via: mod?.url === candidate ? "url" : mod ? "id" : void 0,
180
+ moduleId: mod?.id ?? void 0,
181
+ moduleType: mod?.type
182
+ });
183
+ if (mod?.id && mod.type === "js" && isComponentStyleSheet(mod.id) && isModuleForChangedResource(mod, changedFile, stylesheetRegistry)) wrapperModules.set(mod.id, mod);
184
+ }
185
+ debugHmrV("component stylesheet wrapper lookup", {
186
+ file: changedFile,
187
+ sourcePath,
188
+ directModuleId: directModule.id,
189
+ directModuleUrl: directModule.url,
190
+ candidateWrapperIds,
191
+ lookupHits
192
+ });
193
+ if (wrapperModules.size === 0) debugHmrV("component stylesheet wrapper lookup empty", {
194
+ file: changedFile,
195
+ sourcePath,
196
+ directModuleId: directModule.id,
197
+ directModuleUrl: directModule.url,
198
+ candidateWrapperIds
199
+ });
200
+ return [...wrapperModules.values()];
201
+ }
202
+ function findTemplateOwnerModules(server, resourceFile) {
203
+ const candidateTsFiles = [normalizePath(resourceFile.split("?")[0]).replace(/\.(html|htm)$/i, ".ts")];
204
+ const modules = /* @__PURE__ */ new Map();
205
+ for (const candidate of candidateTsFiles) server.moduleGraph.getModulesByFile(candidate)?.forEach((mod) => {
206
+ if (mod.id) modules.set(mod.id, mod);
207
+ });
208
+ return [...modules.values()];
209
+ }
210
+ function sendCssUpdate(server, update) {
211
+ const timestamp = Date.now();
212
+ debugHmrV("ws send: css-update", {
213
+ ...update,
214
+ timestamp
215
+ });
216
+ server.ws.send({
217
+ type: "update",
218
+ updates: [{
219
+ type: "css-update",
220
+ timestamp,
221
+ path: update.path,
222
+ acceptedPath: update.acceptedPath
223
+ }]
224
+ });
225
+ }
226
+ function sendFullReload(server, details) {
227
+ debugHmrV("ws send: full-reload", details);
228
+ server.ws.send("analog:debug-full-reload", details);
229
+ server.ws.send({ type: "full-reload" });
230
+ }
231
+ function logComponentStylesheetHmrOutcome(details) {
232
+ const pitfalls = [];
233
+ const rejectedPreferredPaths = [];
234
+ const hints = [];
235
+ if (details.encapsulation === "shadow") {
236
+ pitfalls.push("shadow-encapsulation");
237
+ rejectedPreferredPaths.push("css-update");
238
+ hints.push("Shadow DOM styles cannot rely on Vite CSS patching because Angular applies them inside a shadow root.");
239
+ }
240
+ if (details.diagnosis.anomalies.includes("wrapper_not_yet_tracked")) {
241
+ pitfalls.push("wrapper-not-yet-tracked");
242
+ rejectedPreferredPaths.push("css-update");
243
+ 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.");
244
+ }
245
+ if (details.diagnosis.anomalies.includes("tracked_wrapper_missing_from_module_graph")) {
246
+ pitfalls.push("tracked-wrapper-missing-from-module-graph");
247
+ rejectedPreferredPaths.push("css-update");
248
+ hints.push("A wrapper request id is known, but Vite could not resolve a live wrapper module for targeted CSS HMR.");
249
+ }
250
+ debugHmrV("component stylesheet hmr outcome", {
251
+ file: details.file,
252
+ outcome: details.outcome,
253
+ encapsulation: details.encapsulation,
254
+ directModuleId: details.directModuleId,
255
+ wrapperIds: details.wrapperIds ?? [],
256
+ preferredPath: details.encapsulation === "shadow" ? "full-reload" : "css-update",
257
+ rejectedPreferredPaths: [...new Set(rejectedPreferredPaths)],
258
+ pitfalls: [...new Set(pitfalls)],
259
+ anomalies: details.diagnosis.anomalies,
260
+ hints: [.../* @__PURE__ */ new Set([...details.diagnosis.hints, ...hints])]
261
+ });
262
+ }
263
+ async function handleDirectComponentStyleHmr(options) {
264
+ const { server, file, directModule, fileModules, stylesheetRegistry, stylePreprocessor } = options;
265
+ const { encapsulation } = getComponentStyleSheetMeta(directModule.id);
266
+ const wrapperModules = await findComponentStylesheetWrapperModules(server, file, directModule, fileModules, stylesheetRegistry);
267
+ const { sourcePath } = resolveDirectStylesheetSourcePath(normalizePath(file.split("?")[0]), directModule, stylesheetRegistry);
268
+ const trackedRequestIds = stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? "") ?? [];
269
+ let stylesheetDiagnosis;
270
+ if (debugHmrV.enabled) try {
271
+ stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(file, directModule, stylesheetRegistry, wrapperModules, stylePreprocessor);
272
+ } catch (error) {
273
+ debugHmrV("component stylesheet pipeline diagnosis failed", {
274
+ file,
275
+ error: error instanceof Error ? error.message : String(error)
276
+ });
277
+ }
278
+ debugStylesV("HMR: component stylesheet changed", {
279
+ file: directModule.file,
280
+ encapsulation
281
+ });
282
+ debugHmrV("component stylesheet wrapper modules", {
283
+ file,
284
+ wrapperCount: wrapperModules.length,
285
+ wrapperIds: wrapperModules.map((mod) => mod.id),
286
+ availableModuleIds: fileModules.map((mod) => mod.id)
287
+ });
288
+ if (stylesheetDiagnosis) debugHmrV("component stylesheet pipeline diagnosis", stylesheetDiagnosis);
289
+ server.moduleGraph.invalidateModule(directModule);
290
+ debugHmrV("component stylesheet direct module invalidated", {
291
+ file,
292
+ directModuleId: directModule.id,
293
+ directModuleUrl: directModule.url,
294
+ reason: "Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues."
295
+ });
296
+ const trackedWrapperRequestIds = trackedRequestIds.filter((id) => id.includes("?ngcomp="));
297
+ if (encapsulation !== "shadow" && (wrapperModules.length > 0 || trackedWrapperRequestIds.length > 0)) {
298
+ wrapperModules.forEach((mod) => server.moduleGraph.invalidateModule(mod));
299
+ debugHmrV("sending css-update for component stylesheet", {
300
+ file,
301
+ path: directModule.url,
302
+ acceptedPath: directModule.file,
303
+ wrapperCount: wrapperModules.length,
304
+ trackedWrapperRequestIds,
305
+ 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."
306
+ });
307
+ sendCssUpdate(server, {
308
+ path: directModule.url,
309
+ acceptedPath: directModule.file
310
+ });
311
+ if (stylesheetDiagnosis) logComponentStylesheetHmrOutcome({
312
+ file,
313
+ encapsulation,
314
+ diagnosis: stylesheetDiagnosis,
315
+ outcome: "css-update",
316
+ directModuleId: directModule.id ?? void 0,
317
+ wrapperIds: wrapperModules.map((mod) => mod.id).filter((id) => id !== null)
318
+ });
319
+ return union(fileModules.filter((mod) => {
320
+ return mod.file !== file || mod.id !== directModule.id;
321
+ }).map((mod) => {
322
+ if (mod.file === file) return markModuleSelfAccepting(mod);
323
+ return mod;
324
+ }), wrapperModules.map((mod) => markModuleSelfAccepting(mod)));
325
+ }
326
+ debugHmrV("component stylesheet hmr fallback: full reload", {
327
+ file,
328
+ encapsulation,
329
+ reason: trackedWrapperRequestIds.length === 0 ? "missing-wrapper-module" : encapsulation === "shadow" ? "shadow-encapsulation" : "tracked-wrapper-still-not-patchable",
330
+ directId: directModule.id,
331
+ trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(file) ?? []
332
+ });
333
+ if (stylesheetDiagnosis) logComponentStylesheetHmrOutcome({
334
+ file,
335
+ encapsulation,
336
+ diagnosis: stylesheetDiagnosis,
337
+ outcome: "full-reload",
338
+ directModuleId: directModule.id ?? void 0,
339
+ wrapperIds: wrapperModules.map((mod) => mod.id).filter((id) => id !== null)
340
+ });
341
+ sendFullReload(server, {
342
+ file,
343
+ encapsulation,
344
+ reason: wrapperModules.length === 0 ? "missing-wrapper-module" : "shadow-encapsulation",
345
+ directId: directModule.id,
346
+ trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(file) ?? []
347
+ });
348
+ return [];
349
+ }
350
+ //#endregion
351
+ export { componentStylesPlugin, diagnoseComponentStylesheetPipeline, findComponentStylesheetWrapperModules, findTemplateOwnerModules, getModulesForChangedFile, handleDirectComponentStyleHmr, isModuleForChangedResource, markModuleSelfAccepting };
352
+
353
+ //# sourceMappingURL=component-styles-plugin.js.map