@analogjs/vite-plugin-angular 3.0.0-alpha.25 → 3.0.0-alpha.26

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.
@@ -1 +1 @@
1
- {"version":3,"file":"angular-vite-plugin.js","names":[],"sources":["../../../src/lib/angular-vite-plugin.ts"],"sourcesContent":["import { NgtscProgram } from '@angular/compiler-cli';\nimport { union } from 'es-toolkit';\nimport { createHash } from 'node:crypto';\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n} from 'node:path';\nimport * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport { createRequire } from 'node:module';\nimport * as ts from 'typescript';\nimport { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';\n\nimport * as ngCompiler from '@angular/compiler';\nimport { globSync } from 'tinyglobby';\nimport {\n defaultClientConditions,\n ModuleNode,\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\nimport { buildOptimizerPlugin } from './angular-build-optimizer-plugin.js';\nimport { jitPlugin } from './angular-jit-plugin.js';\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from './compiler-plugin.js';\nimport {\n getAngularComponentMetadata,\n StyleUrlsResolver,\n TemplateUrlsResolver,\n} from './component-resolvers.js';\nimport {\n augmentHostWithCaching,\n augmentHostWithResources,\n augmentProgramWithVersioning,\n mergeTransformers,\n} from './host.js';\nimport type { StylePreprocessor } from './style-preprocessor.js';\n\nimport { angularVitestPlugins } from './angular-vitest-plugin.js';\nimport {\n createAngularCompilation,\n createJitResourceTransformer,\n SourceFileCache,\n angularFullVersion,\n} from './utils/devkit.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugCompilationApi,\n debugCompiler,\n debugCompilerV,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n debugTailwind,\n debugTailwindV,\n type DebugOption,\n} from './utils/debug.js';\nimport { getJsTransformConfigKey, isRolldown } from './utils/rolldown.js';\nimport { type SourceFileCache as SourceFileCacheType } from './utils/source-file-cache.js';\n\nconst require = createRequire(import.meta.url);\n\nimport { pendingTasksPlugin } from './angular-pending-tasks.plugin.js';\nimport { liveReloadPlugin } from './live-reload-plugin.js';\nimport { EmitFileResult } from './models.js';\nimport { nxFolderPlugin } from './nx-folder-plugin.js';\nimport {\n FileReplacement,\n FileReplacementSSR,\n FileReplacementWith,\n replaceFiles,\n} from './plugins/file-replacements.plugin.js';\nimport { routerPlugin } from './router-plugin.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheet,\n registerStylesheetContent,\n rewriteRelativeCssImports,\n} from './stylesheet-registry.js';\n\nexport enum DiagnosticModes {\n None = 0,\n Option = 1 << 0,\n Syntactic = 1 << 1,\n Semantic = 1 << 2,\n All = Option | Syntactic | Semantic,\n}\n\nexport interface PluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n advanced?: {\n /**\n * Custom TypeScript transformers that are run before Angular compilation\n */\n tsTransformers?: ts.CustomTransformers;\n };\n supportedBrowsers?: string[];\n transformFilter?: (code: string, id: string) => boolean;\n /**\n * Additional files to include in compilation\n */\n include?: string[];\n additionalContentDirs?: string[];\n /**\n * Enables Angular's HMR during development/watch mode.\n *\n * Defaults to `true` for watch mode. Set to `false` to disable HMR while\n * keeping other stylesheet externalization behavior available when needed.\n */\n hmr?: boolean;\n /**\n * @deprecated Use `hmr` instead. Kept as a compatibility alias.\n */\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n fileReplacements?: FileReplacement[];\n experimental?: {\n useAngularCompilationAPI?: boolean;\n };\n /**\n * Enable debug logging for specific scopes.\n *\n * - `true` → enables all `analog:angular:*` scopes\n * - `string[]` → enables listed namespaces (e.g. `['analog:angular:tailwind']`)\n * - `{ scopes?, mode? }` → object form with optional `mode: 'build' | 'dev'`\n * to restrict output to a specific Vite command (omit for both)\n *\n * Also responds to the `DEBUG` env var (Node.js) or `localStorage.debug`\n * (browser), using the `obug` convention.\n */\n debug?: DebugOption;\n /**\n * Optional preprocessor that transforms component CSS before it enters Vite's\n * preprocessCSS pipeline. Runs on every component stylesheet (both external\n * `.component.css` files and inline `styles: [...]` blocks).\n *\n * @param code - Raw CSS content of the component stylesheet\n * @param filename - Resolved file path of the stylesheet (or containing .ts file for inline styles)\n * @returns Transformed CSS string, or the original code if no transformation is needed\n */\n stylePreprocessor?: StylePreprocessor;\n /**\n * First-class Tailwind CSS v4 integration for Angular component styles.\n *\n * Angular's compiler processes component CSS through Vite's `preprocessCSS()`,\n * which runs `@tailwindcss/vite` — but each component stylesheet is processed\n * in isolation without access to the root Tailwind configuration (prefix, @theme,\n * @custom-variant, @plugin definitions). This causes errors like:\n *\n * \"Cannot apply utility class `sa:grid` because the `sa` variant does not exist\"\n *\n * The `tailwindCss` option solves this by auto-injecting a `@reference` directive\n * into every component CSS file that uses Tailwind utilities, pointing it to the\n * root Tailwind stylesheet so `@tailwindcss/vite` can resolve the full configuration.\n *\n * @example Basic usage — reference a root Tailwind CSS file:\n * ```ts\n * import { resolve } from 'node:path';\n *\n * angular({\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, 'src/styles/tailwind.css'),\n * },\n * })\n * ```\n *\n * @example With prefix detection — only inject for files using specific prefixes:\n * ```ts\n * angular({\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, 'src/styles/tailwind.css'),\n * // Only inject @reference into files that use these prefixed classes\n * prefixes: ['sa:', 'tw:'],\n * },\n * })\n * ```\n *\n * @example AnalogJS platform — passed through the `vite` option:\n * ```ts\n * analog({\n * vite: {\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, '../../../libs/meritos/tailwind.config.css'),\n * },\n * },\n * })\n * ```\n */\n tailwindCss?: {\n /**\n * Absolute path to the root Tailwind CSS file that contains `@import \"tailwindcss\"`,\n * `@theme`, `@custom-variant`, and `@plugin` definitions.\n *\n * A `@reference` directive pointing to this file will be auto-injected into\n * component CSS files that use Tailwind utilities.\n */\n rootStylesheet: string;\n /**\n * Optional list of class prefixes to detect (e.g. `['sa:', 'tw:']`).\n * When provided, `@reference` is only injected into component CSS files that\n * contain at least one of these prefixes. When omitted, `@reference` is injected\n * into all component CSS files that contain `@apply` or `@` directives.\n *\n * @default undefined — inject into all component CSS files with `@apply`\n */\n prefixes?: string[];\n };\n}\n\nexport function normalizeIncludeGlob(\n workspaceRoot: string,\n glob: string,\n): string {\n const normalizedWorkspaceRoot = normalizePath(resolve(workspaceRoot));\n const normalizedGlob = normalizePath(glob);\n\n if (\n normalizedGlob === normalizedWorkspaceRoot ||\n normalizedGlob.startsWith(`${normalizedWorkspaceRoot}/`)\n ) {\n return normalizedGlob;\n }\n\n if (normalizedGlob.startsWith('/')) {\n return `${normalizedWorkspaceRoot}${normalizedGlob}`;\n }\n\n return normalizePath(resolve(normalizedWorkspaceRoot, normalizedGlob));\n}\n\n/**\n * TypeScript file extension regex\n * Match .(c or m)ts, .ts extensions with an optional ? for query params\n * Ignore .tsx extensions\n */\nconst TS_EXT_REGEX = /\\.[cm]?(ts)[^x]?\\??/;\nconst classNames = new Map();\n\nexport function evictDeletedFileMetadata(\n file: string,\n {\n removeActiveGraphMetadata,\n removeStyleOwnerMetadata,\n classNamesMap,\n fileTransformMap,\n }: {\n removeActiveGraphMetadata: (file: string) => void;\n removeStyleOwnerMetadata: (file: string) => void;\n classNamesMap: Map<string, string>;\n fileTransformMap: Map<string, string>;\n },\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n removeActiveGraphMetadata(normalizedFile);\n removeStyleOwnerMetadata(normalizedFile);\n classNamesMap.delete(normalizedFile);\n fileTransformMap.delete(normalizedFile);\n}\n\nexport function injectViteIgnoreForHmrMetadata(code: string): string {\n let patched = code.replace(\n /\\bimport\\(([a-zA-Z_$][\\w$]*\\.\\u0275\\u0275getReplaceMetadataURL)/g,\n 'import(/* @vite-ignore */ $1',\n );\n\n if (patched === code) {\n patched = patched.replace(\n /import\\((\\S+getReplaceMetadataURL)/g,\n 'import(/* @vite-ignore */ $1',\n );\n }\n\n return patched;\n}\n\nexport function isIgnoredHmrFile(file: string): boolean {\n return file.endsWith('.tsbuildinfo');\n}\n\ninterface DeclarationFile {\n declarationFileDir: string;\n declarationPath: string;\n data: string;\n}\n\n/**\n * Builds a resolved stylePreprocessor function from plugin options.\n *\n * When `tailwindCss` is configured, creates an injector that prepends\n * `@reference \"<rootStylesheet>\"` into component CSS that uses Tailwind\n * utilities. Uses absolute paths because Angular's externalRuntimeStyles\n * serves component CSS as virtual modules (hash-based IDs) with no\n * meaningful directory — relative paths can't resolve from a hash.\n *\n * If both `tailwindCss` and `stylePreprocessor` are provided, they are\n * chained: Tailwind reference injection runs first, then the user's\n * custom preprocessor.\n */\nfunction buildStylePreprocessor(\n options?: PluginOptions,\n): ((code: string, filename: string) => string) | undefined {\n const userPreprocessor = options?.stylePreprocessor;\n const tw = options?.tailwindCss;\n\n if (!tw && !userPreprocessor) {\n return undefined;\n }\n\n let tailwindPreprocessor:\n | ((code: string, filename: string) => string)\n | undefined;\n\n if (tw) {\n const rootStylesheet = tw.rootStylesheet;\n const prefixes = tw.prefixes;\n debugTailwind('configured', { rootStylesheet, prefixes });\n\n if (!existsSync(rootStylesheet)) {\n console.warn(\n `[@analogjs/vite-plugin-angular] tailwindCss.rootStylesheet not found ` +\n `at \"${rootStylesheet}\". @reference directives will point to a ` +\n `non-existent file, which will cause Tailwind CSS errors. ` +\n `Ensure the path is absolute and the file exists.`,\n );\n }\n\n tailwindPreprocessor = (code: string, filename: string): string => {\n // Skip files that already define the Tailwind config\n if (\n code.includes('@reference') ||\n code.includes('@import \"tailwindcss\"') ||\n code.includes(\"@import 'tailwindcss'\")\n ) {\n debugTailwindV('skip (already has @reference or is root)', {\n filename,\n });\n return code;\n }\n\n const needsReference = prefixes\n ? prefixes.some((prefix) => code.includes(prefix))\n : code.includes('@apply');\n\n if (!needsReference) {\n debugTailwindV('skip (no Tailwind usage detected)', { filename });\n return code;\n }\n\n debugTailwind('injected @reference via preprocessor', { filename });\n\n // Absolute path — required for virtual modules (see JSDoc above).\n return `@reference \"${rootStylesheet}\";\\n${code}`;\n };\n }\n\n // Chain: tailwind preprocessor first, then user preprocessor\n if (tailwindPreprocessor && userPreprocessor) {\n debugTailwind('chained with user stylePreprocessor');\n return (code: string, filename: string) => {\n const intermediate = tailwindPreprocessor!(code, filename);\n return userPreprocessor(intermediate, filename);\n };\n }\n\n return tailwindPreprocessor ?? userPreprocessor;\n}\n\nexport function angular(options?: PluginOptions): Plugin[] {\n applyDebugOption(options?.debug, options?.workspaceRoot);\n\n /**\n * Normalize plugin options so defaults\n * are used for values not provided.\n */\n const pluginOptions = {\n tsconfigGetter: createTsConfigGetter(options?.tsconfig),\n workspaceRoot: options?.workspaceRoot ?? process.cwd(),\n inlineStylesExtension: options?.inlineStylesExtension ?? 'css',\n advanced: {\n tsTransformers: {\n before: options?.advanced?.tsTransformers?.before ?? [],\n after: options?.advanced?.tsTransformers?.after ?? [],\n afterDeclarations:\n options?.advanced?.tsTransformers?.afterDeclarations ?? [],\n },\n },\n supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],\n jit: options?.jit,\n include: options?.include ?? [],\n additionalContentDirs: options?.additionalContentDirs ?? [],\n hmr: options?.hmr ?? options?.liveReload ?? true,\n disableTypeChecking: options?.disableTypeChecking ?? true,\n fileReplacements: options?.fileReplacements ?? [],\n useAngularCompilationAPI:\n options?.experimental?.useAngularCompilationAPI ?? false,\n hasTailwindCss: !!options?.tailwindCss,\n tailwindCss: options?.tailwindCss,\n stylePreprocessor: buildStylePreprocessor(options),\n };\n\n let resolvedConfig: ResolvedConfig;\n // Store config context needed for getTsConfigPath resolution\n let tsConfigResolutionContext: {\n root: string;\n isProd: boolean;\n isLib: boolean;\n } | null = null;\n\n const ts = require('typescript');\n let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n let nextProgram: NgtscProgram | undefined;\n // Caches (always rebuild Angular program per user request)\n const tsconfigOptionsCache = new Map<\n string,\n { options: ts.CompilerOptions; rootNames: string[] }\n >();\n let cachedHost: ts.CompilerHost | undefined;\n let cachedHostKey: string | undefined;\n let includeCache: string[] = [];\n function invalidateFsCaches() {\n includeCache = [];\n }\n function invalidateTsconfigCaches() {\n // `readConfiguration` caches the root file list, so hot-added pages can be\n // missing from Angular's compilation program until we clear this state.\n tsconfigOptionsCache.clear();\n cachedHost = undefined;\n cachedHostKey = undefined;\n }\n let watchMode = false;\n let testWatchMode = isTestWatchMode();\n // Dev-time component identity index for the currently active Vite graph.\n // We intentionally populate this during the pre-transform pass instead of a\n // workspace-wide scan so diagnostics stay tied to the app the developer is\n // actually serving, and so they track hot-updated files incrementally.\n const activeGraphComponentMetadata = new Map<\n string,\n ActiveGraphComponentRecord[]\n >();\n const selectorOwners = new Map<string, Set<string>>();\n const classNameOwners = new Map<string, Set<string>>();\n const transformedStyleOwnerMetadata = new Map<string, StyleOwnerRecord[]>();\n const styleSourceOwners = new Map<string, Set<string>>();\n\n function shouldEnableHmr(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n return !!(effectiveWatchMode && pluginOptions.hmr);\n }\n\n /**\n * Determines whether Angular should externalize component styles.\n *\n * When true, Angular emits style references (hash-based IDs) instead of\n * inlining CSS strings. Vite's resolveId → load → transform pipeline\n * then serves these virtual modules, allowing @tailwindcss/vite to\n * process @reference directives.\n *\n * Required for TWO independent use-cases:\n * 1. HMR — Vite needs external modules for hot replacement\n * 2. Tailwind CSS (hasTailwindCss) — styles must pass through Vite's\n * CSS pipeline so @tailwindcss/vite can resolve @apply directives\n *\n * In production builds (!watchMode), styles are NOT externalized — they\n * are inlined after preprocessCSS runs eagerly in transformStylesheet.\n */\n function shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n if (!effectiveWatchMode) return false;\n return !!(shouldEnableHmr() || pluginOptions.hasTailwindCss);\n }\n\n /**\n * Validates the Tailwind CSS integration configuration and emits actionable\n * warnings for common misconfigurations that cause silent failures.\n *\n * Called once during `configResolved` when `tailwindCss` is configured.\n */\n function validateTailwindConfig(\n config: ResolvedConfig,\n isWatchMode: boolean,\n ): void {\n const PREFIX = '[@analogjs/vite-plugin-angular]';\n const tw = pluginOptions.tailwindCss;\n\n if (!tw) return;\n\n // rootStylesheet must be absolute — relative paths break when Angular\n // externalizes styles as hash-based virtual modules.\n if (!isAbsolute(tw.rootStylesheet)) {\n console.warn(\n `${PREFIX} tailwindCss.rootStylesheet must be an absolute path. ` +\n `Got: \"${tw.rootStylesheet}\". Use path.resolve(__dirname, '...') ` +\n `in your vite.config to convert it.`,\n );\n }\n\n // Dev: @tailwindcss/vite must be registered, otherwise component CSS\n // with @apply/@reference silently fails.\n const resolvedPlugins = config.plugins;\n const hasTailwindPlugin = resolvedPlugins.some(\n (p) =>\n p.name.startsWith('@tailwindcss/vite') ||\n p.name.startsWith('tailwindcss'),\n );\n\n if (isWatchMode && !hasTailwindPlugin) {\n throw new Error(\n `${PREFIX} tailwindCss is configured but no @tailwindcss/vite ` +\n `plugin was found. Component CSS with @apply directives will ` +\n `not be processed.\\n\\n` +\n ` Fix: npm install @tailwindcss/vite --save-dev\\n` +\n ` Then add tailwindcss() to your vite.config plugins array.\\n`,\n );\n }\n\n // Monorepo: rootStylesheet outside project root needs server.fs.allow\n if (isWatchMode && tw.rootStylesheet) {\n const projectRoot = config.root;\n if (!tw.rootStylesheet.startsWith(projectRoot)) {\n const fsAllow = config.server?.fs?.allow ?? [];\n const isAllowed = fsAllow.some((allowed) =>\n tw.rootStylesheet.startsWith(allowed),\n );\n if (!isAllowed) {\n console.warn(\n `${PREFIX} tailwindCss.rootStylesheet is outside the Vite ` +\n `project root. The dev server may reject it with 403.\\n\\n` +\n ` Root: ${projectRoot}\\n` +\n ` Stylesheet: ${tw.rootStylesheet}\\n\\n` +\n ` Fix: server.fs.allow: ['${dirname(tw.rootStylesheet)}']\\n`,\n );\n }\n }\n }\n\n // Empty prefixes array means no component stylesheets get @reference\n if (tw.prefixes !== undefined && tw.prefixes.length === 0) {\n console.warn(\n `${PREFIX} tailwindCss.prefixes is an empty array. No component ` +\n `stylesheets will receive @reference injection. Either remove ` +\n `the prefixes option (to use @apply detection) or specify your ` +\n `prefixes: ['tw:']\\n`,\n );\n }\n\n // Duplicate analog() registrations cause orphaned style maps\n const analogInstances = resolvedPlugins.filter(\n (p) => p.name === '@analogjs/vite-plugin-angular',\n );\n if (analogInstances.length > 1) {\n throw new Error(\n `${PREFIX} analog() is registered ${analogInstances.length} times. ` +\n `Each instance creates separate style maps, causing component ` +\n `styles to be lost. Remove duplicate registrations.`,\n );\n }\n\n // rootStylesheet content must contain @import \"tailwindcss\"\n if (existsSync(tw.rootStylesheet)) {\n try {\n const rootContent = readFileSync(tw.rootStylesheet, 'utf-8');\n if (\n !rootContent.includes('@import \"tailwindcss\"') &&\n !rootContent.includes(\"@import 'tailwindcss'\")\n ) {\n console.warn(\n `${PREFIX} tailwindCss.rootStylesheet does not contain ` +\n `@import \"tailwindcss\". The @reference directive will ` +\n `point to a file without Tailwind configuration.\\n\\n` +\n ` File: ${tw.rootStylesheet}\\n`,\n );\n }\n } catch {\n // Silently skip — existence check already warned in buildStylePreprocessor.\n }\n }\n }\n\n function isLikelyPageOnlyComponent(id: string): boolean {\n return (\n id.includes('/pages/') ||\n /\\.page\\.[cm]?[jt]sx?$/i.test(id) ||\n /\\([^/]+\\)\\.page\\.[cm]?[jt]sx?$/i.test(id)\n );\n }\n\n function removeActiveGraphMetadata(file: string) {\n const previous = activeGraphComponentMetadata.get(file);\n if (!previous) {\n return;\n }\n\n for (const record of previous) {\n const location = `${record.file}#${record.className}`;\n if (record.selector) {\n const selectorSet = selectorOwners.get(record.selector);\n selectorSet?.delete(location);\n if (selectorSet?.size === 0) {\n selectorOwners.delete(record.selector);\n }\n }\n\n const classNameSet = classNameOwners.get(record.className);\n classNameSet?.delete(location);\n if (classNameSet?.size === 0) {\n classNameOwners.delete(record.className);\n }\n }\n\n activeGraphComponentMetadata.delete(file);\n }\n\n function registerActiveGraphMetadata(\n file: string,\n records: ActiveGraphComponentRecord[],\n ) {\n removeActiveGraphMetadata(file);\n\n if (records.length === 0) {\n return;\n }\n\n activeGraphComponentMetadata.set(file, records);\n\n for (const record of records) {\n const location = `${record.file}#${record.className}`;\n\n if (record.selector) {\n let selectorSet = selectorOwners.get(record.selector);\n if (!selectorSet) {\n selectorSet = new Set<string>();\n selectorOwners.set(record.selector, selectorSet);\n }\n selectorSet.add(location);\n }\n\n let classNameSet = classNameOwners.get(record.className);\n if (!classNameSet) {\n classNameSet = new Set<string>();\n classNameOwners.set(record.className, classNameSet);\n }\n classNameSet.add(location);\n }\n }\n\n function removeStyleOwnerMetadata(file: string) {\n const previous = transformedStyleOwnerMetadata.get(file);\n if (!previous) {\n return;\n }\n\n for (const record of previous) {\n const owners = styleSourceOwners.get(record.sourcePath);\n owners?.delete(record.ownerFile);\n if (owners?.size === 0) {\n styleSourceOwners.delete(record.sourcePath);\n }\n }\n\n transformedStyleOwnerMetadata.delete(file);\n }\n\n function registerStyleOwnerMetadata(file: string, styleUrls: string[]) {\n removeStyleOwnerMetadata(file);\n\n const records = styleUrls\n .map((urlSet) => {\n const [, absoluteFileUrl] = urlSet.split('|');\n return absoluteFileUrl\n ? {\n ownerFile: file,\n sourcePath: normalizePath(absoluteFileUrl),\n }\n : undefined;\n })\n .filter((record): record is StyleOwnerRecord => !!record);\n\n if (records.length === 0) {\n return;\n }\n\n transformedStyleOwnerMetadata.set(file, records);\n\n for (const record of records) {\n let owners = styleSourceOwners.get(record.sourcePath);\n if (!owners) {\n owners = new Set<string>();\n styleSourceOwners.set(record.sourcePath, owners);\n }\n owners.add(record.ownerFile);\n }\n }\n\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';\n\n const jit =\n typeof pluginOptions?.jit !== 'undefined' ? pluginOptions.jit : isTest;\n let viteServer: ViteDevServer | undefined;\n\n const styleUrlsResolver = new StyleUrlsResolver();\n const templateUrlsResolver = new TemplateUrlsResolver();\n let outputFile: ((file: string) => void) | undefined;\n const outputFiles = new Map<string, EmitFileResult>();\n const fileEmitter = (file: string) => {\n outputFile?.(file);\n return outputFiles.get(normalizePath(file));\n };\n let initialCompilation = false;\n const declarationFiles: DeclarationFile[] = [];\n const fileTransformMap = new Map<string, string>();\n let styleTransform: (\n code: string,\n filename: string,\n ) => Promise<vite.PreprocessCSSResult>;\n let pendingCompilation: Promise<void> | null;\n let compilationLock = Promise.resolve();\n // Persistent Angular Compilation API instance. Kept alive across rebuilds so\n // Angular can diff previous state and emit `templateUpdates` for HMR.\n // Previously the compilation was recreated on every pass, which meant Angular\n // never had prior state and could never produce HMR payloads.\n let angularCompilation:\n | Awaited<ReturnType<typeof createAngularCompilationType>>\n | undefined;\n\n function angularPlugin(): Plugin {\n let isProd = false;\n\n if (angularFullVersion < 190000 && pluginOptions.hmr) {\n // Angular < 19 does not support externalRuntimeStyles or _enableHmr.\n debugHmr('hmr disabled: Angular version does not support HMR APIs', {\n angularVersion: angularFullVersion,\n isTest,\n });\n console.warn(\n '[@analogjs/vite-plugin-angular]: HMR was disabled because Angular v19+ is required for externalRuntimeStyles/_enableHmr support. Detected Angular version: %s.',\n angularFullVersion,\n );\n pluginOptions.hmr = false;\n }\n\n if (isTest) {\n // Test mode: disable HMR because\n // Vitest's runner doesn't support Vite's WebSocket-based HMR.\n // This does NOT block style externalization — shouldExternalizeStyles()\n // independently checks hasTailwindCss, so Tailwind utilities in\n // component styles still work in unit tests.\n pluginOptions.hmr = false;\n debugHmr('hmr disabled', {\n angularVersion: angularFullVersion,\n isTest,\n });\n }\n\n // HMR and fileReplacements guards were previously here and forced\n // both options off when useAngularCompilationAPI was enabled. Those guards\n // have been removed because:\n // - HMR: the persistent compilation instance (above) now gives\n // Angular the prior state it needs to emit `templateUpdates` for HMR\n // - fileReplacements: Angular's AngularHostOptions already accepts a\n // `fileReplacements` record — we now convert and pass it through in\n // `performAngularCompilation` via `toAngularCompilationFileReplacements`\n if (pluginOptions.useAngularCompilationAPI) {\n if (angularFullVersion < 200100) {\n pluginOptions.useAngularCompilationAPI = false;\n debugCompilationApi(\n 'disabled: Angular version %s < 20.1',\n angularFullVersion,\n );\n console.warn(\n '[@analogjs/vite-plugin-angular]: The Angular Compilation API is only available with Angular v20.1 and later',\n );\n } else {\n debugCompilationApi('enabled (Angular %s)', angularFullVersion);\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular',\n async config(config, { command }) {\n activateDeferredDebug(command);\n watchMode = command === 'serve';\n isProd =\n config.mode === 'production' ||\n process.env['NODE_ENV'] === 'production';\n\n // Store the config context for later resolution in configResolved\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n // Do a preliminary resolution for esbuild plugin (before configResolved)\n const preliminaryTsConfigPath = resolveTsConfigPath();\n\n const esbuild = pluginOptions.useAngularCompilationAPI\n ? undefined\n : (config.esbuild ?? false);\n const oxc = pluginOptions.useAngularCompilationAPI\n ? undefined\n : (config.oxc ?? false);\n if (pluginOptions.useAngularCompilationAPI) {\n debugCompilationApi(\n 'esbuild/oxc disabled, Angular handles transforms',\n );\n }\n\n const defineOptions = {\n ngJitMode: 'false',\n ngI18nClosureMode: 'false',\n ...(watchMode ? {} : { ngDevMode: 'false' }),\n };\n const useRolldown = isRolldown();\n const jsTransformConfigKey = getJsTransformConfigKey();\n const jsTransformConfigValue =\n jsTransformConfigKey === 'oxc' ? oxc : esbuild;\n\n const rolldownOptions: vite.DepOptimizationOptions['rolldownOptions'] =\n {\n plugins: [\n createRolldownCompilerPlugin(\n {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit,\n incremental: watchMode,\n },\n // Astro manages the transformer lifecycle externally.\n !isAstroIntegration,\n ),\n ],\n };\n\n const esbuildOptions: vite.DepOptimizationOptions['esbuildOptions'] = {\n plugins: [\n createCompilerPlugin(\n {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit,\n incremental: watchMode,\n },\n isTest,\n !isAstroIntegration,\n ),\n ],\n define: defineOptions,\n };\n\n return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown ? { rolldownOptions } : { esbuildOptions }),\n },\n resolve: {\n conditions: [\n 'style',\n ...(config.resolve?.conditions || defaultClientConditions),\n ],\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n\n if (pluginOptions.hasTailwindCss) {\n validateTailwindConfig(config, watchMode);\n }\n\n if (pluginOptions.useAngularCompilationAPI) {\n stylesheetRegistry = new AnalogStylesheetRegistry();\n debugStyles(\n 'stylesheet registry initialized (Angular Compilation API)',\n );\n }\n\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\n\n if (isTest) {\n // set test watch mode\n // - vite override from vitest-angular\n // - @nx/vite executor set server.watch explicitly to undefined (watch)/null (watch=false)\n // - vite config for test.watch variable\n // - vitest watch mode detected from the command line\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 // Add/unlink changes the TypeScript program shape, not just file\n // contents, so we need to invalidate both include discovery and the\n // cached tsconfig root names before recompiling.\n const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(\n invalidateFsCaches,\n invalidateTsconfigCaches,\n () => performCompilation(resolvedConfig),\n );\n server.watcher.on('add', invalidateCompilationOnFsChange);\n server.watcher.on('unlink', (file) => {\n evictDeletedFileMetadata(file, {\n removeActiveGraphMetadata,\n removeStyleOwnerMetadata,\n classNamesMap: classNames as Map<string, string>,\n fileTransformMap,\n });\n return invalidateCompilationOnFsChange();\n });\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n // Defer the first compilation in test mode\n if (!isVitestVscode) {\n await performCompilation(resolvedConfig);\n pendingCompilation = null;\n\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 pendingCompilation = performCompilation(resolvedConfig, [fileId]);\n\n let result;\n\n if (shouldEnableHmr()) {\n await pendingCompilation;\n pendingCompilation = null;\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n });\n debugHmrV('ts hmr evaluation', {\n file: ctx.file,\n fileId,\n hasResult: !!result,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n className: classNames.get(fileId),\n updateCode: result?.hmrUpdateCode\n ? describeStylesheetContent(result.hmrUpdateCode)\n : undefined,\n errors: result?.errors?.length ?? 0,\n warnings: result?.warnings?.length ?? 0,\n hint: result?.hmrEligible\n ? 'A TS-side component change, including inline template edits, produced an Angular HMR payload.'\n : 'No Angular HMR payload was emitted for this TS change; the change may not affect component template state.',\n });\n }\n\n if (\n shouldEnableHmr() &&\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 debugHmrV('ts hmr component update payload', {\n file: ctx.file,\n fileId,\n relativeFileId,\n className: classNames.get(fileId),\n });\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n\n return ctx.modules.map((mod) => {\n if (mod.id === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {\n debugHmr('resource file changed', { file: ctx.file });\n fileTransformMap.delete(ctx.file.split('?')[0]);\n if (/\\.(css|less|sass|scss)$/.test(ctx.file)) {\n refreshStylesheetRegistryForFile(\n ctx.file,\n stylesheetRegistry,\n pluginOptions.stylePreprocessor,\n );\n }\n if (\n /\\.(css|less|sass|scss)$/.test(ctx.file) &&\n existsSync(ctx.file)\n ) {\n try {\n const rawResource = readFileSync(ctx.file, 'utf-8');\n debugHmrV('resource source snapshot', {\n file: ctx.file,\n mtimeMs: safeStatMtimeMs(ctx.file),\n ...describeStylesheetContent(rawResource),\n });\n } catch (error) {\n debugHmrV('resource source snapshot failed', {\n file: ctx.file,\n error: String(error),\n });\n }\n }\n // Angular component resources frequently enter HMR with incomplete\n // watcher context. In practice `ctx.modules` may only contain the\n // source file, only the `?direct` module, or nothing at all after a\n // TS-driven component refresh. Resolve the full live module set from\n // Vite's module graph and our stylesheet registry before deciding how\n // to hot update the resource.\n const fileModules = await getModulesForChangedFile(\n ctx.server,\n ctx.file,\n ctx.modules,\n stylesheetRegistry,\n );\n debugHmrV('resource modules resolved', {\n file: ctx.file,\n eventModuleCount: ctx.modules.length,\n fileModuleCount: fileModules.length,\n modules: fileModules.map((mod) => ({\n id: mod.id,\n file: mod.file,\n type: mod.type,\n url: mod.url,\n })),\n });\n /**\n * Check to see if this was a direct request\n * for an external resource (styles, html).\n */\n const isDirect = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?direct') &&\n isModuleForChangedResource(mod, ctx.file, stylesheetRegistry),\n );\n const isInline = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?inline') &&\n isModuleForChangedResource(mod, ctx.file, stylesheetRegistry),\n );\n debugHmrV('resource direct/inline detection', {\n file: ctx.file,\n hasDirect: !!isDirect,\n directId: isDirect?.id,\n hasInline: !!isInline,\n inlineId: isInline?.id,\n });\n\n if (isDirect || isInline) {\n if (shouldExternalizeStyles() && isDirect?.id && isDirect.file) {\n const isComponentStyle =\n isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);\n debugHmrV('resource direct branch', {\n file: ctx.file,\n directId: isDirect.id,\n directType: isDirect.type,\n shouldExternalize: shouldExternalizeStyles(),\n isComponentStyle,\n });\n if (isComponentStyle) {\n const { encapsulation } = getComponentStyleSheetMeta(\n isDirect.id,\n );\n // Angular component styles are served through two live module\n // shapes:\n // 1. a `?direct&ngcomp=...` CSS module that Vite can patch with\n // a normal `css-update`\n // 2. a `?ngcomp=...` JS wrapper module that embeds `__vite__css`\n // for Angular's runtime consumption\n //\n // If we only patch the direct CSS module, the browser can keep\n // running a stale wrapper whose embedded CSS no longer matches\n // the source file. We therefore invalidate any wrapper modules\n // that map back to the same source stylesheet before sending\n // the CSS update.\n const wrapperModules =\n await findComponentStylesheetWrapperModules(\n ctx.server,\n ctx.file,\n isDirect,\n fileModules,\n stylesheetRegistry,\n );\n const stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(\n ctx.file,\n isDirect,\n stylesheetRegistry,\n wrapperModules,\n pluginOptions.stylePreprocessor,\n );\n debugStylesV('HMR: component stylesheet changed', {\n file: isDirect.file,\n encapsulation,\n });\n debugHmrV('component stylesheet wrapper modules', {\n file: ctx.file,\n wrapperCount: wrapperModules.length,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n availableModuleIds: fileModules.map((mod) => mod.id),\n });\n debugHmrV(\n 'component stylesheet pipeline diagnosis',\n stylesheetDiagnosis,\n );\n\n // The stylesheet registry may already hold the fresh served CSS\n // while Vite still has a stale transform result cached for the\n // direct `?direct&ngcomp=...` module id. Invalidate the direct\n // module up front so subsequent wrapper generation and explicit\n // fetches cannot keep serving the pre-edit CSS payload.\n ctx.server.moduleGraph.invalidateModule(isDirect);\n debugHmrV('component stylesheet direct module invalidated', {\n file: ctx.file,\n directModuleId: isDirect.id,\n directModuleUrl: isDirect.url,\n reason:\n 'Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues.',\n });\n\n // Track if the component uses ShadowDOM encapsulation\n // Shadow DOM components currently require a full reload.\n // Vite's CSS hot replacement does not support shadow root searching.\n const trackedWrapperRequestIds =\n stylesheetDiagnosis.trackedRequestIds.filter((id) =>\n id.includes('?ngcomp='),\n );\n const canUseCssUpdate =\n encapsulation !== 'shadow' &&\n (wrapperModules.length > 0 ||\n trackedWrapperRequestIds.length > 0);\n\n if (canUseCssUpdate) {\n wrapperModules.forEach((mod) =>\n ctx.server.moduleGraph.invalidateModule(mod),\n );\n // A live wrapper ModuleNode is ideal because we can\n // invalidate it directly, but it is not strictly required.\n // When the browser has already loaded the wrapper URL and the\n // registry knows that wrapper request id, a normal CSS patch\n // against the direct stylesheet is still the most accurate\n // update path available. Falling back to full reload in that\n // state is needlessly pessimistic and causes the exact UX\n // regression we are trying to eliminate.\n debugHmrV('sending css-update for component stylesheet', {\n file: ctx.file,\n path: isDirect.url,\n acceptedPath: isDirect.file,\n wrapperCount: wrapperModules.length,\n trackedWrapperRequestIds,\n hint:\n wrapperModules.length > 0\n ? 'Live wrapper modules were found and invalidated before sending the CSS update.'\n : '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.',\n });\n sendCssUpdate(ctx.server, {\n path: isDirect.url,\n acceptedPath: isDirect.file,\n });\n logComponentStylesheetHmrOutcome({\n file: ctx.file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'css-update',\n directModuleId: isDirect.id,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n });\n\n return union(\n fileModules\n .filter((mod) => {\n // Component stylesheets will have 2 modules (*.component.scss and *.component.scss?direct&ngcomp=xyz&e=x)\n // We remove the module with the query params to prevent vite double logging the stylesheet name \"hmr update *.component.scss, *.component.scss?direct&ngcomp=xyz&e=x\"\n return mod.file !== ctx.file || mod.id !== isDirect.id;\n })\n .map((mod) => {\n if (mod.file === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n }) as ModuleNode[],\n wrapperModules.map((mod) => markModuleSelfAccepting(mod)),\n );\n }\n\n // A direct CSS patch without the browser-visible `?ngcomp=...`\n // wrapper module is not trustworthy. Angular consumes the\n // wrapper JS module, which embeds `__vite__css` for runtime\n // style application. When that wrapper is missing from the live\n // module graph, prefer correctness over a partial update and\n // force a reload so the component re-evaluates with fresh CSS.\n debugHmrV('component stylesheet hmr fallback: full reload', {\n file: ctx.file,\n encapsulation,\n reason:\n trackedWrapperRequestIds.length === 0\n ? 'missing-wrapper-module'\n : encapsulation === 'shadow'\n ? 'shadow-encapsulation'\n : 'tracked-wrapper-still-not-patchable',\n directId: isDirect.id,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? [],\n });\n const ownerModules = findStyleOwnerModules(\n ctx.server,\n ctx.file,\n styleSourceOwners,\n );\n debugHmrV('component stylesheet owner fallback lookup', {\n file: ctx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n ownerFiles: [\n ...(styleSourceOwners.get(normalizePath(ctx.file)) ?? []),\n ],\n });\n\n if (ownerModules.length > 0) {\n pendingCompilation = performCompilation(resolvedConfig, [\n ...ownerModules.map((mod) => mod.id).filter(Boolean),\n ]);\n await pendingCompilation;\n pendingCompilation = null;\n\n const updates = ownerModules\n .map((mod) => mod.id)\n .filter((id): id is string => !!id && !!classNames.get(id));\n const derivedUpdates = ownerModules\n .map((mod) => mod.id)\n .filter((id): id is string => !!id)\n .flatMap((ownerId) =>\n resolveComponentClassNamesForStyleOwner(\n ownerId,\n ctx.file,\n ).map((className) => ({\n ownerId,\n className,\n via: 'raw-component-metadata' as const,\n })),\n );\n debugHmrV('component stylesheet owner fallback compilation', {\n file: ctx.file,\n ownerIds: ownerModules.map((mod) => mod.id),\n updateIds: updates,\n classNames: updates.map((id) => ({\n id,\n className: classNames.get(id),\n })),\n derivedUpdates,\n });\n // Keep owner recompilation and metadata derivation as\n // diagnostics only. For externalized component styles, a\n // component-update message is not a safe substitute for a\n // missing `?ngcomp=...` wrapper module because Angular can\n // re-render the component without forcing the browser to\n // re-evaluate the live stylesheet wrapper. That exact shape\n // produced false-positive \"successful HMR\" logs while the UI\n // stayed visually stale. If the wrapper is absent, prefer a\n // hard reload after gathering the owner evidence needed to\n // explain why the fallback was necessary.\n if (derivedUpdates.length > 0) {\n debugHmrV(\n 'component stylesheet owner fallback derived updates',\n {\n file: ctx.file,\n updates: derivedUpdates,\n hint: 'Angular did not repopulate classNames during CSS-only owner recompilation, so Analog derived component identities from raw component metadata.',\n },\n );\n }\n }\n\n logComponentStylesheetHmrOutcome({\n file: ctx.file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'full-reload',\n directModuleId: isDirect.id,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n ownerIds: ownerModules.map((mod) => mod.id),\n });\n sendFullReload(ctx.server, {\n file: ctx.file,\n encapsulation,\n reason:\n wrapperModules.length === 0\n ? 'missing-wrapper-module-and-no-owner-updates'\n : 'shadow-encapsulation',\n directId: isDirect.id,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? [],\n });\n return [];\n }\n }\n return fileModules;\n }\n\n if (\n shouldEnableHmr() &&\n /\\.(html|htm)$/.test(ctx.file) &&\n fileModules.length === 0\n ) {\n const ownerModules = findTemplateOwnerModules(ctx.server, ctx.file);\n debugHmrV('template owner lookup', {\n file: ctx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n hint:\n ownerModules.length > 0\n ? 'The external template has candidate TS owner modules that can be recompiled for HMR.'\n : 'No TS owner modules were visible for this external template change; HMR will fall through to the generic importer path.',\n });\n if (ownerModules.length > 0) {\n const ownerIds = ownerModules\n .map((mod) => mod.id)\n .filter(Boolean) as string[];\n\n ownerModules.forEach((mod) =>\n ctx.server.moduleGraph.invalidateModule(mod),\n );\n\n pendingCompilation = performCompilation(resolvedConfig, ownerIds);\n await pendingCompilation;\n pendingCompilation = null;\n\n const updates = ownerIds.filter((id) => classNames.get(id));\n debugHmrV('template owner recompilation result', {\n file: ctx.file,\n ownerIds,\n updates,\n updateClassNames: updates.map((id) => ({\n id,\n className: classNames.get(id),\n })),\n hint:\n updates.length > 0\n ? 'External template recompilation produced Angular component update targets.'\n : 'External template recompilation completed, but no Angular component update targets were surfaced.',\n });\n if (updates.length > 0) {\n debugHmr('template owner module invalidation', {\n file: ctx.file,\n ownerIds,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), updateId),\n )}@${classNames.get(updateId)}`;\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n });\n\n return ownerModules.map((mod) => markModuleSelfAccepting(mod));\n }\n }\n }\n\n const mods: ModuleNode[] = [];\n const updates: string[] = [];\n fileModules.forEach((mod) => {\n mod.importers.forEach((imp) => {\n ctx.server.moduleGraph.invalidateModule(imp);\n\n if (shouldExternalizeStyles() && classNames.get(imp.id)) {\n updates.push(imp.id as string);\n } else {\n mods.push(imp);\n }\n });\n });\n debugHmrV('resource importer analysis', {\n file: ctx.file,\n fileModuleCount: fileModules.length,\n importerCount: fileModules.reduce(\n (count, mod) => count + mod.importers.size,\n 0,\n ),\n updates,\n mods: mods.map((mod) => mod.id),\n });\n\n pendingCompilation = performCompilation(resolvedConfig, [\n ...mods.map((mod) => mod.id).filter(Boolean),\n ...updates,\n ]);\n\n if (updates.length > 0) {\n await pendingCompilation;\n pendingCompilation = null;\n\n debugHmr('resource importer component updates', {\n file: ctx.file,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n const impRelativeFileId = `${normalizePath(\n relative(process.cwd(), updateId),\n )}@${classNames.get(updateId)}`;\n\n sendHMRComponentUpdate(ctx.server, impRelativeFileId);\n });\n\n return fileModules.map((mod) => {\n if (mod.id === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n\n return mods;\n }\n\n // clear HMR updates with a full reload\n debugHmr('full reload — unrecognized file type', { file: ctx.file });\n classNames.clear();\n return ctx.modules;\n },\n resolveId(id, importer) {\n if (jit && id.startsWith('angular:jit:')) {\n const path = id.split(';')[1];\n return `${normalizePath(\n resolve(dirname(importer as string), path),\n )}?${id.includes(':style') ? 'inline' : 'raw'}`;\n }\n\n // Map angular component stylesheets. Prefer registry-served CSS\n // (preprocessed, with @reference) over external raw file mappings\n // file path). Without this priority, Angular may emit a basename ID\n // that resolves to the raw file, bypassing preprocessing.\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n\n if (stylesheetRegistry?.hasServed(filename)) {\n debugStylesV('resolveId: kept preprocessed ID', { filename });\n return id;\n }\n\n const componentStyles =\n stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n debugStylesV('resolveId: mapped external stylesheet', {\n filename,\n resolvedPath: componentStyles,\n });\n return componentStyles + new URL(id, 'http://localhost').search;\n }\n\n debugStyles(\n 'resolveId: component stylesheet NOT FOUND in either map',\n {\n filename,\n inlineMapSize: stylesheetRegistry?.servedCount ?? 0,\n externalMapSize: stylesheetRegistry?.externalCount ?? 0,\n },\n );\n }\n\n return undefined;\n },\n async load(id) {\n // Map angular inline styles to the source text\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const componentStyles =\n stylesheetRegistry?.getServedContent(filename);\n if (componentStyles) {\n stylesheetRegistry?.registerActiveRequest(id);\n // Register the concrete request id that was just served. During HMR\n // the changed file event references the original source stylesheet\n // path, but the live browser module graph references hashed\n // stylesheet request ids such as `/abc123.css?ngcomp=...`. This is\n // the bridge between those two worlds.\n debugHmrV('stylesheet active request registered', {\n requestId: id,\n filename,\n sourcePath:\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\n filename.replace(/^\\//, ''),\n ),\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\n filename.replace(/^\\//, ''),\n ) ??\n '',\n ) ?? [],\n });\n debugStylesV('load: served inline component stylesheet', {\n filename,\n length: componentStyles.length,\n requestId: id,\n ...describeStylesheetContent(componentStyles),\n });\n return componentStyles;\n }\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [/node_modules/, 'type=script', '@ng/component'],\n },\n },\n async handler(code, id) {\n /**\n * Check for options.transformFilter\n */\n if (\n options?.transformFilter &&\n !(options?.transformFilter(code, id) ?? true)\n ) {\n return;\n }\n\n if (pluginOptions.useAngularCompilationAPI) {\n const isAngular =\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n\n if (!isAngular) {\n debugCompilationApi('transform skip (non-Angular file)', { id });\n return;\n }\n }\n\n /**\n * Skip transforming content files\n */\n if (id.includes('?') && id.includes('analog-content-')) {\n return;\n }\n\n /**\n * Encapsulate component stylesheets that use emulated encapsulation.\n * Must run whenever styles are externalized (not just HMR), because\n * Angular's externalRuntimeStyles skips its own encapsulation when\n * styles are external — the build tool is expected to handle it.\n */\n if (shouldExternalizeStyles() && isComponentStyleSheet(id)) {\n const { encapsulation, componentId } =\n getComponentStyleSheetMeta(id);\n if (encapsulation === 'emulated' && componentId) {\n debugStylesV('applying emulated view encapsulation', {\n stylesheet: id.split('?')[0],\n componentId,\n });\n const encapsulated = ngCompiler.encapsulateStyle(\n code,\n componentId,\n );\n return {\n code: encapsulated,\n map: null,\n };\n }\n }\n\n if (id.includes('.ts?')) {\n // Strip the query string off the ID\n // in case of a dynamically loaded file\n id = id.replace(/\\?(.*)/, '');\n }\n\n fileTransformMap.set(id, code);\n\n /**\n * Re-analyze on each transform\n * for test(Vitest)\n */\n if (isTest) {\n if (isVitestVscode && !initialCompilation) {\n // Do full initial compilation\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\n if (testWatchMode && invalidated) {\n pendingCompilation = performCompilation(resolvedConfig, [id]);\n }\n }\n }\n\n // Detect whether the code contains an Angular @Component decorator.\n //\n // IMPORTANT — useAngularCompilationAPI behavior:\n // When `useAngularCompilationAPI: true`, the Angular Compilation API\n // compiles TypeScript BEFORE this Vite transform hook fires. By the\n // time `code` reaches here, @Component decorators have been compiled\n // away into ɵɵdefineComponent() calls, so `hasComponent` is always\n // false for actual component files.\n //\n // This is expected and NOT a bug. The Angular Compilation API handles\n // template and style resolution through its own internal pipeline:\n // - Templates: resolved during compilation, not via templateUrls\n // - Styles: externalized and served via the resolveId/load hooks\n // (confirmed by `analog:angular:styles resolveId: mapped external\n // stylesheet` debug messages)\n //\n // The only consequence of hasComponent=false is that external template\n // and style files are not registered via addWatchFile(), which means\n // HMR for external HTML/CSS edits may trigger a full reload instead of\n // a targeted hot replacement. The Angular Compilation API's own\n // invalidation mechanism handles recompilation regardless.\n //\n // For the legacy (non-API) compilation path, hasComponent works as\n // expected because the transform hook sees raw TypeScript source.\n const hasComponent = code.includes('@Component');\n debugCompilerV('transform', {\n id,\n codeLength: code.length,\n hasComponent,\n });\n const templateUrls = hasComponent\n ? templateUrlsResolver.resolve(code, id)\n : [];\n const styleUrls = hasComponent\n ? styleUrlsResolver.resolve(code, id)\n : [];\n\n if (hasComponent && watchMode) {\n for (const urlSet of [...templateUrls, ...styleUrls]) {\n // `urlSet` is a string where a relative path is joined with an\n // absolute path using the `|` symbol.\n // For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.\n const [, absoluteFileUrl] = urlSet.split('|');\n this.addWatchFile(absoluteFileUrl);\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n\n const typescriptResult = fileEmitter(id);\n\n if (\n typescriptResult?.warnings &&\n typescriptResult?.warnings.length > 0\n ) {\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 // return fileEmitter\n let data = typescriptResult?.content ?? '';\n\n if (jit && data.includes('angular:jit:')) {\n data = data.replace(\n /angular:jit:style:inline;/g,\n 'virtual:angular:jit:style:inline;',\n );\n\n templateUrls.forEach((templateUrlSet) => {\n const [templateFile, resolvedTemplateUrl] =\n templateUrlSet.split('|');\n data = data.replace(\n `angular:jit:template:file;${templateFile}`,\n `${resolvedTemplateUrl}?raw`,\n );\n });\n\n styleUrls.forEach((styleUrlSet) => {\n const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');\n data = data.replace(\n `angular:jit:style:file;${styleFile}`,\n `${resolvedStyleUrl}?inline`,\n );\n });\n }\n\n // Angular's HMR initializer emits dynamic import() calls that Vite's\n // import-analysis plugin cannot statically analyze, producing SSR\n // warnings. The Angular compiler's IR includes a @vite-ignore comment\n // but it can be lost during TypeScript emit. Re-inject it here so the\n // warning is suppressed regardless of the compilation path used.\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n debugHmrV('vite-ignore injection', {\n id,\n dataLength: data.length,\n hasMetaUrl,\n });\n if (hasMetaUrl) {\n const patched = injectViteIgnoreForHmrMetadata(data);\n if (patched !== data && !patched.includes('@vite-ignore')) {\n debugHmrV('vite-ignore regex fallback', { id });\n }\n data = patched;\n }\n }\n\n return {\n code: data,\n map: null,\n };\n },\n },\n closeBundle() {\n declarationFiles.forEach(\n ({ declarationFileDir, declarationPath, data }) => {\n mkdirSync(declarationFileDir, { recursive: true });\n writeFileSync(declarationPath, data, 'utf-8');\n },\n );\n // Tear down the persistent compilation instance at end of build so it\n // does not leak memory across unrelated Vite invocations.\n angularCompilation?.close?.();\n angularCompilation = undefined;\n },\n };\n }\n\n return [\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n {\n name: '@analogjs/vite-plugin-angular:template-class-binding-guard',\n enforce: 'pre',\n transform(code: string, id: string) {\n if (id.includes('node_modules')) {\n return;\n }\n\n const cleanId = id.split('?')[0];\n\n if (/\\.(html|htm)$/i.test(cleanId)) {\n const staticClassIssue =\n findStaticClassAndBoundClassConflicts(code)[0];\n if (staticClassIssue) {\n throwTemplateClassBindingConflict(cleanId, staticClassIssue);\n }\n\n const mixedClassIssue = findBoundClassAndNgClassConflicts(code)[0];\n if (mixedClassIssue) {\n this.warn(\n [\n '[Analog Angular] Conflicting class composition.',\n `File: ${cleanId}:${mixedClassIssue.line}:${mixedClassIssue.column}`,\n 'This element mixes `[class]` and `[ngClass]`.',\n 'Prefer a single class-binding strategy so class merging stays predictable.',\n 'Use one `[ngClass]` expression or explicit `[class.foo]` bindings.',\n `Snippet: ${mixedClassIssue.snippet}`,\n ].join('\\n'),\n );\n }\n return;\n }\n\n if (TS_EXT_REGEX.test(cleanId)) {\n const rawStyleUrls = styleUrlsResolver.resolve(code, cleanId);\n registerStyleOwnerMetadata(cleanId, rawStyleUrls);\n debugHmrV('component stylesheet owner metadata registered', {\n file: cleanId,\n styleUrlCount: rawStyleUrls.length,\n styleUrls: rawStyleUrls,\n ownerSources: [\n ...(transformedStyleOwnerMetadata\n .get(cleanId)\n ?.map((record) => record.sourcePath) ?? []),\n ],\n });\n\n // Parse raw component decorators before Angular compilation strips\n // them. This lets Analog fail fast on template/class-footguns and\n // keep a lightweight active-graph index for duplicate selector/class\n // diagnostics without requiring a full compiler pass first.\n const components = getAngularComponentMetadata(code);\n\n const inlineTemplateIssue = components.flatMap((component) =>\n component.inlineTemplates.flatMap((template) =>\n findStaticClassAndBoundClassConflicts(template),\n ),\n )[0];\n\n if (inlineTemplateIssue) {\n throwTemplateClassBindingConflict(cleanId, inlineTemplateIssue);\n }\n\n const mixedInlineClassIssue = components.flatMap((component) =>\n component.inlineTemplates.flatMap((template) =>\n findBoundClassAndNgClassConflicts(template),\n ),\n )[0];\n\n if (mixedInlineClassIssue) {\n this.warn(\n [\n '[Analog Angular] Conflicting class composition.',\n `File: ${cleanId}:${mixedInlineClassIssue.line}:${mixedInlineClassIssue.column}`,\n 'This element mixes `[class]` and `[ngClass]`.',\n 'Prefer a single class-binding strategy so class merging stays predictable.',\n 'Use one `[ngClass]` expression or explicit `[class.foo]` bindings.',\n `Snippet: ${mixedInlineClassIssue.snippet}`,\n ].join('\\n'),\n );\n }\n\n const activeGraphRecords = components.map((component) => ({\n file: cleanId,\n className: component.className,\n selector: component.selector,\n }));\n\n registerActiveGraphMetadata(cleanId, activeGraphRecords);\n\n for (const component of components) {\n if (!component.selector && !isLikelyPageOnlyComponent(cleanId)) {\n throw new Error(\n [\n '[Analog Angular] Selectorless component detected.',\n `File: ${cleanId}`,\n `Component: ${component.className}`,\n 'This component has no `selector`, so Angular will render it as `ng-component`.',\n 'That increases the chance of component ID collisions and makes diagnostics harder to interpret.',\n 'Add an explicit selector for reusable components.',\n 'Selectorless components are only supported for page and route-only files.',\n ].join('\\n'),\n );\n }\n\n if (component.selector) {\n const selectorEntries = selectorOwners.get(component.selector);\n if (selectorEntries && selectorEntries.size > 1) {\n throw new Error(\n [\n '[Analog Angular] Duplicate component selector detected.',\n `Selector: ${component.selector}`,\n 'Multiple components in the active application graph use the same selector.',\n 'Selectors must be unique within the active graph to avoid ambiguous rendering and confusing diagnostics.',\n `Locations:\\n${formatActiveGraphLocations(selectorEntries)}`,\n ].join('\\n'),\n );\n }\n }\n\n const classNameEntries = classNameOwners.get(component.className);\n if (classNameEntries && classNameEntries.size > 1) {\n this.warn(\n [\n '[Analog Angular] Duplicate component class name detected.',\n `Class name: ${component.className}`,\n 'Two or more Angular components in the active graph share the same exported class name.',\n 'Rename one of them to keep HMR, stack traces, and compiler diagnostics unambiguous.',\n `Locations:\\n${formatActiveGraphLocations(classNameEntries)}`,\n ].join('\\n'),\n );\n }\n }\n }\n },\n } satisfies Plugin,\n // Tailwind CSS v4 @reference injection for direct-file-loaded CSS.\n // Catches CSS files loaded from disk (not virtual modules) that need\n // @reference before @tailwindcss/vite processes them.\n pluginOptions.hasTailwindCss &&\n ({\n name: '@analogjs/vite-plugin-angular:tailwind-reference',\n enforce: 'pre',\n transform(code: string, id: string) {\n const tw = pluginOptions.tailwindCss;\n if (!tw || !id.includes('.css')) return;\n\n const cleanId = id.split('?')[0];\n if (cleanId === tw.rootStylesheet) return;\n\n if (\n code.includes('@reference') ||\n code.includes('@import \"tailwindcss\"') ||\n code.includes(\"@import 'tailwindcss'\")\n ) {\n return;\n }\n\n // Skip entry stylesheets that @import the root config\n const rootBasename = basename(tw.rootStylesheet);\n if (code.includes(rootBasename)) return;\n\n const prefixes = tw.prefixes;\n const needsRef = prefixes\n ? prefixes.some((p) => code.includes(p))\n : code.includes('@apply');\n\n if (needsRef) {\n debugTailwind('injected @reference via pre-transform', {\n id: id.split('/').slice(-2).join('/'),\n });\n return `@reference \"${tw.rootStylesheet}\";\\n${code}`;\n }\n },\n } satisfies Plugin),\n angularPlugin(),\n pluginOptions.hmr && liveReloadPlugin({ classNames, fileEmitter }),\n ...(isTest && !isStackBlitz ? angularVitestPlugins() : []),\n (jit &&\n jitPlugin({\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n })) as Plugin,\n buildOptimizerPlugin({\n supportedBrowsers: pluginOptions.supportedBrowsers,\n jit,\n }),\n routerPlugin(),\n angularFullVersion < 190004 && pendingTasksPlugin(),\n nxFolderPlugin(),\n ].filter(Boolean) as Plugin[];\n\n function findIncludes() {\n // Map include patterns to absolute workspace paths\n const globs = pluginOptions.include.map((glob) =>\n normalizeIncludeGlob(pluginOptions.workspaceRoot, glob),\n );\n\n // Discover TypeScript files using tinyglobby\n return globSync(globs, {\n dot: true,\n absolute: true,\n });\n }\n\n function createTsConfigGetter(tsconfigOrGetter?: string | (() => string)) {\n if (typeof tsconfigOrGetter === 'function') {\n return tsconfigOrGetter;\n }\n\n return () => tsconfigOrGetter || '';\n }\n\n function getTsConfigPath(\n root: string,\n tsconfig: string,\n isProd: boolean,\n isTest: boolean,\n isLib: boolean,\n ) {\n if (tsconfig && isAbsolute(tsconfig)) {\n if (!existsSync(tsconfig)) {\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${tsconfig}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n }\n\n return tsconfig;\n }\n\n let tsconfigFilePath = './tsconfig.app.json';\n\n if (isLib) {\n tsconfigFilePath = isProd\n ? './tsconfig.lib.prod.json'\n : './tsconfig.lib.json';\n }\n\n if (isTest) {\n tsconfigFilePath = './tsconfig.spec.json';\n }\n\n if (tsconfig) {\n tsconfigFilePath = tsconfig;\n }\n\n const resolvedPath = resolve(root, tsconfigFilePath);\n\n if (!existsSync(resolvedPath)) {\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${resolvedPath}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n }\n\n return resolvedPath;\n }\n\n function resolveTsConfigPath() {\n const tsconfigValue = pluginOptions.tsconfigGetter();\n\n return getTsConfigPath(\n tsConfigResolutionContext!.root,\n tsconfigValue,\n tsConfigResolutionContext!.isProd,\n isTest,\n tsConfigResolutionContext!.isLib,\n );\n }\n\n /**\n * Perform compilation using Angular's private Compilation API.\n *\n * Key differences from the standard `performCompilation` path:\n * 1. The compilation instance is reused across rebuilds (nullish-coalescing\n * assignment below) so Angular retains prior state and can diff it to\n * produce `templateUpdates` for HMR.\n * 2. `ids` (modified files) are forwarded to both the source-file cache and\n * `angularCompilation.update()` so that incremental re-analysis is\n * scoped to what actually changed.\n * 3. `fileReplacements` are converted and passed into Angular's host via\n * `toAngularCompilationFileReplacements`.\n * 4. `templateUpdates` from the compilation result are mapped back to\n * file-level HMR metadata (`hmrUpdateCode`, `hmrEligible`, `classNames`).\n */\n async function performAngularCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ) {\n // Reuse the existing instance so Angular can diff against prior state.\n 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 // Notify Angular of modified files before re-initialization so it can\n // scope its incremental analysis.\n if (modifiedFiles?.size && angularCompilation.update) {\n debugCompilationApi('incremental update', {\n files: [...modifiedFiles],\n });\n await angularCompilation.update(modifiedFiles);\n }\n\n const resolvedTsConfigPath = resolveTsConfigPath();\n const compilationResult = await angularCompilation.initialize(\n resolvedTsConfigPath,\n {\n // Convert Analog's browser-style `{ replace, with }` entries into the\n // `Record<string, string>` shape that Angular's AngularHostOptions\n // expects. SSR-only replacements (`{ replace, ssr }`) are intentionally\n // excluded — they stay on the Vite runtime side.\n fileReplacements: toAngularCompilationFileReplacements(\n pluginOptions.fileReplacements,\n pluginOptions.workspaceRoot,\n ),\n modifiedFiles,\n async transformStylesheet(\n data,\n containingFile,\n resourceFile,\n order,\n className,\n ) {\n const filename =\n resourceFile ??\n containingFile.replace(\n '.ts',\n `.${pluginOptions.inlineStylesExtension}`,\n );\n\n const preprocessedData = preprocessStylesheet(\n data,\n filename,\n pluginOptions.stylePreprocessor,\n );\n\n // Populate classNames during initial compilation so HMR for\n // HTML template changes can find the parent TS module.\n if (shouldEnableHmr() && className && containingFile) {\n classNames.set(normalizePath(containingFile), className as string);\n }\n\n if (shouldExternalizeStyles()) {\n // Store preprocessed CSS so Vite's serve-time pipeline handles\n // PostCSS / Tailwind processing when the load hook returns it.\n const stylesheetId = registerStylesheetContent(\n stylesheetRegistry!,\n {\n code: preprocessedData,\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 debugStylesV('stylesheet deferred content snapshot', {\n stylesheetId,\n filename,\n resourceFile: resourceFile ?? '(inline)',\n ...describeStylesheetContent(preprocessedData),\n });\n\n return stylesheetId;\n }\n\n // Non-externalized: CSS is returned directly to the Angular compiler\n // and never re-enters Vite's pipeline, so run preprocessCSS() eagerly.\n debugStyles('stylesheet processed inline via preprocessCSS', {\n filename,\n resourceFile: resourceFile ?? '(inline)',\n dataLength: preprocessedData.length,\n });\n let stylesheetResult;\n\n try {\n stylesheetResult = await preprocessCSS(\n preprocessedData,\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 }\n\n return stylesheetResult?.code || '';\n },\n processWebWorker(workerFile, containingFile) {\n return '';\n },\n },\n (tsCompilerOptions) => {\n if (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (shouldEnableHmr()) {\n tsCompilerOptions['_enableHmr'] = true;\n // Workaround for https://github.com/angular/angular/issues/59310\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (compilation API)', {\n hmr: pluginOptions.hmr,\n hasTailwindCss: pluginOptions.hasTailwindCss,\n watchMode,\n shouldExternalize: shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions.compilationMode === 'partial') {\n // These options can't be false in partial mode\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (angularFullVersion >= 200000) {\n tsCompilerOptions['_enableSelectorless'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n return tsCompilerOptions;\n },\n );\n\n // -------------------------------------------------------------------\n // Preprocess external stylesheets for Tailwind CSS @reference\n //\n // Angular's Compilation API with externalRuntimeStyles does NOT call\n // transformStylesheet for external styleUrls (files referenced via\n // `styleUrls: ['./foo.component.css']`). Angular's angular-host.js\n // asserts this explicitly:\n //\n // assert(!resourceFile || !hostOptions.externalStylesheets?.has(resourceFile),\n // 'External runtime stylesheets should not be transformed')\n //\n // Only inline styles (`styles: [...]`) go through transformStylesheet,\n // which is where buildStylePreprocessor injects `@reference` for\n // Tailwind CSS. External component CSS files are instead reported in\n // compilationResult.externalStylesheets as Map<absolutePath, sha256Hash>.\n //\n // Without intervention, the resolveId hook maps Angular's hash to the\n // raw file path, the load hook reads the raw file from disk, and\n // @tailwindcss/vite processes CSS without @reference — causing:\n //\n // \"Cannot apply utility class 'sa:grid' because the 'sa'\n // variant does not exist\"\n //\n // Fix: for each external stylesheet, read the file from disk, run the\n // style preprocessor (which injects @reference), and store the result\n // in the stylesheet registry under Angular's hash. The resolveId hook\n // then finds it on the first lookup, the load hook serves the\n // @reference-injected version, and @tailwindcss/vite compiles correctly.\n // -------------------------------------------------------------------\n debugStyles('external stylesheets from compilation API', {\n count: compilationResult.externalStylesheets?.size ?? 0,\n hasPreprocessor: !!pluginOptions.stylePreprocessor,\n hasInlineMap: !!stylesheetRegistry,\n });\n const preprocessStats = { total: 0, injected: 0, skipped: 0, errors: 0 };\n compilationResult.externalStylesheets?.forEach((value, key) => {\n preprocessStats.total++;\n const angularHash = `${value}.css`;\n stylesheetRegistry?.registerExternalRequest(angularHash, key);\n\n // Read the raw CSS file from disk, run the style preprocessor\n // (which injects @reference for Tailwind), and store the result\n // in the stylesheet registry under Angular's hash. This way\n // resolveId finds the preprocessed version on the first lookup\n // and the load hook serves CSS that @tailwindcss/vite can compile.\n //\n // After preprocessing, resolve relative @import paths to absolute\n // paths. When @tailwindcss/vite processes the CSS, the virtual\n // hash-based module ID has no meaningful directory, so relative\n // imports like `@import './submenu/submenu.component.css'` would\n // fail to resolve from `/`. Converting to absolute paths ensures\n // Tailwind's enhanced-resolve can find the imported files.\n if (\n stylesheetRegistry &&\n pluginOptions.stylePreprocessor &&\n existsSync(key)\n ) {\n try {\n const rawCss = readFileSync(key, 'utf-8');\n let preprocessed = preprocessStylesheet(\n rawCss,\n key,\n pluginOptions.stylePreprocessor,\n );\n debugStylesV('external stylesheet raw snapshot', {\n angularHash,\n resolvedPath: key,\n mtimeMs: safeStatMtimeMs(key),\n ...describeStylesheetContent(rawCss),\n });\n preprocessed = rewriteRelativeCssImports(preprocessed, key);\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId: angularHash,\n sourcePath: key,\n originalCode: rawCss,\n normalizedCode: preprocessed,\n },\n [key, normalizePath(key), basename(key), key.replace(/^\\//, '')],\n );\n\n if (preprocessed && preprocessed !== rawCss) {\n preprocessStats.injected++;\n debugStylesV(\n 'preprocessed external stylesheet for Tailwind @reference',\n {\n angularHash,\n resolvedPath: key,\n mtimeMs: safeStatMtimeMs(key),\n raw: describeStylesheetContent(rawCss),\n served: describeStylesheetContent(preprocessed),\n },\n );\n } else {\n preprocessStats.skipped++;\n debugStylesV('external stylesheet unchanged after preprocessing', {\n angularHash,\n resolvedPath: key,\n mtimeMs: safeStatMtimeMs(key),\n raw: describeStylesheetContent(rawCss),\n served: describeStylesheetContent(preprocessed),\n hint: 'Registry mapping is still registered so Angular component stylesheet HMR can track and refresh this file even when preprocessing makes no textual changes.',\n });\n }\n } catch (e) {\n preprocessStats.errors++;\n console.warn(\n `[@analogjs/vite-plugin-angular] failed to preprocess external stylesheet: ${key}: ${e}`,\n );\n // Non-fatal: fall through to the external source mapping which\n // serves the raw file. @tailwindcss/vite will still process\n // it but without @reference (Tailwind prefix utilities won't\n // resolve).\n }\n } else {\n preprocessStats.skipped++;\n debugStylesV('external stylesheet preprocessing skipped', {\n filename: angularHash,\n resolvedPath: key,\n reason: !stylesheetRegistry\n ? 'no stylesheetRegistry'\n : !pluginOptions.stylePreprocessor\n ? 'no stylePreprocessor'\n : 'file not found on disk',\n });\n }\n\n debugStylesV('external stylesheet registered for resolveId mapping', {\n filename: angularHash,\n resolvedPath: key,\n });\n });\n debugStyles('external stylesheet preprocessing complete', preprocessStats);\n\n const diagnostics = await angularCompilation.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 // Angular encodes template updates as `encodedFilePath@ClassName` keys.\n // `mapTemplateUpdatesToFiles` decodes them back to absolute file paths so\n // we can attach HMR metadata to the correct `EmitFileResult` below.\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 for (const file of await angularCompilation.emitAffectedFiles()) {\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 // Surface Angular's HMR payloads into Analog's existing live-reload\n // flow via the `hmrUpdateCode` / `hmrEligible` fields.\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\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 await _doPerformCompilation(config, ids);\n } finally {\n resolve!();\n }\n }\n\n /**\n * This method share mutable state and performs the actual compilation work.\n * It should not be called concurrently. Use `performCompilation` which wraps this method in a lock to ensure only one compilation runs at a time.\n */\n async function _doPerformCompilation(config: ResolvedConfig, ids?: string[]) {\n // Forward `ids` (modified files) so the Compilation API path can do\n // incremental re-analysis instead of a full recompile on every change.\n if (pluginOptions.useAngularCompilationAPI) {\n debugCompilationApi('using compilation API path', {\n modifiedFiles: ids?.length ?? 0,\n });\n await performAngularCompilation(config, ids);\n return;\n }\n\n const isProd = config.mode === 'production';\n const modifiedFiles = new Set<string>(ids ?? []);\n sourceFileCache.invalidate(modifiedFiles);\n\n if (ids?.length) {\n for (const id of ids || []) {\n fileTransformMap.delete(id);\n }\n }\n\n // Cached include discovery (invalidated only on FS events)\n if (pluginOptions.include.length > 0 && includeCache.length === 0) {\n includeCache = findIncludes();\n }\n\n const resolvedTsConfigPath = resolveTsConfigPath();\n const tsconfigKey = [\n resolvedTsConfigPath,\n isProd ? 'prod' : 'dev',\n isTest ? 'test' : 'app',\n config.build?.lib ? 'lib' : 'nolib',\n pluginOptions.hmr ? 'hmr' : 'nohmr',\n pluginOptions.hasTailwindCss ? 'tw' : 'notw',\n ].join('|');\n let cached = tsconfigOptionsCache.get(tsconfigKey);\n\n if (!cached) {\n const read = compilerCli.readConfiguration(resolvedTsConfigPath, {\n suppressOutputPathCheck: true,\n outDir: undefined,\n sourceMap: false,\n inlineSourceMap: !isProd,\n inlineSources: !isProd,\n declaration: false,\n declarationMap: false,\n allowEmptyCodegenFiles: false,\n annotationsAs: 'decorators',\n enableResourceInlining: false,\n noEmitOnError: false,\n mapRoot: undefined,\n sourceRoot: undefined,\n supportTestBed: false,\n supportJitMode: false,\n });\n cached = { options: read.options, rootNames: read.rootNames };\n tsconfigOptionsCache.set(tsconfigKey, cached);\n }\n\n // Clone options before mutation (preserve cache purity)\n const tsCompilerOptions = { ...cached.options };\n let rootNames = [...cached.rootNames];\n\n if (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (shouldEnableHmr()) {\n tsCompilerOptions['_enableHmr'] = true;\n // Workaround for https://github.com/angular/angular/issues/59310\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (NgtscProgram path)', {\n hmr: pluginOptions.hmr,\n shouldExternalize: shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n // These options can't be false in partial mode\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (angularFullVersion >= 200000) {\n tsCompilerOptions['_enableSelectorless'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n const replacements = pluginOptions.fileReplacements.map((rp) =>\n join(\n pluginOptions.workspaceRoot,\n (rp as FileReplacementSSR).ssr || (rp as FileReplacementWith).with,\n ),\n );\n // Merge + dedupe root names\n rootNames = union(rootNames, includeCache, replacements);\n const hostKey = JSON.stringify(tsCompilerOptions);\n let host: ts.CompilerHost;\n\n if (cachedHost && cachedHostKey === hostKey) {\n host = cachedHost;\n } else {\n host = ts.createIncrementalCompilerHost(tsCompilerOptions, {\n ...ts.sys,\n readFile(path: string, encoding: string) {\n if (fileTransformMap.has(path)) {\n return fileTransformMap.get(path);\n }\n\n const file = ts.sys.readFile.call(null, path, encoding);\n\n if (file) {\n fileTransformMap.set(path, file);\n }\n\n return file;\n },\n });\n cachedHost = host;\n cachedHostKey = hostKey;\n\n // Only store cache if in watch mode\n if (watchMode) {\n augmentHostWithCaching(host, sourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n stylesheetRegistry = externalizeStyles\n ? new AnalogStylesheetRegistry()\n : undefined;\n debugStyles('stylesheet registry initialized (NgtscProgram path)', {\n externalizeStyles,\n });\n augmentHostWithResources(host, styleTransform, {\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n isProd,\n stylesheetRegistry,\n sourceFileCache,\n stylePreprocessor: pluginOptions.stylePreprocessor,\n });\n }\n\n /**\n * Creates a new NgtscProgram to analyze/re-analyze\n * the source files and create a file emitter.\n * This is shared between an initial build and a hot update.\n */\n let typeScriptProgram: ts.Program;\n let angularCompiler: NgtscProgram['compiler'];\n const oldBuilder =\n builder ?? ts.readBuilderProgram(tsCompilerOptions, host);\n\n if (!jit) {\n // Create the Angular specific program that contains the Angular compiler\n const angularProgram: NgtscProgram = new compilerCli.NgtscProgram(\n rootNames,\n tsCompilerOptions,\n host,\n nextProgram,\n );\n angularCompiler = angularProgram.compiler;\n typeScriptProgram = angularProgram.compiler.getCurrentProgram();\n augmentProgramWithVersioning(typeScriptProgram);\n\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n typeScriptProgram,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n nextProgram = angularProgram;\n } else {\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n rootNames,\n tsCompilerOptions,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n typeScriptProgram = builder.getProgram();\n }\n\n if (!watchMode) {\n // When not in watch mode, the startup cost of the incremental analysis can be avoided by\n // using an abstract builder that only wraps a TypeScript program.\n builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);\n }\n\n if (angularCompiler!) {\n await angularCompiler.analyzeAsync();\n }\n\n const beforeTransformers = jit\n ? [\n compilerCli.constructorParametersDownlevelTransform(\n builder.getProgram(),\n ),\n createJitResourceTransformer(() =>\n builder.getProgram().getTypeChecker(),\n ),\n ]\n : [];\n\n const transformers = mergeTransformers(\n { before: beforeTransformers },\n jit ? {} : angularCompiler!.prepareEmit().transformers,\n );\n\n const fileMetadata = getFileMetadata(\n builder,\n angularCompiler!,\n pluginOptions.hmr,\n pluginOptions.disableTypeChecking,\n );\n\n const writeFileCallback: ts.WriteFileCallback = (\n _filename,\n content,\n _a,\n _b,\n sourceFiles,\n ) => {\n if (!sourceFiles?.length) {\n return;\n }\n\n const filename = normalizePath(sourceFiles[0].fileName);\n\n if (filename.includes('ngtypecheck.ts') || filename.includes('.d.')) {\n return;\n }\n\n const metadata = watchMode ? fileMetadata(filename) : {};\n\n outputFiles.set(filename, {\n content,\n dependencies: [],\n errors: metadata.errors,\n warnings: metadata.warnings,\n hmrUpdateCode: metadata.hmrUpdateCode,\n hmrEligible: metadata.hmrEligible,\n });\n };\n\n const writeOutputFile = (id: string) => {\n const sourceFile = builder.getSourceFile(id);\n if (!sourceFile) {\n return;\n }\n\n let content = '';\n builder.emit(\n sourceFile,\n (filename, data) => {\n if (/\\.[cm]?js$/.test(filename)) {\n content = data;\n }\n\n if (\n !watchMode &&\n !isTest &&\n /\\.d\\.ts/.test(filename) &&\n !filename.includes('.ngtypecheck.')\n ) {\n // output to library root instead /src\n const declarationPath = resolve(\n config.root,\n config.build.outDir,\n relative(config.root, filename),\n ).replace('/src/', '/');\n\n const declarationFileDir = declarationPath\n .replace(basename(filename), '')\n .replace('/src/', '/');\n\n declarationFiles.push({\n declarationFileDir,\n declarationPath,\n data,\n });\n }\n },\n undefined /* cancellationToken */,\n undefined /* emitOnlyDtsFiles */,\n transformers,\n );\n\n writeFileCallback(id, content, false, undefined, [sourceFile]);\n\n if (angularCompiler) {\n angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);\n }\n };\n\n if (watchMode) {\n if (ids && ids.length > 0) {\n ids.forEach((id) => writeOutputFile(id));\n } else {\n /**\n * Only block the server from starting up\n * during testing.\n */\n if (isTest) {\n // TypeScript will loop until there are no more affected files in the program\n while (\n (\n builder as ts.EmitAndSemanticDiagnosticsBuilderProgram\n ).emitNextAffectedFile(\n writeFileCallback,\n undefined,\n undefined,\n transformers,\n )\n ) {\n /* empty */\n }\n }\n }\n }\n\n if (!isTest) {\n /**\n * Perf: Output files on demand so the dev server\n * isn't blocked when emitting files.\n */\n outputFile = writeOutputFile;\n }\n }\n}\n\nexport function createFsWatcherCacheInvalidator(\n invalidateFsCaches: () => void,\n invalidateTsconfigCaches: () => void,\n performCompilation: () => Promise<void>,\n): () => Promise<void> {\n return async (): Promise<void> => {\n invalidateFsCaches();\n invalidateTsconfigCaches();\n await performCompilation();\n };\n}\n\n/**\n * Convert Analog/Angular CLI-style file replacements into the flat record\n * expected by `AngularHostOptions.fileReplacements`.\n *\n * Only browser replacements (`{ replace, with }`) are converted. SSR-only\n * replacements (`{ replace, ssr }`) are left for the Vite runtime plugin to\n * handle — they should not be baked into the Angular compilation host because\n * that would apply them to both browser and server builds.\n *\n * Relative paths are resolved against `workspaceRoot` so that the host\n * receives the same absolute paths it would get from the Angular CLI.\n */\nexport function toAngularCompilationFileReplacements(\n replacements: FileReplacement[],\n workspaceRoot: string,\n): Record<string, string> | undefined {\n const mappedReplacements = replacements.flatMap((replacement) => {\n // Skip SSR-only entries — they use `ssr` instead of `with`.\n if (!('with' in replacement)) {\n return [];\n }\n\n return [\n [\n isAbsolute(replacement.replace)\n ? replacement.replace\n : resolve(workspaceRoot, replacement.replace),\n isAbsolute(replacement.with)\n ? replacement.with\n : resolve(workspaceRoot, replacement.with),\n ] as const,\n ];\n });\n\n return mappedReplacements.length\n ? Object.fromEntries(mappedReplacements)\n : undefined;\n}\n\n/**\n * Map Angular's `templateUpdates` (keyed by `encodedFilePath@ClassName`)\n * back to absolute file paths with their associated HMR code and component\n * class name.\n *\n * Angular's private Compilation API emits template update keys in the form\n * `encodeURIComponent(relativePath + '@' + className)`. We decode and resolve\n * them so the caller can look up updates by the same normalized absolute path\n * used elsewhere in the plugin (`outputFiles`, `classNames`, etc.).\n */\nexport function mapTemplateUpdatesToFiles(\n templateUpdates: ReadonlyMap<string, string> | undefined,\n): Map<\n string,\n {\n className: string;\n code: string;\n }\n> {\n const updatesByFile = new Map<string, { className: string; code: string }>();\n\n templateUpdates?.forEach((code, encodedUpdateId) => {\n const [file, className = ''] =\n decodeURIComponent(encodedUpdateId).split('@');\n const resolvedFile = normalizePath(resolve(process.cwd(), file));\n\n updatesByFile.set(resolvedFile, {\n className,\n code,\n });\n });\n\n return updatesByFile;\n}\n\n/**\n * Returns every live Vite module that can legitimately represent a changed\n * Angular resource file.\n *\n * For normal files, `getModulesByFile()` is enough. For Angular component\n * stylesheets, it is not: the browser often holds virtual hashed requests\n * (`/abc123.css?direct&ngcomp=...` and `/abc123.css?ngcomp=...`) that are no\n * longer discoverable from the original source path alone. We therefore merge:\n * - watcher event modules\n * - module-graph modules by source file\n * - registry-tracked live request ids resolved back through the module graph\n */\nexport async function getModulesForChangedFile(\n server: ViteDevServer,\n file: string,\n eventModules: readonly ModuleNode[] = [],\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): Promise<ModuleNode[]> {\n const normalizedFile = normalizePath(file.split('?')[0]);\n const modules = new Map<string, ModuleNode>();\n\n for (const mod of eventModules) {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n }\n\n server.moduleGraph.getModulesByFile(normalizedFile)?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n\n const stylesheetRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(normalizedFile) ?? [];\n const requestIdHits: Array<{\n requestId: string;\n candidate: string;\n via: 'url' | 'id';\n moduleId?: string;\n }> = [];\n for (const requestId of stylesheetRequestIds) {\n const candidates = [\n requestId,\n requestId.startsWith('/') ? requestId : `/${requestId}`,\n ];\n\n for (const candidate of candidates) {\n // `getModuleByUrl()` is the important lookup here. Angular's wrapper\n // module is served by URL and can be absent from a straight `getModuleById`\n // lookup during CSS HMR, even though it is the browser-visible module\n // that must be refreshed. We keep `getModuleById()` as a compatibility\n // fallback for the simpler direct CSS case.\n const mod =\n (await server.moduleGraph.getModuleByUrl(candidate)) ??\n server.moduleGraph.getModuleById(candidate);\n requestIdHits.push({\n requestId,\n candidate,\n via: mod?.url === candidate ? 'url' : 'id',\n moduleId: mod?.id,\n });\n if (mod?.id) {\n modules.set(mod.id, mod);\n }\n }\n }\n\n debugHmrV('getModulesForChangedFile registry lookup', {\n file: normalizedFile,\n stylesheetRequestIds,\n requestIdHits,\n resolvedModuleIds: [...modules.keys()],\n });\n\n return [...modules.values()];\n}\n\nexport function isModuleForChangedResource(\n mod: ModuleNode,\n changedFile: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): boolean {\n const normalizedChangedFile = normalizePath(changedFile.split('?')[0]);\n\n if (normalizePath((mod.file ?? '').split('?')[0]) === normalizedChangedFile) {\n return true;\n }\n\n if (!mod.id) {\n return false;\n }\n\n // Virtual Angular stylesheet modules do not report the original source file\n // as `mod.file`; they point at the served hashed stylesheet asset instead.\n // Recover the source file through the stylesheet registry so HMR can still\n // answer \"does this live module belong to the resource that just changed?\"\n const requestPath = getFilenameFromPath(mod.id);\n const sourcePath =\n stylesheetRegistry?.resolveExternalSource(requestPath) ??\n stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\\//, ''));\n\n return (\n normalizePath((sourcePath ?? '').split('?')[0]) === normalizedChangedFile\n );\n}\n\nfunction describeStylesheetContent(code: string): {\n length: number;\n digest: string;\n preview: string;\n} {\n return {\n length: code.length,\n digest: createHash('sha256').update(code).digest('hex').slice(0, 12),\n preview: code.replace(/\\s+/g, ' ').trim().slice(0, 160),\n };\n}\n\nfunction safeStatMtimeMs(file: string): number | undefined {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Refreshes any already-served stylesheet records that map back to a changed\n * source file.\n *\n * This is the critical bridge for externalized Angular component styles during\n * HMR. Angular's resource watcher can notice that `/src/...component.css`\n * changed before Angular recompilation has had a chance to repopulate the\n * stylesheet registry. If we emit a CSS update against the existing virtual\n * stylesheet id without first refreshing the registry content, the browser gets\n * a hot update containing stale CSS. By rewriting the existing served records\n * from disk up front, HMR always pushes the latest source content.\n */\nexport function refreshStylesheetRegistryForFile(\n file: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n stylePreprocessor?: StylePreprocessor,\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n if (!stylesheetRegistry || !existsSync(normalizedFile)) {\n return;\n }\n\n const publicIds = stylesheetRegistry.getPublicIdsForSource(normalizedFile);\n if (publicIds.length === 0) {\n return;\n }\n\n const rawCss = readFileSync(normalizedFile, 'utf-8');\n let servedCss = preprocessStylesheet(\n rawCss,\n normalizedFile,\n stylePreprocessor,\n );\n servedCss = rewriteRelativeCssImports(servedCss, normalizedFile);\n\n for (const publicId of publicIds) {\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId,\n sourcePath: normalizedFile,\n originalCode: rawCss,\n normalizedCode: servedCss,\n },\n [\n normalizedFile,\n normalizePath(normalizedFile),\n basename(normalizedFile),\n normalizedFile.replace(/^\\//, ''),\n ],\n );\n }\n\n debugStylesV('stylesheet registry refreshed from source file', {\n file: normalizedFile,\n publicIds,\n source: describeStylesheetContent(rawCss),\n served: describeStylesheetContent(servedCss),\n });\n}\n\nfunction diagnoseComponentStylesheetPipeline(\n changedFile: string,\n directModule: ModuleNode,\n stylesheetRegistry: AnalogStylesheetRegistry | undefined,\n wrapperModules: ModuleNode[],\n stylePreprocessor?: StylePreprocessor,\n): {\n file: string;\n sourcePath?: string;\n source?: ReturnType<typeof describeStylesheetContent>;\n registry?: ReturnType<typeof describeStylesheetContent>;\n directModuleId?: string;\n directModuleUrl?: string;\n trackedRequestIds: string[];\n wrapperCount: number;\n anomalies: string[];\n hints: string[];\n} {\n const normalizedFile = normalizePath(changedFile.split('?')[0]);\n const sourceExists = existsSync(normalizedFile);\n const sourceCode = sourceExists\n ? readFileSync(normalizedFile, 'utf-8')\n : undefined;\n\n const directRequestPath = directModule.id\n ? getFilenameFromPath(directModule.id)\n : undefined;\n const sourcePath = directRequestPath\n ? (stylesheetRegistry?.resolveExternalSource(directRequestPath) ??\n stylesheetRegistry?.resolveExternalSource(\n directRequestPath.replace(/^\\//, ''),\n ))\n : normalizedFile;\n const registryCode = directRequestPath\n ? stylesheetRegistry?.getServedContent(directRequestPath)\n : undefined;\n const trackedRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? '') ?? [];\n\n const anomalies: string[] = [];\n const hints: string[] = [];\n\n if (!sourceExists) {\n anomalies.push('source_file_missing');\n hints.push(\n 'The stylesheet watcher fired for a file that no longer exists on disk.',\n );\n }\n\n if (!registryCode) {\n anomalies.push('registry_content_missing');\n hints.push(\n 'The stylesheet registry has no served content for the direct module request path.',\n );\n }\n\n if (sourceCode && registryCode) {\n // Compare against the same served representation that the registry stores,\n // not the raw file on disk. Analog intentionally prepends `@reference`\n // and rewrites relative imports before the stylesheet reaches Vite, so a\n // raw-source hash comparison would flag a false positive on every healthy\n // update.\n let expectedRegistryCode = preprocessStylesheet(\n sourceCode,\n normalizedFile,\n stylePreprocessor,\n );\n expectedRegistryCode = rewriteRelativeCssImports(\n expectedRegistryCode,\n normalizedFile,\n );\n const sourceDigest = describeStylesheetContent(expectedRegistryCode).digest;\n const registryDigest = describeStylesheetContent(registryCode).digest;\n if (sourceDigest !== registryDigest) {\n anomalies.push('source_registry_mismatch');\n hints.push(\n 'The source file changed, but the served stylesheet content in the registry is still stale.',\n );\n }\n }\n\n if (trackedRequestIds.length === 0) {\n anomalies.push('no_tracked_requests');\n hints.push(\n 'No live stylesheet requests are tracked for this source file, so HMR has no browser-facing target.',\n );\n }\n\n if (\n trackedRequestIds.some((id) => id.includes('?ngcomp=')) &&\n wrapperModules.length === 0\n ) {\n anomalies.push('tracked_wrapper_missing_from_module_graph');\n hints.push(\n 'A wrapper request id is known, but Vite did not expose a live wrapper module during this HMR pass.',\n );\n }\n\n if (\n trackedRequestIds.every((id) => !id.includes('?ngcomp=')) &&\n wrapperModules.length === 0\n ) {\n anomalies.push('wrapper_not_yet_tracked');\n hints.push(\n 'Only direct stylesheet requests were tracked during this HMR pass; the wrapper request may be appearing too late.',\n );\n }\n\n return {\n file: changedFile,\n sourcePath,\n source: sourceCode\n ? describeStylesheetContent(\n rewriteRelativeCssImports(\n preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor),\n normalizedFile,\n ),\n )\n : undefined,\n registry: registryCode\n ? describeStylesheetContent(registryCode)\n : undefined,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n trackedRequestIds,\n wrapperCount: wrapperModules.length,\n anomalies,\n hints,\n };\n}\n\nexport async function findComponentStylesheetWrapperModules(\n server: ViteDevServer,\n changedFile: string,\n directModule: ModuleNode,\n fileModules: ModuleNode[],\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): Promise<ModuleNode[]> {\n const wrapperModules = new Map<string, ModuleNode>();\n\n // Fast path: if the wrapper JS module is already present in the resolved\n // fileModules set for this HMR cycle, use it directly.\n for (const mod of fileModules) {\n if (\n mod.id &&\n mod.type === 'js' &&\n isComponentStyleSheet(mod.id) &&\n isModuleForChangedResource(mod, changedFile, stylesheetRegistry)\n ) {\n wrapperModules.set(mod.id, mod);\n }\n }\n\n const directRequestIds = new Set<string>();\n if (directModule.id) {\n directRequestIds.add(directModule.id);\n }\n if (directModule.url) {\n directRequestIds.add(directModule.url);\n }\n\n const requestPath = directModule.id\n ? getFilenameFromPath(directModule.id)\n : undefined;\n const sourcePath = requestPath\n ? (stylesheetRegistry?.resolveExternalSource(requestPath) ??\n stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\\//, '')))\n : undefined;\n\n // HMR timing matters here. On a pure CSS edit, the browser often already has\n // the `?ngcomp=...` wrapper module loaded, but the registry may only know\n // about the `?direct&ngcomp=...` request at the moment the file watcher\n // fires. Pull in any already-tracked wrapper ids for the same source file,\n // then derive wrapper candidates from the known direct request ids.\n for (const requestId of stylesheetRegistry?.getRequestIdsForSource(\n sourcePath ?? '',\n ) ?? []) {\n if (requestId.includes('?ngcomp=')) {\n directRequestIds.add(requestId);\n }\n }\n\n const candidateWrapperIds = [...directRequestIds]\n .filter((id) => id.includes('?direct&ngcomp='))\n .map((id) => id.replace('?direct&ngcomp=', '?ngcomp='));\n\n const lookupHits: Array<{\n candidate: string;\n via?: 'url' | 'id';\n moduleId?: string;\n moduleType?: string;\n }> = [];\n\n for (const candidate of candidateWrapperIds) {\n // Wrapper modules are served by URL and can be absent from a straight\n // module-id lookup during HMR. Prefer URL resolution first, then fall back\n // to id lookup for compatibility with simpler module graph states.\n const mod =\n (await server.moduleGraph.getModuleByUrl(candidate)) ??\n server.moduleGraph.getModuleById(candidate);\n lookupHits.push({\n candidate,\n via: mod?.url === candidate ? 'url' : mod ? 'id' : undefined,\n moduleId: mod?.id,\n moduleType: mod?.type,\n });\n if (\n mod?.id &&\n mod.type === 'js' &&\n isComponentStyleSheet(mod.id) &&\n isModuleForChangedResource(mod, changedFile, stylesheetRegistry)\n ) {\n wrapperModules.set(mod.id, mod);\n }\n }\n\n debugHmrV('component stylesheet wrapper lookup', {\n file: changedFile,\n sourcePath,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n candidateWrapperIds,\n lookupHits,\n });\n\n if (wrapperModules.size === 0) {\n debugHmrV('component stylesheet wrapper lookup empty', {\n file: changedFile,\n sourcePath,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n candidateWrapperIds,\n });\n }\n\n return [...wrapperModules.values()];\n}\n\nfunction 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\n classNames.delete(id);\n}\n\nfunction sendCssUpdate(\n server: ViteDevServer,\n update: {\n path: string;\n acceptedPath: string;\n },\n) {\n const timestamp = Date.now();\n debugHmrV('ws send: css-update', {\n ...update,\n timestamp,\n });\n server.ws.send({\n type: 'update',\n updates: [\n {\n type: 'css-update',\n timestamp,\n path: update.path,\n acceptedPath: update.acceptedPath,\n },\n ],\n });\n}\n\nfunction sendFullReload(\n server: ViteDevServer,\n details: Record<string, unknown>,\n) {\n debugHmrV('ws send: full-reload', details);\n server.ws.send('analog:debug-full-reload', details);\n server.ws.send({ type: 'full-reload' });\n}\n\nfunction resolveComponentClassNamesForStyleOwner(\n ownerFile: string,\n sourcePath: string,\n): string[] {\n if (!existsSync(ownerFile)) {\n return [];\n }\n\n const ownerCode = readFileSync(ownerFile, 'utf-8');\n const components = getAngularComponentMetadata(ownerCode);\n const normalizedSourcePath = normalizePath(sourcePath);\n\n return components\n .filter((component) =>\n component.styleUrls.some(\n (styleUrl) =>\n normalizePath(resolve(dirname(ownerFile), styleUrl)) ===\n normalizedSourcePath,\n ),\n )\n .map((component) => component.className);\n}\n\ninterface TemplateClassBindingIssue {\n line: number;\n column: number;\n snippet: string;\n}\n\ninterface ActiveGraphComponentRecord {\n file: string;\n className: string;\n selector?: string;\n}\n\ninterface StyleOwnerRecord {\n sourcePath: string;\n ownerFile: string;\n}\n\ntype ComponentStylesheetHmrOutcome =\n | 'css-update'\n | 'owner-component-update'\n | 'full-reload';\n\nexport function findStaticClassAndBoundClassConflicts(\n template: string,\n): TemplateClassBindingIssue[] {\n const issues: TemplateClassBindingIssue[] = [];\n\n for (const { index, snippet } of findOpeningTagSnippets(template)) {\n if (!snippet.includes('[class]')) {\n continue;\n }\n\n const hasStaticClass = /\\sclass\\s*=\\s*(['\"])(?:(?!\\1)[\\s\\S])*\\1/.test(\n snippet,\n );\n const hasBoundClass = /\\s\\[class\\]\\s*=\\s*(['\"])(?:(?!\\1)[\\s\\S])*\\1/.test(\n snippet,\n );\n\n if (hasStaticClass && hasBoundClass) {\n const prefix = template.slice(0, index);\n const line = prefix.split('\\n').length;\n const lastNewline = prefix.lastIndexOf('\\n');\n const column = index - lastNewline;\n issues.push({\n line,\n column,\n snippet: snippet.replace(/\\s+/g, ' ').trim(),\n });\n }\n }\n\n return issues;\n}\n\nfunction throwTemplateClassBindingConflict(\n id: string,\n issue: TemplateClassBindingIssue,\n): never {\n throw new Error(\n [\n '[Analog Angular] Invalid template class binding.',\n `File: ${id}:${issue.line}:${issue.column}`,\n 'The same element uses both a static `class=\"...\"` attribute and a whole-element `[class]=\"...\"` binding.',\n 'That pattern can replace or conflict with static Tailwind classes, which makes styles appear to stop applying.',\n 'Use `[ngClass]` or explicit `[class.foo]` bindings instead of `[class]` when the element also has static classes.',\n `Snippet: ${issue.snippet}`,\n ].join('\\n'),\n );\n}\n\nexport function findBoundClassAndNgClassConflicts(\n template: string,\n): TemplateClassBindingIssue[] {\n const issues: TemplateClassBindingIssue[] = [];\n const hasWholeElementClassBinding = /\\[class\\]\\s*=/.test(template);\n\n if (!hasWholeElementClassBinding || !template.includes('[ngClass]')) {\n return issues;\n }\n\n for (const { index, snippet } of findOpeningTagSnippets(template)) {\n if (!/\\[class\\]\\s*=/.test(snippet) || !snippet.includes('[ngClass]')) {\n continue;\n }\n\n const prefix = template.slice(0, index);\n const line = prefix.split('\\n').length;\n const lastNewline = prefix.lastIndexOf('\\n');\n const column = index - lastNewline;\n issues.push({\n line,\n column,\n snippet: snippet.replace(/\\s+/g, ' ').trim(),\n });\n }\n\n return issues;\n}\n\nfunction findOpeningTagSnippets(\n template: string,\n): Array<{ index: number; snippet: string }> {\n const matches: Array<{ index: number; snippet: string }> = [];\n\n for (let index = 0; index < template.length; index++) {\n if (template[index] !== '<') {\n continue;\n }\n\n const tagStart = template[index + 1];\n if (!tagStart || !/[a-zA-Z]/.test(tagStart)) {\n continue;\n }\n\n let quote: '\"' | \"'\" | null = null;\n\n for (let end = index + 1; end < template.length; end++) {\n const char = template[end];\n\n if (quote) {\n if (char === quote) {\n quote = null;\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n\n if (char === '>') {\n matches.push({\n index,\n snippet: template.slice(index, end + 1),\n });\n index = end;\n break;\n }\n }\n }\n\n return matches;\n}\n\nfunction formatActiveGraphLocations(entries: Iterable<string>): string {\n return [...entries]\n .sort()\n .map((entry) => `- ${entry}`)\n .join('\\n');\n}\n\nfunction logComponentStylesheetHmrOutcome(details: {\n file: string;\n encapsulation: string;\n diagnosis: ReturnType<typeof diagnoseComponentStylesheetPipeline>;\n outcome: ComponentStylesheetHmrOutcome;\n directModuleId?: string;\n wrapperIds?: string[];\n ownerIds?: Array<string | undefined>;\n updateIds?: string[];\n}) {\n const pitfalls: string[] = [];\n const rejectedPreferredPaths: string[] = [];\n const hints: string[] = [];\n\n if (details.encapsulation === 'shadow') {\n pitfalls.push('shadow-encapsulation');\n rejectedPreferredPaths.push('css-update');\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'Shadow DOM styles cannot rely on Vite CSS patching because Angular applies them inside a shadow root.',\n );\n }\n\n if (details.diagnosis.anomalies.includes('wrapper_not_yet_tracked')) {\n pitfalls.push('wrapper-not-yet-tracked');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'The direct stylesheet module exists, but the browser-visible Angular wrapper module was not available in the live graph during this HMR pass.',\n );\n }\n\n if (\n details.diagnosis.anomalies.includes(\n 'tracked_wrapper_missing_from_module_graph',\n )\n ) {\n pitfalls.push('tracked-wrapper-missing-from-module-graph');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'A wrapper request id is known, but Vite could not resolve a live wrapper module for targeted CSS HMR.',\n );\n }\n\n if ((details.ownerIds?.filter(Boolean).length ?? 0) === 0) {\n pitfalls.push('no-owner-modules');\n if (details.outcome === 'full-reload') {\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'No owning TS component modules were available in the module graph for owner-based fallback.',\n );\n }\n } else if ((details.updateIds?.length ?? 0) === 0) {\n pitfalls.push('owner-modules-without-class-identities');\n if (details.outcome === 'full-reload') {\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'Owner modules were found, but Angular did not expose component class identities after recompilation, so no targeted component update could be sent.',\n );\n }\n }\n\n debugHmrV('component stylesheet hmr outcome', {\n file: details.file,\n outcome: details.outcome,\n encapsulation: details.encapsulation,\n directModuleId: details.directModuleId,\n wrapperIds: details.wrapperIds ?? [],\n ownerIds: details.ownerIds ?? [],\n updateIds: details.updateIds ?? [],\n preferredPath:\n details.encapsulation === 'shadow' ? 'full-reload' : 'css-update',\n rejectedPreferredPaths: [...new Set(rejectedPreferredPaths)],\n pitfalls: [...new Set(pitfalls)],\n anomalies: details.diagnosis.anomalies,\n hints: [...new Set([...details.diagnosis.hints, ...hints])],\n });\n}\n\nexport function findTemplateOwnerModules(\n server: ViteDevServer,\n resourceFile: string,\n): ModuleNode[] {\n const normalizedResourceFile = normalizePath(resourceFile.split('?')[0]);\n const candidateTsFiles = [\n normalizedResourceFile.replace(/\\.(html|htm)$/i, '.ts'),\n ];\n\n const modules = new Map<string, ModuleNode>();\n for (const candidate of candidateTsFiles) {\n const owners = server.moduleGraph.getModulesByFile(candidate);\n owners?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n }\n\n return [...modules.values()];\n}\n\nfunction findStyleOwnerModules(\n server: ViteDevServer,\n resourceFile: string,\n styleSourceOwners: Map<string, Set<string>>,\n): ModuleNode[] {\n const normalizedResourceFile = normalizePath(resourceFile.split('?')[0]);\n const candidateOwnerFiles = [\n ...(styleSourceOwners.get(normalizedResourceFile) ?? []),\n ];\n const modules = new Map<string, ModuleNode>();\n\n for (const ownerFile of candidateOwnerFiles) {\n const owners = server.moduleGraph.getModulesByFile(ownerFile);\n owners?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n }\n\n return [...modules.values()];\n}\n\nexport function getFileMetadata(\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n hmrEnabled?: boolean,\n disableTypeChecking?: boolean,\n) {\n const ts = require('typescript');\n return (\n file: string,\n ): {\n errors?: string[];\n warnings?: (string | ts.DiagnosticMessageChain)[];\n hmrUpdateCode?: string | null;\n hmrEligible?: boolean;\n } => {\n const sourceFile = program.getSourceFile(file);\n if (!sourceFile) {\n return {};\n }\n\n const diagnostics = getDiagnosticsForSourceFile(\n sourceFile,\n !!disableTypeChecking,\n program,\n angularCompiler,\n );\n\n const errors = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Error)\n .map((d) =>\n typeof d.messageText === 'object'\n ? d.messageText.messageText\n : d.messageText,\n );\n\n const warnings = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Warning)\n .map((d) => d.messageText);\n\n let hmrUpdateCode: string | null | undefined = undefined;\n\n let hmrEligible = false;\n if (hmrEnabled) {\n for (const node of sourceFile.statements) {\n if (ts.isClassDeclaration(node) && (node as any).name != null) {\n hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node as any);\n if (hmrUpdateCode) {\n const className = (node as any).name.getText();\n classNames.set(file, className);\n hmrEligible = true;\n debugHmr('NgtscProgram emitHmrUpdateModule', { file, className });\n }\n }\n }\n }\n\n return { errors, warnings, hmrUpdateCode, hmrEligible };\n };\n}\n\nfunction getDiagnosticsForSourceFile(\n sourceFile: ts.SourceFile,\n disableTypeChecking: boolean,\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n) {\n const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);\n\n if (disableTypeChecking) {\n // Syntax errors are cheap to compute and the app will not run if there are any\n // So always show these types of errors regardless if type checking is disabled\n return syntacticDiagnostics;\n }\n\n const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);\n const angularDiagnostics = angularCompiler\n ? angularCompiler.getDiagnosticsForFile(sourceFile, 1)\n : [];\n return [\n ...syntacticDiagnostics,\n ...semanticDiagnostics,\n ...angularDiagnostics,\n ];\n}\n\nfunction markModuleSelfAccepting(mod: ModuleNode): ModuleNode {\n // support Vite 6\n if ('_clientModule' in mod) {\n (mod as any)['_clientModule'].isSelfAccepting = true;\n }\n\n return {\n ...mod,\n isSelfAccepting: true,\n } as ModuleNode;\n}\n\nfunction isComponentStyleSheet(id: string): boolean {\n return id.includes('ngcomp=');\n}\n\nfunction getComponentStyleSheetMeta(id: string): {\n componentId: string;\n encapsulation: 'emulated' | 'shadow' | 'none';\n} {\n const params = new URL(id, 'http://localhost').searchParams;\n const encapsulationMapping = {\n '0': 'emulated',\n '2': 'none',\n '3': 'shadow',\n };\n return {\n componentId: params.get('ngcomp')!,\n encapsulation: encapsulationMapping[\n params.get('e') as keyof typeof encapsulationMapping\n ] as 'emulated' | 'shadow' | 'none',\n };\n}\n\n/**\n * Removes leading / and query string from a url path\n * e.g. /foo.scss?direct&ngcomp=ng-c3153525609&e=0 returns foo.scss\n * @param id\n */\nfunction getFilenameFromPath(id: string): string {\n try {\n return new URL(id, 'http://localhost').pathname.replace(/^\\//, '');\n } catch {\n // Defensive fallback: if the ID cannot be parsed as a URL (e.g., it\n // contains characters that are invalid in URLs but valid in file paths\n // on some platforms), strip the query string manually.\n const queryIndex = id.indexOf('?');\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id;\n return pathname.replace(/^\\//, '');\n }\n}\n\n/**\n * Checks for vitest run from the command line\n * @returns boolean\n */\nexport function isTestWatchMode(args: string[] = process.argv): boolean {\n // vitest --run\n const hasRun = args.find((arg) => arg.includes('--run'));\n if (hasRun) {\n return false;\n }\n\n // vitest --no-run\n const hasNoRun = args.find((arg) => arg.includes('--no-run'));\n if (hasNoRun) {\n return true;\n }\n\n // check for --watch=false or --no-watch\n const hasWatch = args.find((arg) => arg.includes('watch'));\n if (hasWatch && ['false', 'no'].some((neg) => hasWatch.includes(neg))) {\n return false;\n }\n\n // check for --watch false\n const watchIndex = args.findIndex((arg) => arg.includes('watch'));\n const watchArg = args[watchIndex + 1];\n if (watchArg && watchArg === 'false') {\n return false;\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+EA,IAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAoB9C,IAAY,kBAAL,yBAAA,iBA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B,CAAC;AAM/C,QAAO;EACL,aAAa,OAAO,IAAI,SAAS;EACjC,eAP2B;GAC3B,KAAK;GACL,KAAK;GACL,KAAK;GACN,CAIG,OAAO,IAAI,IAAI;EAElB;;;;;;;AAQH,SAAS,oBAAoB,IAAoB;AAC/C,KAAI;AACF,SAAO,IAAI,IAAI,IAAI,mBAAmB,CAAC,SAAS,QAAQ,OAAO,GAAG;SAC5D;EAIN,MAAM,aAAa,GAAG,QAAQ,IAAI;AAElC,UADiB,cAAc,IAAI,GAAG,MAAM,GAAG,WAAW,GAAG,IAC7C,QAAQ,OAAO,GAAG;;;;;;;AAQtC,SAAgB,gBAAgB,OAAiB,QAAQ,MAAe;AAGtE,KADe,KAAK,MAAM,QAAQ,IAAI,SAAS,QAAQ,CAAC,CAEtD,QAAO;AAKT,KADiB,KAAK,MAAM,QAAQ,IAAI,SAAS,WAAW,CAAC,CAE3D,QAAO;CAIT,MAAM,WAAW,KAAK,MAAM,QAAQ,IAAI,SAAS,QAAQ,CAAC;AAC1D,KAAI,YAAY,CAAC,SAAS,KAAK,CAAC,MAAM,QAAQ,SAAS,SAAS,IAAI,CAAC,CACnE,QAAO;CAKT,MAAM,WAAW,KADE,KAAK,WAAW,QAAQ,IAAI,SAAS,QAAQ,CAAC,GAC9B;AACnC,KAAI,YAAY,aAAa,QAC3B,QAAO;AAGT,QAAO"}
1
+ {"version":3,"file":"angular-vite-plugin.js","names":[],"sources":["../../../src/lib/angular-vite-plugin.ts"],"sourcesContent":["import { NgtscProgram } from '@angular/compiler-cli';\nimport { union } from 'es-toolkit';\nimport { createHash } from 'node:crypto';\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n} from 'node:path';\nimport * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport { createRequire } from 'node:module';\nimport * as ts from 'typescript';\nimport { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';\n\nimport * as ngCompiler from '@angular/compiler';\nimport { globSync } from 'tinyglobby';\nimport {\n defaultClientConditions,\n ModuleNode,\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\nimport { buildOptimizerPlugin } from './angular-build-optimizer-plugin.js';\nimport { jitPlugin } from './angular-jit-plugin.js';\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from './compiler-plugin.js';\nimport {\n getAngularComponentMetadata,\n StyleUrlsResolver,\n TemplateUrlsResolver,\n} from './component-resolvers.js';\nimport {\n augmentHostWithCaching,\n augmentHostWithResources,\n augmentProgramWithVersioning,\n mergeTransformers,\n} from './host.js';\nimport {\n composeStylePreprocessors,\n normalizeStylesheetDependencies,\n} from './style-preprocessor.js';\nimport type {\n StylePreprocessor,\n StylesheetDependency,\n} from './style-preprocessor.js';\n\nimport { angularVitestPlugins } from './angular-vitest-plugin.js';\nimport {\n createAngularCompilation,\n createJitResourceTransformer,\n SourceFileCache,\n angularFullVersion,\n} from './utils/devkit.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugCompilationApi,\n debugCompiler,\n debugCompilerV,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n debugTailwind,\n debugTailwindV,\n type DebugOption,\n} from './utils/debug.js';\nimport { getJsTransformConfigKey, isRolldown } from './utils/rolldown.js';\nimport { type SourceFileCache as SourceFileCacheType } from './utils/source-file-cache.js';\n\nconst require = createRequire(import.meta.url);\n\nimport { pendingTasksPlugin } from './angular-pending-tasks.plugin.js';\nimport { liveReloadPlugin } from './live-reload-plugin.js';\nimport { EmitFileResult } from './models.js';\nimport { nxFolderPlugin } from './nx-folder-plugin.js';\nimport {\n FileReplacement,\n FileReplacementSSR,\n FileReplacementWith,\n replaceFiles,\n} from './plugins/file-replacements.plugin.js';\nimport { routerPlugin } from './router-plugin.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheet,\n preprocessStylesheetResult,\n registerStylesheetContent,\n rewriteRelativeCssImports,\n} from './stylesheet-registry.js';\nimport {\n type AngularStylePipelineOptions,\n configureStylePipelineRegistry,\n stylePipelinePreprocessorFromPlugins,\n} from './style-pipeline.js';\n\nexport enum DiagnosticModes {\n None = 0,\n Option = 1 << 0,\n Syntactic = 1 << 1,\n Semantic = 1 << 2,\n All = Option | Syntactic | Semantic,\n}\n\nexport interface PluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n advanced?: {\n /**\n * Custom TypeScript transformers that are run before Angular compilation\n */\n tsTransformers?: ts.CustomTransformers;\n };\n supportedBrowsers?: string[];\n transformFilter?: (code: string, id: string) => boolean;\n /**\n * Additional files to include in compilation\n */\n include?: string[];\n additionalContentDirs?: string[];\n /**\n * Enables Angular's HMR during development/watch mode.\n *\n * Defaults to `true` for watch mode. Set to `false` to disable HMR while\n * keeping other stylesheet externalization behavior available when needed.\n */\n hmr?: boolean;\n /**\n * @deprecated Use `hmr` instead. Kept as a compatibility alias.\n */\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n fileReplacements?: FileReplacement[];\n experimental?: {\n useAngularCompilationAPI?: boolean;\n };\n /**\n * Enable debug logging for specific scopes.\n *\n * - `true` → enables all `analog:angular:*` scopes\n * - `string[]` → enables listed namespaces (e.g. `['analog:angular:tailwind']`)\n * - `{ scopes?, mode? }` → object form with optional `mode: 'build' | 'dev'`\n * to restrict output to a specific Vite command (omit for both)\n *\n * Also responds to the `DEBUG` env var (Node.js) or `localStorage.debug`\n * (browser), using the `obug` convention.\n */\n debug?: DebugOption;\n /**\n * Optional preprocessor that transforms component CSS before it enters Vite's\n * preprocessCSS pipeline. Runs on every component stylesheet (both external\n * `.component.css` files and inline `styles: [...]` blocks).\n *\n * @param code - Raw CSS content of the component stylesheet\n * @param filename - Resolved file path of the stylesheet (or containing .ts file for inline styles)\n * @returns Transformed CSS string, or the original code if no transformation is needed\n */\n stylePreprocessor?: StylePreprocessor;\n /**\n * Experimental Angular stylesheet-resource hooks for community-maintained\n * style-pipeline plugins.\n *\n * These hooks run inside the Angular resource pipeline, which is the seam a\n * standalone Vite plugin cannot own on its own.\n */\n stylePipeline?: AngularStylePipelineOptions;\n /**\n * First-class Tailwind CSS v4 integration for Angular component styles.\n *\n * Angular's compiler processes component CSS through Vite's `preprocessCSS()`,\n * which runs `@tailwindcss/vite` — but each component stylesheet is processed\n * in isolation without access to the root Tailwind configuration (prefix, @theme,\n * @custom-variant, @plugin definitions). This causes errors like:\n *\n * \"Cannot apply utility class `sa:grid` because the `sa` variant does not exist\"\n *\n * The `tailwindCss` option solves this by auto-injecting a `@reference` directive\n * into every component CSS file that uses Tailwind utilities, pointing it to the\n * root Tailwind stylesheet so `@tailwindcss/vite` can resolve the full configuration.\n *\n * @example Basic usage — reference a root Tailwind CSS file:\n * ```ts\n * import { resolve } from 'node:path';\n *\n * angular({\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, 'src/styles/tailwind.css'),\n * },\n * })\n * ```\n *\n * @example With prefix detection — only inject for files using specific prefixes:\n * ```ts\n * angular({\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, 'src/styles/tailwind.css'),\n * // Only inject @reference into files that use these prefixed classes\n * prefixes: ['sa:', 'tw:'],\n * },\n * })\n * ```\n *\n * @example AnalogJS platform — passed through the `vite` option:\n * ```ts\n * analog({\n * vite: {\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, '../../../libs/meritos/tailwind.config.css'),\n * },\n * },\n * })\n * ```\n */\n tailwindCss?: {\n /**\n * Absolute path to the root Tailwind CSS file that contains `@import \"tailwindcss\"`,\n * `@theme`, `@custom-variant`, and `@plugin` definitions.\n *\n * A `@reference` directive pointing to this file will be auto-injected into\n * component CSS files that use Tailwind utilities.\n */\n rootStylesheet: string;\n /**\n * Optional list of class prefixes to detect (e.g. `['sa:', 'tw:']`).\n * When provided, `@reference` is only injected into component CSS files that\n * contain at least one of these prefixes. When omitted, `@reference` is injected\n * into all component CSS files that contain `@apply` or `@` directives.\n *\n * @default undefined — inject into all component CSS files with `@apply`\n */\n prefixes?: string[];\n };\n}\n\nexport function normalizeIncludeGlob(\n workspaceRoot: string,\n glob: string,\n): string {\n const normalizedWorkspaceRoot = normalizePath(resolve(workspaceRoot));\n const normalizedGlob = normalizePath(glob);\n\n if (\n normalizedGlob === normalizedWorkspaceRoot ||\n normalizedGlob.startsWith(`${normalizedWorkspaceRoot}/`)\n ) {\n return normalizedGlob;\n }\n\n if (normalizedGlob.startsWith('/')) {\n return `${normalizedWorkspaceRoot}${normalizedGlob}`;\n }\n\n return normalizePath(resolve(normalizedWorkspaceRoot, normalizedGlob));\n}\n\n/**\n * TypeScript file extension regex\n * Match .(c or m)ts, .ts extensions with an optional ? for query params\n * Ignore .tsx extensions\n */\nconst TS_EXT_REGEX = /\\.[cm]?(ts)[^x]?\\??/;\nconst classNames = new Map();\n\nexport function evictDeletedFileMetadata(\n file: string,\n {\n removeActiveGraphMetadata,\n removeStyleOwnerMetadata,\n classNamesMap,\n fileTransformMap,\n }: {\n removeActiveGraphMetadata: (file: string) => void;\n removeStyleOwnerMetadata: (file: string) => void;\n classNamesMap: Map<string, string>;\n fileTransformMap: Map<string, string>;\n },\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n removeActiveGraphMetadata(normalizedFile);\n removeStyleOwnerMetadata(normalizedFile);\n classNamesMap.delete(normalizedFile);\n fileTransformMap.delete(normalizedFile);\n}\n\nexport function injectViteIgnoreForHmrMetadata(code: string): string {\n let patched = code.replace(\n /\\bimport\\(([a-zA-Z_$][\\w$]*\\.\\u0275\\u0275getReplaceMetadataURL)/g,\n 'import(/* @vite-ignore */ $1',\n );\n\n if (patched === code) {\n patched = patched.replace(\n /import\\((\\S+getReplaceMetadataURL)/g,\n 'import(/* @vite-ignore */ $1',\n );\n }\n\n return patched;\n}\n\nexport function isIgnoredHmrFile(file: string): boolean {\n return file.endsWith('.tsbuildinfo');\n}\n\ninterface DeclarationFile {\n declarationFileDir: string;\n declarationPath: string;\n data: string;\n}\n\n/**\n * Builds a resolved stylePreprocessor function from plugin options.\n *\n * When `tailwindCss` is configured, creates an injector that prepends\n * `@reference \"<rootStylesheet>\"` into component CSS that uses Tailwind\n * utilities. Uses absolute paths because Angular's externalRuntimeStyles\n * serves component CSS as virtual modules (hash-based IDs) with no\n * meaningful directory — relative paths can't resolve from a hash.\n *\n * If both `tailwindCss` and `stylePreprocessor` are provided, they are\n * chained: Tailwind reference injection runs first, then the user's\n * custom preprocessor.\n */\nfunction buildStylePreprocessor(\n options?: PluginOptions,\n): StylePreprocessor | undefined {\n const userPreprocessor = options?.stylePreprocessor;\n const stylePipelinePreprocessor = stylePipelinePreprocessorFromPlugins(\n options?.stylePipeline,\n );\n const tw = options?.tailwindCss;\n\n if (!tw && !userPreprocessor && !stylePipelinePreprocessor) {\n return undefined;\n }\n\n let tailwindPreprocessor:\n | ((code: string, filename: string) => string)\n | undefined;\n\n if (tw) {\n const rootStylesheet = tw.rootStylesheet;\n const prefixes = tw.prefixes;\n debugTailwind('configured', { rootStylesheet, prefixes });\n\n if (!existsSync(rootStylesheet)) {\n console.warn(\n `[@analogjs/vite-plugin-angular] tailwindCss.rootStylesheet not found ` +\n `at \"${rootStylesheet}\". @reference directives will point to a ` +\n `non-existent file, which will cause Tailwind CSS errors. ` +\n `Ensure the path is absolute and the file exists.`,\n );\n }\n\n tailwindPreprocessor = (code: string, filename: string): string => {\n // Skip files that already define the Tailwind config\n if (\n code.includes('@reference') ||\n code.includes('@import \"tailwindcss\"') ||\n code.includes(\"@import 'tailwindcss'\")\n ) {\n debugTailwindV('skip (already has @reference or is root)', {\n filename,\n });\n return code;\n }\n\n const needsReference = prefixes\n ? prefixes.some((prefix) => code.includes(prefix))\n : code.includes('@apply');\n\n if (!needsReference) {\n debugTailwindV('skip (no Tailwind usage detected)', { filename });\n return code;\n }\n\n debugTailwind('injected @reference via preprocessor', { filename });\n\n // Absolute path — required for virtual modules (see JSDoc above).\n return `@reference \"${rootStylesheet}\";\\n${code}`;\n };\n }\n\n if (tailwindPreprocessor && (stylePipelinePreprocessor || userPreprocessor)) {\n debugTailwind('chained with style pipeline or user stylePreprocessor');\n }\n\n return composeStylePreprocessors([\n tailwindPreprocessor,\n stylePipelinePreprocessor,\n userPreprocessor,\n ]);\n}\n\nexport function angular(options?: PluginOptions): Plugin[] {\n applyDebugOption(options?.debug, options?.workspaceRoot);\n\n /**\n * Normalize plugin options so defaults\n * are used for values not provided.\n */\n const pluginOptions = {\n tsconfigGetter: createTsConfigGetter(options?.tsconfig),\n workspaceRoot: options?.workspaceRoot ?? process.cwd(),\n inlineStylesExtension: options?.inlineStylesExtension ?? 'css',\n advanced: {\n tsTransformers: {\n before: options?.advanced?.tsTransformers?.before ?? [],\n after: options?.advanced?.tsTransformers?.after ?? [],\n afterDeclarations:\n options?.advanced?.tsTransformers?.afterDeclarations ?? [],\n },\n },\n supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],\n jit: options?.jit,\n include: options?.include ?? [],\n additionalContentDirs: options?.additionalContentDirs ?? [],\n hmr: options?.hmr ?? options?.liveReload ?? true,\n disableTypeChecking: options?.disableTypeChecking ?? true,\n fileReplacements: options?.fileReplacements ?? [],\n useAngularCompilationAPI:\n options?.experimental?.useAngularCompilationAPI ?? false,\n hasTailwindCss: !!options?.tailwindCss,\n tailwindCss: options?.tailwindCss,\n stylePreprocessor: buildStylePreprocessor(options),\n };\n\n let resolvedConfig: ResolvedConfig;\n // Store config context needed for getTsConfigPath resolution\n let tsConfigResolutionContext: {\n root: string;\n isProd: boolean;\n isLib: boolean;\n } | null = null;\n\n const ts = require('typescript');\n let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n let nextProgram: NgtscProgram | undefined;\n // Caches (always rebuild Angular program per user request)\n const tsconfigOptionsCache = new Map<\n string,\n { options: ts.CompilerOptions; rootNames: string[] }\n >();\n let cachedHost: ts.CompilerHost | undefined;\n let cachedHostKey: string | undefined;\n let includeCache: string[] = [];\n function invalidateFsCaches() {\n includeCache = [];\n }\n function invalidateTsconfigCaches() {\n // `readConfiguration` caches the root file list, so hot-added pages can be\n // missing from Angular's compilation program until we clear this state.\n tsconfigOptionsCache.clear();\n cachedHost = undefined;\n cachedHostKey = undefined;\n }\n let watchMode = false;\n let testWatchMode = isTestWatchMode();\n // Dev-time component identity index for the currently active Vite graph.\n // We intentionally populate this during the pre-transform pass instead of a\n // workspace-wide scan so diagnostics stay tied to the app the developer is\n // actually serving, and so they track hot-updated files incrementally.\n const activeGraphComponentMetadata = new Map<\n string,\n ActiveGraphComponentRecord[]\n >();\n const selectorOwners = new Map<string, Set<string>>();\n const classNameOwners = new Map<string, Set<string>>();\n const transformedStyleOwnerMetadata = new Map<string, StyleOwnerRecord[]>();\n const styleSourceOwners = new Map<string, Set<string>>();\n\n function shouldEnableHmr(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n return !!(effectiveWatchMode && pluginOptions.hmr);\n }\n\n /**\n * Determines whether Angular should externalize component styles.\n *\n * When true, Angular emits style references (hash-based IDs) instead of\n * inlining CSS strings. Vite's resolveId → load → transform pipeline\n * then serves these virtual modules, allowing @tailwindcss/vite to\n * process @reference directives.\n *\n * Required for TWO independent use-cases:\n * 1. HMR — Vite needs external modules for hot replacement\n * 2. Tailwind CSS (hasTailwindCss) — styles must pass through Vite's\n * CSS pipeline so @tailwindcss/vite can resolve @apply directives\n *\n * In production builds (!watchMode), styles are NOT externalized — they\n * are inlined after preprocessCSS runs eagerly in transformStylesheet.\n */\n function shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n if (!effectiveWatchMode) return false;\n return !!(shouldEnableHmr() || pluginOptions.hasTailwindCss);\n }\n\n /**\n * Validates the Tailwind CSS integration configuration and emits actionable\n * warnings for common misconfigurations that cause silent failures.\n *\n * Called once during `configResolved` when `tailwindCss` is configured.\n */\n function validateTailwindConfig(\n config: ResolvedConfig,\n isWatchMode: boolean,\n ): void {\n const PREFIX = '[@analogjs/vite-plugin-angular]';\n const tw = pluginOptions.tailwindCss;\n\n if (!tw) return;\n\n // rootStylesheet must be absolute — relative paths break when Angular\n // externalizes styles as hash-based virtual modules.\n if (!isAbsolute(tw.rootStylesheet)) {\n console.warn(\n `${PREFIX} tailwindCss.rootStylesheet must be an absolute path. ` +\n `Got: \"${tw.rootStylesheet}\". Use path.resolve(__dirname, '...') ` +\n `in your vite.config to convert it.`,\n );\n }\n\n // Dev: @tailwindcss/vite must be registered, otherwise component CSS\n // with @apply/@reference silently fails.\n const resolvedPlugins = config.plugins;\n const hasTailwindPlugin = resolvedPlugins.some(\n (p) =>\n p.name.startsWith('@tailwindcss/vite') ||\n p.name.startsWith('tailwindcss'),\n );\n\n if (isWatchMode && !hasTailwindPlugin) {\n throw new Error(\n `${PREFIX} tailwindCss is configured but no @tailwindcss/vite ` +\n `plugin was found. Component CSS with @apply directives will ` +\n `not be processed.\\n\\n` +\n ` Fix: npm install @tailwindcss/vite --save-dev\\n` +\n ` Then add tailwindcss() to your vite.config plugins array.\\n`,\n );\n }\n\n // Monorepo: rootStylesheet outside project root needs server.fs.allow\n if (isWatchMode && tw.rootStylesheet) {\n const projectRoot = config.root;\n if (!tw.rootStylesheet.startsWith(projectRoot)) {\n const fsAllow = config.server?.fs?.allow ?? [];\n const isAllowed = fsAllow.some((allowed) =>\n tw.rootStylesheet.startsWith(allowed),\n );\n if (!isAllowed) {\n console.warn(\n `${PREFIX} tailwindCss.rootStylesheet is outside the Vite ` +\n `project root. The dev server may reject it with 403.\\n\\n` +\n ` Root: ${projectRoot}\\n` +\n ` Stylesheet: ${tw.rootStylesheet}\\n\\n` +\n ` Fix: server.fs.allow: ['${dirname(tw.rootStylesheet)}']\\n`,\n );\n }\n }\n }\n\n // Empty prefixes array means no component stylesheets get @reference\n if (tw.prefixes !== undefined && tw.prefixes.length === 0) {\n console.warn(\n `${PREFIX} tailwindCss.prefixes is an empty array. No component ` +\n `stylesheets will receive @reference injection. Either remove ` +\n `the prefixes option (to use @apply detection) or specify your ` +\n `prefixes: ['tw:']\\n`,\n );\n }\n\n // Duplicate analog() registrations cause orphaned style maps\n const analogInstances = resolvedPlugins.filter(\n (p) => p.name === '@analogjs/vite-plugin-angular',\n );\n if (analogInstances.length > 1) {\n throw new Error(\n `${PREFIX} analog() is registered ${analogInstances.length} times. ` +\n `Each instance creates separate style maps, causing component ` +\n `styles to be lost. Remove duplicate registrations.`,\n );\n }\n\n // rootStylesheet content must contain @import \"tailwindcss\"\n if (existsSync(tw.rootStylesheet)) {\n try {\n const rootContent = readFileSync(tw.rootStylesheet, 'utf-8');\n if (\n !rootContent.includes('@import \"tailwindcss\"') &&\n !rootContent.includes(\"@import 'tailwindcss'\")\n ) {\n console.warn(\n `${PREFIX} tailwindCss.rootStylesheet does not contain ` +\n `@import \"tailwindcss\". The @reference directive will ` +\n `point to a file without Tailwind configuration.\\n\\n` +\n ` File: ${tw.rootStylesheet}\\n`,\n );\n }\n } catch {\n // Silently skip — existence check already warned in buildStylePreprocessor.\n }\n }\n }\n\n function isLikelyPageOnlyComponent(id: string): boolean {\n return (\n id.includes('/pages/') ||\n /\\.page\\.[cm]?[jt]sx?$/i.test(id) ||\n /\\([^/]+\\)\\.page\\.[cm]?[jt]sx?$/i.test(id)\n );\n }\n\n function removeActiveGraphMetadata(file: string) {\n const previous = activeGraphComponentMetadata.get(file);\n if (!previous) {\n return;\n }\n\n for (const record of previous) {\n const location = `${record.file}#${record.className}`;\n if (record.selector) {\n const selectorSet = selectorOwners.get(record.selector);\n selectorSet?.delete(location);\n if (selectorSet?.size === 0) {\n selectorOwners.delete(record.selector);\n }\n }\n\n const classNameSet = classNameOwners.get(record.className);\n classNameSet?.delete(location);\n if (classNameSet?.size === 0) {\n classNameOwners.delete(record.className);\n }\n }\n\n activeGraphComponentMetadata.delete(file);\n }\n\n function registerActiveGraphMetadata(\n file: string,\n records: ActiveGraphComponentRecord[],\n ) {\n removeActiveGraphMetadata(file);\n\n if (records.length === 0) {\n return;\n }\n\n activeGraphComponentMetadata.set(file, records);\n\n for (const record of records) {\n const location = `${record.file}#${record.className}`;\n\n if (record.selector) {\n let selectorSet = selectorOwners.get(record.selector);\n if (!selectorSet) {\n selectorSet = new Set<string>();\n selectorOwners.set(record.selector, selectorSet);\n }\n selectorSet.add(location);\n }\n\n let classNameSet = classNameOwners.get(record.className);\n if (!classNameSet) {\n classNameSet = new Set<string>();\n classNameOwners.set(record.className, classNameSet);\n }\n classNameSet.add(location);\n }\n }\n\n function removeStyleOwnerMetadata(file: string) {\n const previous = transformedStyleOwnerMetadata.get(file);\n if (!previous) {\n return;\n }\n\n for (const record of previous) {\n const owners = styleSourceOwners.get(record.sourcePath);\n owners?.delete(record.ownerFile);\n if (owners?.size === 0) {\n styleSourceOwners.delete(record.sourcePath);\n }\n }\n\n transformedStyleOwnerMetadata.delete(file);\n }\n\n function registerStyleOwnerMetadata(file: string, styleUrls: string[]) {\n removeStyleOwnerMetadata(file);\n\n const records = styleUrls\n .map((urlSet) => {\n const [, absoluteFileUrl] = urlSet.split('|');\n return absoluteFileUrl\n ? {\n ownerFile: file,\n sourcePath: normalizePath(absoluteFileUrl),\n }\n : undefined;\n })\n .filter((record): record is StyleOwnerRecord => !!record);\n\n if (records.length === 0) {\n return;\n }\n\n transformedStyleOwnerMetadata.set(file, records);\n\n for (const record of records) {\n let owners = styleSourceOwners.get(record.sourcePath);\n if (!owners) {\n owners = new Set<string>();\n styleSourceOwners.set(record.sourcePath, owners);\n }\n owners.add(record.ownerFile);\n }\n }\n\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';\n\n const jit =\n typeof pluginOptions?.jit !== 'undefined' ? pluginOptions.jit : isTest;\n let viteServer: ViteDevServer | undefined;\n\n const styleUrlsResolver = new StyleUrlsResolver();\n const templateUrlsResolver = new TemplateUrlsResolver();\n let outputFile: ((file: string) => void) | undefined;\n const outputFiles = new Map<string, EmitFileResult>();\n const fileEmitter = (file: string) => {\n outputFile?.(file);\n return outputFiles.get(normalizePath(file));\n };\n let initialCompilation = false;\n const declarationFiles: DeclarationFile[] = [];\n const fileTransformMap = new Map<string, string>();\n let styleTransform: (\n code: string,\n filename: string,\n ) => Promise<vite.PreprocessCSSResult>;\n let pendingCompilation: Promise<void> | null;\n let compilationLock = Promise.resolve();\n // Persistent Angular Compilation API instance. Kept alive across rebuilds so\n // Angular can diff previous state and emit `templateUpdates` for HMR.\n // Previously the compilation was recreated on every pass, which meant Angular\n // never had prior state and could never produce HMR payloads.\n let angularCompilation:\n | Awaited<ReturnType<typeof createAngularCompilationType>>\n | undefined;\n\n function angularPlugin(): Plugin {\n let isProd = false;\n\n if (angularFullVersion < 190000 && pluginOptions.hmr) {\n // Angular < 19 does not support externalRuntimeStyles or _enableHmr.\n debugHmr('hmr disabled: Angular version does not support HMR APIs', {\n angularVersion: angularFullVersion,\n isTest,\n });\n console.warn(\n '[@analogjs/vite-plugin-angular]: HMR was disabled because Angular v19+ is required for externalRuntimeStyles/_enableHmr support. Detected Angular version: %s.',\n angularFullVersion,\n );\n pluginOptions.hmr = false;\n }\n\n if (isTest) {\n // Test mode: disable HMR because\n // Vitest's runner doesn't support Vite's WebSocket-based HMR.\n // This does NOT block style externalization — shouldExternalizeStyles()\n // independently checks hasTailwindCss, so Tailwind utilities in\n // component styles still work in unit tests.\n pluginOptions.hmr = false;\n debugHmr('hmr disabled', {\n angularVersion: angularFullVersion,\n isTest,\n });\n }\n\n // HMR and fileReplacements guards were previously here and forced\n // both options off when useAngularCompilationAPI was enabled. Those guards\n // have been removed because:\n // - HMR: the persistent compilation instance (above) now gives\n // Angular the prior state it needs to emit `templateUpdates` for HMR\n // - fileReplacements: Angular's AngularHostOptions already accepts a\n // `fileReplacements` record — we now convert and pass it through in\n // `performAngularCompilation` via `toAngularCompilationFileReplacements`\n if (pluginOptions.useAngularCompilationAPI) {\n if (angularFullVersion < 200100) {\n pluginOptions.useAngularCompilationAPI = false;\n debugCompilationApi(\n 'disabled: Angular version %s < 20.1',\n angularFullVersion,\n );\n console.warn(\n '[@analogjs/vite-plugin-angular]: The Angular Compilation API is only available with Angular v20.1 and later',\n );\n } else {\n debugCompilationApi('enabled (Angular %s)', angularFullVersion);\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular',\n async config(config, { command }) {\n activateDeferredDebug(command);\n watchMode = command === 'serve';\n isProd =\n config.mode === 'production' ||\n process.env['NODE_ENV'] === 'production';\n\n // Store the config context for later resolution in configResolved\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n // Do a preliminary resolution for esbuild plugin (before configResolved)\n const preliminaryTsConfigPath = resolveTsConfigPath();\n\n const esbuild = pluginOptions.useAngularCompilationAPI\n ? undefined\n : (config.esbuild ?? false);\n const oxc = pluginOptions.useAngularCompilationAPI\n ? undefined\n : (config.oxc ?? false);\n if (pluginOptions.useAngularCompilationAPI) {\n debugCompilationApi(\n 'esbuild/oxc disabled, Angular handles transforms',\n );\n }\n\n const defineOptions = {\n ngJitMode: 'false',\n ngI18nClosureMode: 'false',\n ...(watchMode ? {} : { ngDevMode: 'false' }),\n };\n const useRolldown = isRolldown();\n const jsTransformConfigKey = getJsTransformConfigKey();\n const jsTransformConfigValue =\n jsTransformConfigKey === 'oxc' ? oxc : esbuild;\n\n const rolldownOptions: vite.DepOptimizationOptions['rolldownOptions'] =\n {\n plugins: [\n createRolldownCompilerPlugin(\n {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit,\n incremental: watchMode,\n },\n // Astro manages the transformer lifecycle externally.\n !isAstroIntegration,\n ),\n ],\n };\n\n const esbuildOptions: vite.DepOptimizationOptions['esbuildOptions'] = {\n plugins: [\n createCompilerPlugin(\n {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit,\n incremental: watchMode,\n },\n isTest,\n !isAstroIntegration,\n ),\n ],\n define: defineOptions,\n };\n\n return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown ? { rolldownOptions } : { esbuildOptions }),\n },\n resolve: {\n conditions: [\n 'style',\n ...(config.resolve?.conditions || defaultClientConditions),\n ],\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n\n if (pluginOptions.hasTailwindCss) {\n validateTailwindConfig(config, watchMode);\n }\n\n if (pluginOptions.useAngularCompilationAPI) {\n stylesheetRegistry = new AnalogStylesheetRegistry();\n configureStylePipelineRegistry(\n pluginOptions.stylePipeline,\n stylesheetRegistry,\n {\n workspaceRoot: pluginOptions.workspaceRoot,\n },\n );\n debugStyles(\n 'stylesheet registry initialized (Angular Compilation API)',\n );\n }\n\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\n\n if (isTest) {\n // set test watch mode\n // - vite override from vitest-angular\n // - @nx/vite executor set server.watch explicitly to undefined (watch)/null (watch=false)\n // - vite config for test.watch variable\n // - vitest watch mode detected from the command line\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 // Add/unlink changes the TypeScript program shape, not just file\n // contents, so we need to invalidate both include discovery and the\n // cached tsconfig root names before recompiling.\n const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(\n invalidateFsCaches,\n invalidateTsconfigCaches,\n () => performCompilation(resolvedConfig),\n );\n server.watcher.on('add', invalidateCompilationOnFsChange);\n server.watcher.on('unlink', (file) => {\n evictDeletedFileMetadata(file, {\n removeActiveGraphMetadata,\n removeStyleOwnerMetadata,\n classNamesMap: classNames as Map<string, string>,\n fileTransformMap,\n });\n return invalidateCompilationOnFsChange();\n });\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n // Defer the first compilation in test mode\n if (!isVitestVscode) {\n await performCompilation(resolvedConfig);\n pendingCompilation = null;\n\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 pendingCompilation = performCompilation(resolvedConfig, [fileId]);\n\n let result;\n\n if (shouldEnableHmr()) {\n await pendingCompilation;\n pendingCompilation = null;\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n });\n debugHmrV('ts hmr evaluation', {\n file: ctx.file,\n fileId,\n hasResult: !!result,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n className: classNames.get(fileId),\n updateCode: result?.hmrUpdateCode\n ? describeStylesheetContent(result.hmrUpdateCode)\n : undefined,\n errors: result?.errors?.length ?? 0,\n warnings: result?.warnings?.length ?? 0,\n hint: result?.hmrEligible\n ? 'A TS-side component change, including inline template edits, produced an Angular HMR payload.'\n : 'No Angular HMR payload was emitted for this TS change; the change may not affect component template state.',\n });\n }\n\n if (\n shouldEnableHmr() &&\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 debugHmrV('ts hmr component update payload', {\n file: ctx.file,\n fileId,\n relativeFileId,\n className: classNames.get(fileId),\n });\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n\n return ctx.modules.map((mod) => {\n if (mod.id === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {\n debugHmr('resource file changed', { file: ctx.file });\n fileTransformMap.delete(ctx.file.split('?')[0]);\n if (/\\.(css|less|sass|scss)$/.test(ctx.file)) {\n refreshStylesheetRegistryForFile(\n ctx.file,\n stylesheetRegistry,\n pluginOptions.stylePreprocessor,\n );\n }\n if (\n /\\.(css|less|sass|scss)$/.test(ctx.file) &&\n existsSync(ctx.file)\n ) {\n try {\n const rawResource = readFileSync(ctx.file, 'utf-8');\n debugHmrV('resource source snapshot', {\n file: ctx.file,\n mtimeMs: safeStatMtimeMs(ctx.file),\n ...describeStylesheetContent(rawResource),\n });\n } catch (error) {\n debugHmrV('resource source snapshot failed', {\n file: ctx.file,\n error: String(error),\n });\n }\n }\n // Angular component resources frequently enter HMR with incomplete\n // watcher context. In practice `ctx.modules` may only contain the\n // source file, only the `?direct` module, or nothing at all after a\n // TS-driven component refresh. Resolve the full live module set from\n // Vite's module graph and our stylesheet registry before deciding how\n // to hot update the resource.\n const fileModules = await getModulesForChangedFile(\n ctx.server,\n ctx.file,\n ctx.modules,\n stylesheetRegistry,\n );\n debugHmrV('resource modules resolved', {\n file: ctx.file,\n eventModuleCount: ctx.modules.length,\n fileModuleCount: fileModules.length,\n modules: fileModules.map((mod) => ({\n id: mod.id,\n file: mod.file,\n type: mod.type,\n url: mod.url,\n })),\n });\n /**\n * Check to see if this was a direct request\n * for an external resource (styles, html).\n */\n const isDirect = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?direct') &&\n isModuleForChangedResource(mod, ctx.file, stylesheetRegistry),\n );\n const isInline = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?inline') &&\n isModuleForChangedResource(mod, ctx.file, stylesheetRegistry),\n );\n debugHmrV('resource direct/inline detection', {\n file: ctx.file,\n hasDirect: !!isDirect,\n directId: isDirect?.id,\n hasInline: !!isInline,\n inlineId: isInline?.id,\n });\n\n if (isDirect || isInline) {\n if (shouldExternalizeStyles() && isDirect?.id && isDirect.file) {\n const isComponentStyle =\n isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);\n debugHmrV('resource direct branch', {\n file: ctx.file,\n directId: isDirect.id,\n directType: isDirect.type,\n shouldExternalize: shouldExternalizeStyles(),\n isComponentStyle,\n });\n if (isComponentStyle) {\n const { encapsulation } = getComponentStyleSheetMeta(\n isDirect.id,\n );\n // Angular component styles are served through two live module\n // shapes:\n // 1. a `?direct&ngcomp=...` CSS module that Vite can patch with\n // a normal `css-update`\n // 2. a `?ngcomp=...` JS wrapper module that embeds `__vite__css`\n // for Angular's runtime consumption\n //\n // If we only patch the direct CSS module, the browser can keep\n // running a stale wrapper whose embedded CSS no longer matches\n // the source file. We therefore invalidate any wrapper modules\n // that map back to the same source stylesheet before sending\n // the CSS update.\n const wrapperModules =\n await findComponentStylesheetWrapperModules(\n ctx.server,\n ctx.file,\n isDirect,\n fileModules,\n stylesheetRegistry,\n );\n const stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(\n ctx.file,\n isDirect,\n stylesheetRegistry,\n wrapperModules,\n pluginOptions.stylePreprocessor,\n );\n debugStylesV('HMR: component stylesheet changed', {\n file: isDirect.file,\n encapsulation,\n });\n debugHmrV('component stylesheet wrapper modules', {\n file: ctx.file,\n wrapperCount: wrapperModules.length,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n availableModuleIds: fileModules.map((mod) => mod.id),\n });\n debugHmrV(\n 'component stylesheet pipeline diagnosis',\n stylesheetDiagnosis,\n );\n\n // The stylesheet registry may already hold the fresh served CSS\n // while Vite still has a stale transform result cached for the\n // direct `?direct&ngcomp=...` module id. Invalidate the direct\n // module up front so subsequent wrapper generation and explicit\n // fetches cannot keep serving the pre-edit CSS payload.\n ctx.server.moduleGraph.invalidateModule(isDirect);\n debugHmrV('component stylesheet direct module invalidated', {\n file: ctx.file,\n directModuleId: isDirect.id,\n directModuleUrl: isDirect.url,\n reason:\n 'Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues.',\n });\n\n // Track if the component uses ShadowDOM encapsulation\n // Shadow DOM components currently require a full reload.\n // Vite's CSS hot replacement does not support shadow root searching.\n const trackedWrapperRequestIds =\n stylesheetDiagnosis.trackedRequestIds.filter((id) =>\n id.includes('?ngcomp='),\n );\n const canUseCssUpdate =\n encapsulation !== 'shadow' &&\n (wrapperModules.length > 0 ||\n trackedWrapperRequestIds.length > 0);\n\n if (canUseCssUpdate) {\n wrapperModules.forEach((mod) =>\n ctx.server.moduleGraph.invalidateModule(mod),\n );\n // A live wrapper ModuleNode is ideal because we can\n // invalidate it directly, but it is not strictly required.\n // When the browser has already loaded the wrapper URL and the\n // registry knows that wrapper request id, a normal CSS patch\n // against the direct stylesheet is still the most accurate\n // update path available. Falling back to full reload in that\n // state is needlessly pessimistic and causes the exact UX\n // regression we are trying to eliminate.\n debugHmrV('sending css-update for component stylesheet', {\n file: ctx.file,\n path: isDirect.url,\n acceptedPath: isDirect.file,\n wrapperCount: wrapperModules.length,\n trackedWrapperRequestIds,\n hint:\n wrapperModules.length > 0\n ? 'Live wrapper modules were found and invalidated before sending the CSS update.'\n : '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.',\n });\n sendCssUpdate(ctx.server, {\n path: isDirect.url,\n acceptedPath: isDirect.file,\n });\n logComponentStylesheetHmrOutcome({\n file: ctx.file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'css-update',\n directModuleId: isDirect.id,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n });\n\n return union(\n fileModules\n .filter((mod) => {\n // Component stylesheets will have 2 modules (*.component.scss and *.component.scss?direct&ngcomp=xyz&e=x)\n // We remove the module with the query params to prevent vite double logging the stylesheet name \"hmr update *.component.scss, *.component.scss?direct&ngcomp=xyz&e=x\"\n return mod.file !== ctx.file || mod.id !== isDirect.id;\n })\n .map((mod) => {\n if (mod.file === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n }) as ModuleNode[],\n wrapperModules.map((mod) => markModuleSelfAccepting(mod)),\n );\n }\n\n // A direct CSS patch without the browser-visible `?ngcomp=...`\n // wrapper module is not trustworthy. Angular consumes the\n // wrapper JS module, which embeds `__vite__css` for runtime\n // style application. When that wrapper is missing from the live\n // module graph, prefer correctness over a partial update and\n // force a reload so the component re-evaluates with fresh CSS.\n debugHmrV('component stylesheet hmr fallback: full reload', {\n file: ctx.file,\n encapsulation,\n reason:\n trackedWrapperRequestIds.length === 0\n ? 'missing-wrapper-module'\n : encapsulation === 'shadow'\n ? 'shadow-encapsulation'\n : 'tracked-wrapper-still-not-patchable',\n directId: isDirect.id,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? [],\n });\n const ownerModules = findStyleOwnerModules(\n ctx.server,\n ctx.file,\n styleSourceOwners,\n );\n debugHmrV('component stylesheet owner fallback lookup', {\n file: ctx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n ownerFiles: [\n ...(styleSourceOwners.get(normalizePath(ctx.file)) ?? []),\n ],\n });\n\n if (ownerModules.length > 0) {\n pendingCompilation = performCompilation(resolvedConfig, [\n ...ownerModules.map((mod) => mod.id).filter(Boolean),\n ]);\n await pendingCompilation;\n pendingCompilation = null;\n\n const updates = ownerModules\n .map((mod) => mod.id)\n .filter((id): id is string => !!id && !!classNames.get(id));\n const derivedUpdates = ownerModules\n .map((mod) => mod.id)\n .filter((id): id is string => !!id)\n .flatMap((ownerId) =>\n resolveComponentClassNamesForStyleOwner(\n ownerId,\n ctx.file,\n ).map((className) => ({\n ownerId,\n className,\n via: 'raw-component-metadata' as const,\n })),\n );\n debugHmrV('component stylesheet owner fallback compilation', {\n file: ctx.file,\n ownerIds: ownerModules.map((mod) => mod.id),\n updateIds: updates,\n classNames: updates.map((id) => ({\n id,\n className: classNames.get(id),\n })),\n derivedUpdates,\n });\n // Keep owner recompilation and metadata derivation as\n // diagnostics only. For externalized component styles, a\n // component-update message is not a safe substitute for a\n // missing `?ngcomp=...` wrapper module because Angular can\n // re-render the component without forcing the browser to\n // re-evaluate the live stylesheet wrapper. That exact shape\n // produced false-positive \"successful HMR\" logs while the UI\n // stayed visually stale. If the wrapper is absent, prefer a\n // hard reload after gathering the owner evidence needed to\n // explain why the fallback was necessary.\n if (derivedUpdates.length > 0) {\n debugHmrV(\n 'component stylesheet owner fallback derived updates',\n {\n file: ctx.file,\n updates: derivedUpdates,\n hint: 'Angular did not repopulate classNames during CSS-only owner recompilation, so Analog derived component identities from raw component metadata.',\n },\n );\n }\n }\n\n logComponentStylesheetHmrOutcome({\n file: ctx.file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'full-reload',\n directModuleId: isDirect.id,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n ownerIds: ownerModules.map((mod) => mod.id),\n });\n sendFullReload(ctx.server, {\n file: ctx.file,\n encapsulation,\n reason:\n wrapperModules.length === 0\n ? 'missing-wrapper-module-and-no-owner-updates'\n : 'shadow-encapsulation',\n directId: isDirect.id,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? [],\n });\n return [];\n }\n }\n return fileModules;\n }\n\n if (\n shouldEnableHmr() &&\n /\\.(html|htm)$/.test(ctx.file) &&\n fileModules.length === 0\n ) {\n const ownerModules = findTemplateOwnerModules(ctx.server, ctx.file);\n debugHmrV('template owner lookup', {\n file: ctx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n hint:\n ownerModules.length > 0\n ? 'The external template has candidate TS owner modules that can be recompiled for HMR.'\n : 'No TS owner modules were visible for this external template change; HMR will fall through to the generic importer path.',\n });\n if (ownerModules.length > 0) {\n const ownerIds = ownerModules\n .map((mod) => mod.id)\n .filter(Boolean) as string[];\n\n ownerModules.forEach((mod) =>\n ctx.server.moduleGraph.invalidateModule(mod),\n );\n\n pendingCompilation = performCompilation(resolvedConfig, ownerIds);\n await pendingCompilation;\n pendingCompilation = null;\n\n const updates = ownerIds.filter((id) => classNames.get(id));\n debugHmrV('template owner recompilation result', {\n file: ctx.file,\n ownerIds,\n updates,\n updateClassNames: updates.map((id) => ({\n id,\n className: classNames.get(id),\n })),\n hint:\n updates.length > 0\n ? 'External template recompilation produced Angular component update targets.'\n : 'External template recompilation completed, but no Angular component update targets were surfaced.',\n });\n if (updates.length > 0) {\n debugHmr('template owner module invalidation', {\n file: ctx.file,\n ownerIds,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), updateId),\n )}@${classNames.get(updateId)}`;\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n });\n\n return ownerModules.map((mod) => markModuleSelfAccepting(mod));\n }\n }\n }\n\n const mods: ModuleNode[] = [];\n const updates: string[] = [];\n fileModules.forEach((mod) => {\n mod.importers.forEach((imp) => {\n ctx.server.moduleGraph.invalidateModule(imp);\n\n if (shouldExternalizeStyles() && classNames.get(imp.id)) {\n updates.push(imp.id as string);\n } else {\n mods.push(imp);\n }\n });\n });\n debugHmrV('resource importer analysis', {\n file: ctx.file,\n fileModuleCount: fileModules.length,\n importerCount: fileModules.reduce(\n (count, mod) => count + mod.importers.size,\n 0,\n ),\n updates,\n mods: mods.map((mod) => mod.id),\n });\n\n pendingCompilation = performCompilation(resolvedConfig, [\n ...mods.map((mod) => mod.id).filter(Boolean),\n ...updates,\n ]);\n\n if (updates.length > 0) {\n await pendingCompilation;\n pendingCompilation = null;\n\n debugHmr('resource importer component updates', {\n file: ctx.file,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n const impRelativeFileId = `${normalizePath(\n relative(process.cwd(), updateId),\n )}@${classNames.get(updateId)}`;\n\n sendHMRComponentUpdate(ctx.server, impRelativeFileId);\n });\n\n return fileModules.map((mod) => {\n if (mod.id === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n\n return mods;\n }\n\n // clear HMR updates with a full reload\n debugHmr('full reload — unrecognized file type', { file: ctx.file });\n classNames.clear();\n return ctx.modules;\n },\n resolveId(id, importer) {\n if (jit && id.startsWith('angular:jit:')) {\n const path = id.split(';')[1];\n return `${normalizePath(\n resolve(dirname(importer as string), path),\n )}?${id.includes(':style') ? 'inline' : 'raw'}`;\n }\n\n // Map angular component stylesheets. Prefer registry-served CSS\n // (preprocessed, with @reference) over external raw file mappings\n // file path). Without this priority, Angular may emit a basename ID\n // that resolves to the raw file, bypassing preprocessing.\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n\n if (stylesheetRegistry?.hasServed(filename)) {\n debugStylesV('resolveId: kept preprocessed ID', { filename });\n return id;\n }\n\n const componentStyles =\n stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n debugStylesV('resolveId: mapped external stylesheet', {\n filename,\n resolvedPath: componentStyles,\n });\n return componentStyles + new URL(id, 'http://localhost').search;\n }\n\n debugStyles(\n 'resolveId: component stylesheet NOT FOUND in either map',\n {\n filename,\n inlineMapSize: stylesheetRegistry?.servedCount ?? 0,\n externalMapSize: stylesheetRegistry?.externalCount ?? 0,\n },\n );\n }\n\n return undefined;\n },\n async load(id) {\n // Map angular inline styles to the source text\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const componentStyles =\n stylesheetRegistry?.getServedContent(filename);\n if (componentStyles) {\n stylesheetRegistry?.registerActiveRequest(id);\n // Register the concrete request id that was just served. During HMR\n // the changed file event references the original source stylesheet\n // path, but the live browser module graph references hashed\n // stylesheet request ids such as `/abc123.css?ngcomp=...`. This is\n // the bridge between those two worlds.\n debugHmrV('stylesheet active request registered', {\n requestId: id,\n filename,\n sourcePath:\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\n filename.replace(/^\\//, ''),\n ),\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\n filename.replace(/^\\//, ''),\n ) ??\n '',\n ) ?? [],\n });\n debugStylesV('load: served inline component stylesheet', {\n filename,\n length: componentStyles.length,\n requestId: id,\n ...describeStylesheetContent(componentStyles),\n });\n return componentStyles;\n }\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [/node_modules/, 'type=script', '@ng/component'],\n },\n },\n async handler(code, id) {\n /**\n * Check for options.transformFilter\n */\n if (\n options?.transformFilter &&\n !(options?.transformFilter(code, id) ?? true)\n ) {\n return;\n }\n\n if (pluginOptions.useAngularCompilationAPI) {\n const isAngular =\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n\n if (!isAngular) {\n debugCompilationApi('transform skip (non-Angular file)', { id });\n return;\n }\n }\n\n /**\n * Skip transforming content files\n */\n if (id.includes('?') && id.includes('analog-content-')) {\n return;\n }\n\n /**\n * Encapsulate component stylesheets that use emulated encapsulation.\n * Must run whenever styles are externalized (not just HMR), because\n * Angular's externalRuntimeStyles skips its own encapsulation when\n * styles are external — the build tool is expected to handle it.\n */\n if (shouldExternalizeStyles() && isComponentStyleSheet(id)) {\n const { encapsulation, componentId } =\n getComponentStyleSheetMeta(id);\n if (encapsulation === 'emulated' && componentId) {\n debugStylesV('applying emulated view encapsulation', {\n stylesheet: id.split('?')[0],\n componentId,\n });\n const encapsulated = ngCompiler.encapsulateStyle(\n code,\n componentId,\n );\n return {\n code: encapsulated,\n map: null,\n };\n }\n }\n\n if (id.includes('.ts?')) {\n // Strip the query string off the ID\n // in case of a dynamically loaded file\n id = id.replace(/\\?(.*)/, '');\n }\n\n fileTransformMap.set(id, code);\n\n /**\n * Re-analyze on each transform\n * for test(Vitest)\n */\n if (isTest) {\n if (isVitestVscode && !initialCompilation) {\n // Do full initial compilation\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\n if (testWatchMode && invalidated) {\n pendingCompilation = performCompilation(resolvedConfig, [id]);\n }\n }\n }\n\n // Detect whether the code contains an Angular @Component decorator.\n //\n // IMPORTANT — useAngularCompilationAPI behavior:\n // When `useAngularCompilationAPI: true`, the Angular Compilation API\n // compiles TypeScript BEFORE this Vite transform hook fires. By the\n // time `code` reaches here, @Component decorators have been compiled\n // away into ɵɵdefineComponent() calls, so `hasComponent` is always\n // false for actual component files.\n //\n // This is expected and NOT a bug. The Angular Compilation API handles\n // template and style resolution through its own internal pipeline:\n // - Templates: resolved during compilation, not via templateUrls\n // - Styles: externalized and served via the resolveId/load hooks\n // (confirmed by `analog:angular:styles resolveId: mapped external\n // stylesheet` debug messages)\n //\n // The only consequence of hasComponent=false is that external template\n // and style files are not registered via addWatchFile(), which means\n // HMR for external HTML/CSS edits may trigger a full reload instead of\n // a targeted hot replacement. The Angular Compilation API's own\n // invalidation mechanism handles recompilation regardless.\n //\n // For the legacy (non-API) compilation path, hasComponent works as\n // expected because the transform hook sees raw TypeScript source.\n const hasComponent = code.includes('@Component');\n debugCompilerV('transform', {\n id,\n codeLength: code.length,\n hasComponent,\n });\n const templateUrls = hasComponent\n ? templateUrlsResolver.resolve(code, id)\n : [];\n const styleUrls = hasComponent\n ? styleUrlsResolver.resolve(code, id)\n : [];\n\n if (hasComponent && watchMode) {\n for (const urlSet of [...templateUrls, ...styleUrls]) {\n // `urlSet` is a string where a relative path is joined with an\n // absolute path using the `|` symbol.\n // For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.\n const [, absoluteFileUrl] = urlSet.split('|');\n this.addWatchFile(absoluteFileUrl);\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n\n const typescriptResult = fileEmitter(id);\n\n if (\n typescriptResult?.warnings &&\n typescriptResult?.warnings.length > 0\n ) {\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 // return fileEmitter\n let data = typescriptResult?.content ?? '';\n\n if (jit && data.includes('angular:jit:')) {\n data = data.replace(\n /angular:jit:style:inline;/g,\n 'virtual:angular:jit:style:inline;',\n );\n\n templateUrls.forEach((templateUrlSet) => {\n const [templateFile, resolvedTemplateUrl] =\n templateUrlSet.split('|');\n data = data.replace(\n `angular:jit:template:file;${templateFile}`,\n `${resolvedTemplateUrl}?raw`,\n );\n });\n\n styleUrls.forEach((styleUrlSet) => {\n const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');\n data = data.replace(\n `angular:jit:style:file;${styleFile}`,\n `${resolvedStyleUrl}?inline`,\n );\n });\n }\n\n // Angular's HMR initializer emits dynamic import() calls that Vite's\n // import-analysis plugin cannot statically analyze, producing SSR\n // warnings. The Angular compiler's IR includes a @vite-ignore comment\n // but it can be lost during TypeScript emit. Re-inject it here so the\n // warning is suppressed regardless of the compilation path used.\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n debugHmrV('vite-ignore injection', {\n id,\n dataLength: data.length,\n hasMetaUrl,\n });\n if (hasMetaUrl) {\n const patched = injectViteIgnoreForHmrMetadata(data);\n if (patched !== data && !patched.includes('@vite-ignore')) {\n debugHmrV('vite-ignore regex fallback', { id });\n }\n data = patched;\n }\n }\n\n return {\n code: data,\n map: null,\n };\n },\n },\n closeBundle() {\n declarationFiles.forEach(\n ({ declarationFileDir, declarationPath, data }) => {\n mkdirSync(declarationFileDir, { recursive: true });\n writeFileSync(declarationPath, data, 'utf-8');\n },\n );\n // Tear down the persistent compilation instance at end of build so it\n // does not leak memory across unrelated Vite invocations.\n angularCompilation?.close?.();\n angularCompilation = undefined;\n },\n };\n }\n\n return [\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n {\n name: '@analogjs/vite-plugin-angular:template-class-binding-guard',\n enforce: 'pre',\n transform(code: string, id: string) {\n if (id.includes('node_modules')) {\n return;\n }\n\n const cleanId = id.split('?')[0];\n\n if (/\\.(html|htm)$/i.test(cleanId)) {\n const staticClassIssue =\n findStaticClassAndBoundClassConflicts(code)[0];\n if (staticClassIssue) {\n throwTemplateClassBindingConflict(cleanId, staticClassIssue);\n }\n\n const mixedClassIssue = findBoundClassAndNgClassConflicts(code)[0];\n if (mixedClassIssue) {\n this.warn(\n [\n '[Analog Angular] Conflicting class composition.',\n `File: ${cleanId}:${mixedClassIssue.line}:${mixedClassIssue.column}`,\n 'This element mixes `[class]` and `[ngClass]`.',\n 'Prefer a single class-binding strategy so class merging stays predictable.',\n 'Use one `[ngClass]` expression or explicit `[class.foo]` bindings.',\n `Snippet: ${mixedClassIssue.snippet}`,\n ].join('\\n'),\n );\n }\n return;\n }\n\n if (TS_EXT_REGEX.test(cleanId)) {\n const rawStyleUrls = styleUrlsResolver.resolve(code, cleanId);\n registerStyleOwnerMetadata(cleanId, rawStyleUrls);\n debugHmrV('component stylesheet owner metadata registered', {\n file: cleanId,\n styleUrlCount: rawStyleUrls.length,\n styleUrls: rawStyleUrls,\n ownerSources: [\n ...(transformedStyleOwnerMetadata\n .get(cleanId)\n ?.map((record) => record.sourcePath) ?? []),\n ],\n });\n\n // Parse raw component decorators before Angular compilation strips\n // them. This lets Analog fail fast on template/class-footguns and\n // keep a lightweight active-graph index for duplicate selector/class\n // diagnostics without requiring a full compiler pass first.\n const components = getAngularComponentMetadata(code);\n\n const inlineTemplateIssue = components.flatMap((component) =>\n component.inlineTemplates.flatMap((template) =>\n findStaticClassAndBoundClassConflicts(template),\n ),\n )[0];\n\n if (inlineTemplateIssue) {\n throwTemplateClassBindingConflict(cleanId, inlineTemplateIssue);\n }\n\n const mixedInlineClassIssue = components.flatMap((component) =>\n component.inlineTemplates.flatMap((template) =>\n findBoundClassAndNgClassConflicts(template),\n ),\n )[0];\n\n if (mixedInlineClassIssue) {\n this.warn(\n [\n '[Analog Angular] Conflicting class composition.',\n `File: ${cleanId}:${mixedInlineClassIssue.line}:${mixedInlineClassIssue.column}`,\n 'This element mixes `[class]` and `[ngClass]`.',\n 'Prefer a single class-binding strategy so class merging stays predictable.',\n 'Use one `[ngClass]` expression or explicit `[class.foo]` bindings.',\n `Snippet: ${mixedInlineClassIssue.snippet}`,\n ].join('\\n'),\n );\n }\n\n const activeGraphRecords = components.map((component) => ({\n file: cleanId,\n className: component.className,\n selector: component.selector,\n }));\n\n registerActiveGraphMetadata(cleanId, activeGraphRecords);\n\n for (const component of components) {\n if (!component.selector && !isLikelyPageOnlyComponent(cleanId)) {\n throw new Error(\n [\n '[Analog Angular] Selectorless component detected.',\n `File: ${cleanId}`,\n `Component: ${component.className}`,\n 'This component has no `selector`, so Angular will render it as `ng-component`.',\n 'That increases the chance of component ID collisions and makes diagnostics harder to interpret.',\n 'Add an explicit selector for reusable components.',\n 'Selectorless components are only supported for page and route-only files.',\n ].join('\\n'),\n );\n }\n\n if (component.selector) {\n const selectorEntries = selectorOwners.get(component.selector);\n if (selectorEntries && selectorEntries.size > 1) {\n throw new Error(\n [\n '[Analog Angular] Duplicate component selector detected.',\n `Selector: ${component.selector}`,\n 'Multiple components in the active application graph use the same selector.',\n 'Selectors must be unique within the active graph to avoid ambiguous rendering and confusing diagnostics.',\n `Locations:\\n${formatActiveGraphLocations(selectorEntries)}`,\n ].join('\\n'),\n );\n }\n }\n\n const classNameEntries = classNameOwners.get(component.className);\n if (classNameEntries && classNameEntries.size > 1) {\n this.warn(\n [\n '[Analog Angular] Duplicate component class name detected.',\n `Class name: ${component.className}`,\n 'Two or more Angular components in the active graph share the same exported class name.',\n 'Rename one of them to keep HMR, stack traces, and compiler diagnostics unambiguous.',\n `Locations:\\n${formatActiveGraphLocations(classNameEntries)}`,\n ].join('\\n'),\n );\n }\n }\n }\n },\n } satisfies Plugin,\n // Tailwind CSS v4 @reference injection for direct-file-loaded CSS.\n // Catches CSS files loaded from disk (not virtual modules) that need\n // @reference before @tailwindcss/vite processes them.\n pluginOptions.hasTailwindCss &&\n ({\n name: '@analogjs/vite-plugin-angular:tailwind-reference',\n enforce: 'pre',\n transform(code: string, id: string) {\n const tw = pluginOptions.tailwindCss;\n if (!tw || !id.includes('.css')) return;\n\n const cleanId = id.split('?')[0];\n if (cleanId === tw.rootStylesheet) return;\n\n if (\n code.includes('@reference') ||\n code.includes('@import \"tailwindcss\"') ||\n code.includes(\"@import 'tailwindcss'\")\n ) {\n return;\n }\n\n // Skip entry stylesheets that @import the root config\n const rootBasename = basename(tw.rootStylesheet);\n if (code.includes(rootBasename)) return;\n\n const prefixes = tw.prefixes;\n const needsRef = prefixes\n ? prefixes.some((p) => code.includes(p))\n : code.includes('@apply');\n\n if (needsRef) {\n debugTailwind('injected @reference via pre-transform', {\n id: id.split('/').slice(-2).join('/'),\n });\n return `@reference \"${tw.rootStylesheet}\";\\n${code}`;\n }\n },\n } satisfies Plugin),\n angularPlugin(),\n pluginOptions.hmr && liveReloadPlugin({ classNames, fileEmitter }),\n ...(isTest && !isStackBlitz ? angularVitestPlugins() : []),\n (jit &&\n jitPlugin({\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n })) as Plugin,\n buildOptimizerPlugin({\n supportedBrowsers: pluginOptions.supportedBrowsers,\n jit,\n }),\n routerPlugin(),\n angularFullVersion < 190004 && pendingTasksPlugin(),\n nxFolderPlugin(),\n ].filter(Boolean) as Plugin[];\n\n function findIncludes() {\n // Map include patterns to absolute workspace paths\n const globs = pluginOptions.include.map((glob) =>\n normalizeIncludeGlob(pluginOptions.workspaceRoot, glob),\n );\n\n // Discover TypeScript files using tinyglobby\n return globSync(globs, {\n dot: true,\n absolute: true,\n });\n }\n\n function createTsConfigGetter(tsconfigOrGetter?: string | (() => string)) {\n if (typeof tsconfigOrGetter === 'function') {\n return tsconfigOrGetter;\n }\n\n return () => tsconfigOrGetter || '';\n }\n\n function getTsConfigPath(\n root: string,\n tsconfig: string,\n isProd: boolean,\n isTest: boolean,\n isLib: boolean,\n ) {\n if (tsconfig && isAbsolute(tsconfig)) {\n if (!existsSync(tsconfig)) {\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${tsconfig}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n }\n\n return tsconfig;\n }\n\n let tsconfigFilePath = './tsconfig.app.json';\n\n if (isLib) {\n tsconfigFilePath = isProd\n ? './tsconfig.lib.prod.json'\n : './tsconfig.lib.json';\n }\n\n if (isTest) {\n tsconfigFilePath = './tsconfig.spec.json';\n }\n\n if (tsconfig) {\n tsconfigFilePath = tsconfig;\n }\n\n const resolvedPath = resolve(root, tsconfigFilePath);\n\n if (!existsSync(resolvedPath)) {\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${resolvedPath}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n }\n\n return resolvedPath;\n }\n\n function resolveTsConfigPath() {\n const tsconfigValue = pluginOptions.tsconfigGetter();\n\n return getTsConfigPath(\n tsConfigResolutionContext!.root,\n tsconfigValue,\n tsConfigResolutionContext!.isProd,\n isTest,\n tsConfigResolutionContext!.isLib,\n );\n }\n\n /**\n * Perform compilation using Angular's private Compilation API.\n *\n * Key differences from the standard `performCompilation` path:\n * 1. The compilation instance is reused across rebuilds (nullish-coalescing\n * assignment below) so Angular retains prior state and can diff it to\n * produce `templateUpdates` for HMR.\n * 2. `ids` (modified files) are forwarded to both the source-file cache and\n * `angularCompilation.update()` so that incremental re-analysis is\n * scoped to what actually changed.\n * 3. `fileReplacements` are converted and passed into Angular's host via\n * `toAngularCompilationFileReplacements`.\n * 4. `templateUpdates` from the compilation result are mapped back to\n * file-level HMR metadata (`hmrUpdateCode`, `hmrEligible`, `classNames`).\n */\n async function performAngularCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ) {\n // Reuse the existing instance so Angular can diff against prior state.\n 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 // Notify Angular of modified files before re-initialization so it can\n // scope its incremental analysis.\n if (modifiedFiles?.size && angularCompilation.update) {\n debugCompilationApi('incremental update', {\n files: [...modifiedFiles],\n });\n await angularCompilation.update(modifiedFiles);\n }\n\n const resolvedTsConfigPath = resolveTsConfigPath();\n const compilationResult = await angularCompilation.initialize(\n resolvedTsConfigPath,\n {\n // Convert Analog's browser-style `{ replace, with }` entries into the\n // `Record<string, string>` shape that Angular's AngularHostOptions\n // expects. SSR-only replacements (`{ replace, ssr }`) are intentionally\n // excluded — they stay on the Vite runtime side.\n fileReplacements: toAngularCompilationFileReplacements(\n pluginOptions.fileReplacements,\n pluginOptions.workspaceRoot,\n ),\n modifiedFiles,\n async transformStylesheet(\n data,\n containingFile,\n resourceFile,\n order,\n className,\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 pluginOptions.stylePreprocessor,\n );\n\n // Populate classNames during initial compilation so HMR for\n // HTML template changes can find the parent TS module.\n if (shouldEnableHmr() && className && containingFile) {\n classNames.set(normalizePath(containingFile), className as string);\n }\n\n if (shouldExternalizeStyles()) {\n // Store preprocessed CSS so Vite's serve-time pipeline handles\n // PostCSS / Tailwind processing when the load hook returns it.\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 debugStylesV('stylesheet deferred content snapshot', {\n stylesheetId,\n filename,\n resourceFile: resourceFile ?? '(inline)',\n dependencies: preprocessed.dependencies,\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n ...describeStylesheetContent(preprocessed.code),\n });\n\n return stylesheetId;\n }\n\n // Non-externalized: CSS is returned directly to the Angular compiler\n // and never re-enters Vite's pipeline, so run preprocessCSS() eagerly.\n debugStyles('stylesheet processed inline via preprocessCSS', {\n filename,\n resourceFile: resourceFile ?? '(inline)',\n dataLength: preprocessed.code.length,\n });\n let stylesheetResult;\n\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 }\n\n return stylesheetResult?.code || '';\n },\n processWebWorker(workerFile, containingFile) {\n return '';\n },\n },\n (tsCompilerOptions) => {\n if (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (shouldEnableHmr()) {\n tsCompilerOptions['_enableHmr'] = true;\n // Workaround for https://github.com/angular/angular/issues/59310\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (compilation API)', {\n hmr: pluginOptions.hmr,\n hasTailwindCss: pluginOptions.hasTailwindCss,\n watchMode,\n shouldExternalize: shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions.compilationMode === 'partial') {\n // These options can't be false in partial mode\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (angularFullVersion >= 200000) {\n tsCompilerOptions['_enableSelectorless'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n return tsCompilerOptions;\n },\n );\n\n // -------------------------------------------------------------------\n // Preprocess external stylesheets for Tailwind CSS @reference\n //\n // Angular's Compilation API with externalRuntimeStyles does NOT call\n // transformStylesheet for external styleUrls (files referenced via\n // `styleUrls: ['./foo.component.css']`). Angular's angular-host.js\n // asserts this explicitly:\n //\n // assert(!resourceFile || !hostOptions.externalStylesheets?.has(resourceFile),\n // 'External runtime stylesheets should not be transformed')\n //\n // Only inline styles (`styles: [...]`) go through transformStylesheet,\n // which is where buildStylePreprocessor injects `@reference` for\n // Tailwind CSS. External component CSS files are instead reported in\n // compilationResult.externalStylesheets as Map<absolutePath, sha256Hash>.\n //\n // Without intervention, the resolveId hook maps Angular's hash to the\n // raw file path, the load hook reads the raw file from disk, and\n // @tailwindcss/vite processes CSS without @reference — causing:\n //\n // \"Cannot apply utility class 'sa:grid' because the 'sa'\n // variant does not exist\"\n //\n // Fix: for each external stylesheet, read the file from disk, run the\n // style preprocessor (which injects @reference), and store the result\n // in the stylesheet registry under Angular's hash. The resolveId hook\n // then finds it on the first lookup, the load hook serves the\n // @reference-injected version, and @tailwindcss/vite compiles correctly.\n // -------------------------------------------------------------------\n debugStyles('external stylesheets from compilation API', {\n count: compilationResult.externalStylesheets?.size ?? 0,\n hasPreprocessor: !!pluginOptions.stylePreprocessor,\n hasInlineMap: !!stylesheetRegistry,\n });\n const preprocessStats = { total: 0, injected: 0, skipped: 0, errors: 0 };\n compilationResult.externalStylesheets?.forEach((value, key) => {\n preprocessStats.total++;\n const angularHash = `${value}.css`;\n stylesheetRegistry?.registerExternalRequest(angularHash, key);\n\n // Read the raw CSS file from disk, run the style preprocessor\n // (which injects @reference for Tailwind), and store the result\n // in the stylesheet registry under Angular's hash. This way\n // resolveId finds the preprocessed version on the first lookup\n // and the load hook serves CSS that @tailwindcss/vite can compile.\n //\n // After preprocessing, resolve relative @import paths to absolute\n // paths. When @tailwindcss/vite processes the CSS, the virtual\n // hash-based module ID has no meaningful directory, so relative\n // imports like `@import './submenu/submenu.component.css'` would\n // fail to resolve from `/`. Converting to absolute paths ensures\n // Tailwind's enhanced-resolve can find the imported files.\n if (\n stylesheetRegistry &&\n pluginOptions.stylePreprocessor &&\n existsSync(key)\n ) {\n try {\n const rawCss = readFileSync(key, 'utf-8');\n const preprocessed = preprocessStylesheetResult(\n rawCss,\n key,\n pluginOptions.stylePreprocessor,\n );\n debugStylesV('external stylesheet raw snapshot', {\n angularHash,\n resolvedPath: key,\n mtimeMs: safeStatMtimeMs(key),\n ...describeStylesheetContent(rawCss),\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 debugStylesV(\n 'preprocessed external stylesheet for Tailwind @reference',\n {\n angularHash,\n resolvedPath: key,\n mtimeMs: safeStatMtimeMs(key),\n raw: describeStylesheetContent(rawCss),\n served: describeStylesheetContent(servedCss),\n dependencies: preprocessed.dependencies,\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n },\n );\n } else {\n preprocessStats.skipped++;\n debugStylesV('external stylesheet unchanged after preprocessing', {\n angularHash,\n resolvedPath: key,\n mtimeMs: safeStatMtimeMs(key),\n raw: describeStylesheetContent(rawCss),\n served: describeStylesheetContent(servedCss),\n dependencies: preprocessed.dependencies,\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n hint: 'Registry mapping is still registered so Angular component stylesheet HMR can track and refresh this file even when preprocessing makes no textual changes.',\n });\n }\n } catch (e) {\n preprocessStats.errors++;\n console.warn(\n `[@analogjs/vite-plugin-angular] failed to preprocess external stylesheet: ${key}: ${e}`,\n );\n // Non-fatal: fall through to the external source mapping which\n // serves the raw file. @tailwindcss/vite will still process\n // it but without @reference (Tailwind prefix utilities won't\n // resolve).\n }\n } else {\n preprocessStats.skipped++;\n debugStylesV('external stylesheet preprocessing skipped', {\n filename: angularHash,\n resolvedPath: key,\n reason: !stylesheetRegistry\n ? 'no stylesheetRegistry'\n : !pluginOptions.stylePreprocessor\n ? 'no stylePreprocessor'\n : 'file not found on disk',\n });\n }\n\n debugStylesV('external stylesheet registered for resolveId mapping', {\n filename: angularHash,\n resolvedPath: key,\n });\n });\n debugStyles('external stylesheet preprocessing complete', preprocessStats);\n\n const diagnostics = await angularCompilation.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 // Angular encodes template updates as `encodedFilePath@ClassName` keys.\n // `mapTemplateUpdatesToFiles` decodes them back to absolute file paths so\n // we can attach HMR metadata to the correct `EmitFileResult` below.\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 for (const file of await angularCompilation.emitAffectedFiles()) {\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 // Surface Angular's HMR payloads into Analog's existing live-reload\n // flow via the `hmrUpdateCode` / `hmrEligible` fields.\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\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 await _doPerformCompilation(config, ids);\n } finally {\n resolve!();\n }\n }\n\n /**\n * This method share mutable state and performs the actual compilation work.\n * It should not be called concurrently. Use `performCompilation` which wraps this method in a lock to ensure only one compilation runs at a time.\n */\n async function _doPerformCompilation(config: ResolvedConfig, ids?: string[]) {\n // Forward `ids` (modified files) so the Compilation API path can do\n // incremental re-analysis instead of a full recompile on every change.\n if (pluginOptions.useAngularCompilationAPI) {\n debugCompilationApi('using compilation API path', {\n modifiedFiles: ids?.length ?? 0,\n });\n await performAngularCompilation(config, ids);\n return;\n }\n\n const isProd = config.mode === 'production';\n const modifiedFiles = new Set<string>(ids ?? []);\n sourceFileCache.invalidate(modifiedFiles);\n\n if (ids?.length) {\n for (const id of ids || []) {\n fileTransformMap.delete(id);\n }\n }\n\n // Cached include discovery (invalidated only on FS events)\n if (pluginOptions.include.length > 0 && includeCache.length === 0) {\n includeCache = findIncludes();\n }\n\n const resolvedTsConfigPath = resolveTsConfigPath();\n const tsconfigKey = [\n resolvedTsConfigPath,\n isProd ? 'prod' : 'dev',\n isTest ? 'test' : 'app',\n config.build?.lib ? 'lib' : 'nolib',\n pluginOptions.hmr ? 'hmr' : 'nohmr',\n pluginOptions.hasTailwindCss ? 'tw' : 'notw',\n ].join('|');\n let cached = tsconfigOptionsCache.get(tsconfigKey);\n\n if (!cached) {\n const read = compilerCli.readConfiguration(resolvedTsConfigPath, {\n suppressOutputPathCheck: true,\n outDir: undefined,\n sourceMap: false,\n inlineSourceMap: !isProd,\n inlineSources: !isProd,\n declaration: false,\n declarationMap: false,\n allowEmptyCodegenFiles: false,\n annotationsAs: 'decorators',\n enableResourceInlining: false,\n noEmitOnError: false,\n mapRoot: undefined,\n sourceRoot: undefined,\n supportTestBed: false,\n supportJitMode: false,\n });\n cached = { options: read.options, rootNames: read.rootNames };\n tsconfigOptionsCache.set(tsconfigKey, cached);\n }\n\n // Clone options before mutation (preserve cache purity)\n const tsCompilerOptions = { ...cached.options };\n let rootNames = [...cached.rootNames];\n\n if (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (shouldEnableHmr()) {\n tsCompilerOptions['_enableHmr'] = true;\n // Workaround for https://github.com/angular/angular/issues/59310\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (NgtscProgram path)', {\n hmr: pluginOptions.hmr,\n shouldExternalize: shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n // These options can't be false in partial mode\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (angularFullVersion >= 200000) {\n tsCompilerOptions['_enableSelectorless'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n const replacements = pluginOptions.fileReplacements.map((rp) =>\n join(\n pluginOptions.workspaceRoot,\n (rp as FileReplacementSSR).ssr || (rp as FileReplacementWith).with,\n ),\n );\n // Merge + dedupe root names\n rootNames = union(rootNames, includeCache, replacements);\n const hostKey = JSON.stringify(tsCompilerOptions);\n let host: ts.CompilerHost;\n\n if (cachedHost && cachedHostKey === hostKey) {\n host = cachedHost;\n } else {\n host = ts.createIncrementalCompilerHost(tsCompilerOptions, {\n ...ts.sys,\n readFile(path: string, encoding: string) {\n if (fileTransformMap.has(path)) {\n return fileTransformMap.get(path);\n }\n\n const file = ts.sys.readFile.call(null, path, encoding);\n\n if (file) {\n fileTransformMap.set(path, file);\n }\n\n return file;\n },\n });\n cachedHost = host;\n cachedHostKey = hostKey;\n\n // Only store cache if in watch mode\n if (watchMode) {\n augmentHostWithCaching(host, sourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n stylesheetRegistry = externalizeStyles\n ? new AnalogStylesheetRegistry()\n : undefined;\n if (stylesheetRegistry) {\n configureStylePipelineRegistry(\n pluginOptions.stylePipeline,\n stylesheetRegistry,\n {\n workspaceRoot: pluginOptions.workspaceRoot,\n },\n );\n }\n debugStyles('stylesheet registry initialized (NgtscProgram path)', {\n externalizeStyles,\n });\n augmentHostWithResources(host, styleTransform, {\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n isProd,\n stylesheetRegistry,\n sourceFileCache,\n stylePreprocessor: pluginOptions.stylePreprocessor,\n });\n }\n\n /**\n * Creates a new NgtscProgram to analyze/re-analyze\n * the source files and create a file emitter.\n * This is shared between an initial build and a hot update.\n */\n let typeScriptProgram: ts.Program;\n let angularCompiler: NgtscProgram['compiler'];\n const oldBuilder =\n builder ?? ts.readBuilderProgram(tsCompilerOptions, host);\n\n if (!jit) {\n // Create the Angular specific program that contains the Angular compiler\n const angularProgram: NgtscProgram = new compilerCli.NgtscProgram(\n rootNames,\n tsCompilerOptions,\n host,\n nextProgram,\n );\n angularCompiler = angularProgram.compiler;\n typeScriptProgram = angularProgram.compiler.getCurrentProgram();\n augmentProgramWithVersioning(typeScriptProgram);\n\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n typeScriptProgram,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n nextProgram = angularProgram;\n } else {\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n rootNames,\n tsCompilerOptions,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n typeScriptProgram = builder.getProgram();\n }\n\n if (!watchMode) {\n // When not in watch mode, the startup cost of the incremental analysis can be avoided by\n // using an abstract builder that only wraps a TypeScript program.\n builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);\n }\n\n if (angularCompiler!) {\n await angularCompiler.analyzeAsync();\n }\n\n const beforeTransformers = jit\n ? [\n compilerCli.constructorParametersDownlevelTransform(\n builder.getProgram(),\n ),\n createJitResourceTransformer(() =>\n builder.getProgram().getTypeChecker(),\n ),\n ]\n : [];\n\n const transformers = mergeTransformers(\n { before: beforeTransformers },\n jit ? {} : angularCompiler!.prepareEmit().transformers,\n );\n\n const fileMetadata = getFileMetadata(\n builder,\n angularCompiler!,\n pluginOptions.hmr,\n pluginOptions.disableTypeChecking,\n );\n\n const writeFileCallback: ts.WriteFileCallback = (\n _filename,\n content,\n _a,\n _b,\n sourceFiles,\n ) => {\n if (!sourceFiles?.length) {\n return;\n }\n\n const filename = normalizePath(sourceFiles[0].fileName);\n\n if (filename.includes('ngtypecheck.ts') || filename.includes('.d.')) {\n return;\n }\n\n const metadata = watchMode ? fileMetadata(filename) : {};\n\n outputFiles.set(filename, {\n content,\n dependencies: [],\n errors: metadata.errors,\n warnings: metadata.warnings,\n hmrUpdateCode: metadata.hmrUpdateCode,\n hmrEligible: metadata.hmrEligible,\n });\n };\n\n const writeOutputFile = (id: string) => {\n const sourceFile = builder.getSourceFile(id);\n if (!sourceFile) {\n return;\n }\n\n let content = '';\n builder.emit(\n sourceFile,\n (filename, data) => {\n if (/\\.[cm]?js$/.test(filename)) {\n content = data;\n }\n\n if (\n !watchMode &&\n !isTest &&\n /\\.d\\.ts/.test(filename) &&\n !filename.includes('.ngtypecheck.')\n ) {\n // output to library root instead /src\n const declarationPath = resolve(\n config.root,\n config.build.outDir,\n relative(config.root, filename),\n ).replace('/src/', '/');\n\n const declarationFileDir = declarationPath\n .replace(basename(filename), '')\n .replace('/src/', '/');\n\n declarationFiles.push({\n declarationFileDir,\n declarationPath,\n data,\n });\n }\n },\n undefined /* cancellationToken */,\n undefined /* emitOnlyDtsFiles */,\n transformers,\n );\n\n writeFileCallback(id, content, false, undefined, [sourceFile]);\n\n if (angularCompiler) {\n angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);\n }\n };\n\n if (watchMode) {\n if (ids && ids.length > 0) {\n ids.forEach((id) => writeOutputFile(id));\n } else {\n /**\n * Only block the server from starting up\n * during testing.\n */\n if (isTest) {\n // TypeScript will loop until there are no more affected files in the program\n while (\n (\n builder as ts.EmitAndSemanticDiagnosticsBuilderProgram\n ).emitNextAffectedFile(\n writeFileCallback,\n undefined,\n undefined,\n transformers,\n )\n ) {\n /* empty */\n }\n }\n }\n }\n\n if (!isTest) {\n /**\n * Perf: Output files on demand so the dev server\n * isn't blocked when emitting files.\n */\n outputFile = writeOutputFile;\n }\n }\n}\n\nexport function createFsWatcherCacheInvalidator(\n invalidateFsCaches: () => void,\n invalidateTsconfigCaches: () => void,\n performCompilation: () => Promise<void>,\n): () => Promise<void> {\n return async (): Promise<void> => {\n invalidateFsCaches();\n invalidateTsconfigCaches();\n await performCompilation();\n };\n}\n\n/**\n * Convert Analog/Angular CLI-style file replacements into the flat record\n * expected by `AngularHostOptions.fileReplacements`.\n *\n * Only browser replacements (`{ replace, with }`) are converted. SSR-only\n * replacements (`{ replace, ssr }`) are left for the Vite runtime plugin to\n * handle — they should not be baked into the Angular compilation host because\n * that would apply them to both browser and server builds.\n *\n * Relative paths are resolved against `workspaceRoot` so that the host\n * receives the same absolute paths it would get from the Angular CLI.\n */\nexport function toAngularCompilationFileReplacements(\n replacements: FileReplacement[],\n workspaceRoot: string,\n): Record<string, string> | undefined {\n const mappedReplacements = replacements.flatMap((replacement) => {\n // Skip SSR-only entries — they use `ssr` instead of `with`.\n if (!('with' in replacement)) {\n return [];\n }\n\n return [\n [\n isAbsolute(replacement.replace)\n ? replacement.replace\n : resolve(workspaceRoot, replacement.replace),\n isAbsolute(replacement.with)\n ? replacement.with\n : resolve(workspaceRoot, replacement.with),\n ] as const,\n ];\n });\n\n return mappedReplacements.length\n ? Object.fromEntries(mappedReplacements)\n : undefined;\n}\n\n/**\n * Map Angular's `templateUpdates` (keyed by `encodedFilePath@ClassName`)\n * back to absolute file paths with their associated HMR code and component\n * class name.\n *\n * Angular's private Compilation API emits template update keys in the form\n * `encodeURIComponent(relativePath + '@' + className)`. We decode and resolve\n * them so the caller can look up updates by the same normalized absolute path\n * used elsewhere in the plugin (`outputFiles`, `classNames`, etc.).\n */\nexport function mapTemplateUpdatesToFiles(\n templateUpdates: ReadonlyMap<string, string> | undefined,\n): Map<\n string,\n {\n className: string;\n code: string;\n }\n> {\n const updatesByFile = new Map<string, { className: string; code: string }>();\n\n templateUpdates?.forEach((code, encodedUpdateId) => {\n const [file, className = ''] =\n decodeURIComponent(encodedUpdateId).split('@');\n const resolvedFile = normalizePath(resolve(process.cwd(), file));\n\n updatesByFile.set(resolvedFile, {\n className,\n code,\n });\n });\n\n return updatesByFile;\n}\n\n/**\n * Returns every live Vite module that can legitimately represent a changed\n * Angular resource file.\n *\n * For normal files, `getModulesByFile()` is enough. For Angular component\n * stylesheets, it is not: the browser often holds virtual hashed requests\n * (`/abc123.css?direct&ngcomp=...` and `/abc123.css?ngcomp=...`) that are no\n * longer discoverable from the original source path alone. We therefore merge:\n * - watcher event modules\n * - module-graph modules by source file\n * - registry-tracked live request ids resolved back through the module graph\n */\nexport async function getModulesForChangedFile(\n server: ViteDevServer,\n file: string,\n eventModules: readonly ModuleNode[] = [],\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): Promise<ModuleNode[]> {\n const normalizedFile = normalizePath(file.split('?')[0]);\n const modules = new Map<string, ModuleNode>();\n\n for (const mod of eventModules) {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n }\n\n server.moduleGraph.getModulesByFile(normalizedFile)?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n\n const stylesheetRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(normalizedFile) ?? [];\n const requestIdHits: Array<{\n requestId: string;\n candidate: string;\n via: 'url' | 'id';\n moduleId?: string;\n }> = [];\n for (const requestId of stylesheetRequestIds) {\n const candidates = [\n requestId,\n requestId.startsWith('/') ? requestId : `/${requestId}`,\n ];\n\n for (const candidate of candidates) {\n // `getModuleByUrl()` is the important lookup here. Angular's wrapper\n // module is served by URL and can be absent from a straight `getModuleById`\n // lookup during CSS HMR, even though it is the browser-visible module\n // that must be refreshed. We keep `getModuleById()` as a compatibility\n // fallback for the simpler direct CSS case.\n const mod =\n (await server.moduleGraph.getModuleByUrl(candidate)) ??\n server.moduleGraph.getModuleById(candidate);\n requestIdHits.push({\n requestId,\n candidate,\n via: mod?.url === candidate ? 'url' : 'id',\n moduleId: mod?.id,\n });\n if (mod?.id) {\n modules.set(mod.id, mod);\n }\n }\n }\n\n debugHmrV('getModulesForChangedFile registry lookup', {\n file: normalizedFile,\n stylesheetRequestIds,\n requestIdHits,\n resolvedModuleIds: [...modules.keys()],\n });\n\n return [...modules.values()];\n}\n\nexport function isModuleForChangedResource(\n mod: ModuleNode,\n changedFile: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): boolean {\n const normalizedChangedFile = normalizePath(changedFile.split('?')[0]);\n\n if (normalizePath((mod.file ?? '').split('?')[0]) === normalizedChangedFile) {\n return true;\n }\n\n if (!mod.id) {\n return false;\n }\n\n // Virtual Angular stylesheet modules do not report the original source file\n // as `mod.file`; they point at the served hashed stylesheet asset instead.\n // Recover the source file through the stylesheet registry so HMR can still\n // answer \"does this live module belong to the resource that just changed?\"\n const requestPath = getFilenameFromPath(mod.id);\n const sourcePath =\n stylesheetRegistry?.resolveExternalSource(requestPath) ??\n stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\\//, ''));\n\n return (\n normalizePath((sourcePath ?? '').split('?')[0]) === normalizedChangedFile\n );\n}\n\nfunction describeStylesheetContent(code: string): {\n length: number;\n digest: string;\n preview: string;\n} {\n return {\n length: code.length,\n digest: createHash('sha256').update(code).digest('hex').slice(0, 12),\n preview: code.replace(/\\s+/g, ' ').trim().slice(0, 160),\n };\n}\n\nfunction safeStatMtimeMs(file: string): number | undefined {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Refreshes any already-served stylesheet records that map back to a changed\n * source file.\n *\n * This is the critical bridge for externalized Angular component styles during\n * HMR. Angular's resource watcher can notice that `/src/...component.css`\n * changed before Angular recompilation has had a chance to repopulate the\n * stylesheet registry. If we emit a CSS update against the existing virtual\n * stylesheet id without first refreshing the registry content, the browser gets\n * a hot update containing stale CSS. By rewriting the existing served records\n * from disk up front, HMR always pushes the latest source content.\n */\nexport function refreshStylesheetRegistryForFile(\n file: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n stylePreprocessor?: StylePreprocessor,\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n if (!stylesheetRegistry || !existsSync(normalizedFile)) {\n return;\n }\n\n const publicIds = stylesheetRegistry.getPublicIdsForSource(normalizedFile);\n if (publicIds.length === 0) {\n return;\n }\n\n const rawCss = readFileSync(normalizedFile, 'utf-8');\n const preprocessed = preprocessStylesheetResult(\n rawCss,\n normalizedFile,\n stylePreprocessor,\n );\n const servedCss = rewriteRelativeCssImports(\n preprocessed.code,\n normalizedFile,\n );\n\n for (const publicId of publicIds) {\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId,\n sourcePath: normalizedFile,\n originalCode: rawCss,\n normalizedCode: servedCss,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n },\n [\n normalizedFile,\n normalizePath(normalizedFile),\n basename(normalizedFile),\n normalizedFile.replace(/^\\//, ''),\n ],\n );\n }\n\n debugStylesV('stylesheet registry refreshed from source file', {\n file: normalizedFile,\n publicIds,\n dependencies: preprocessed.dependencies,\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n source: describeStylesheetContent(rawCss),\n served: describeStylesheetContent(servedCss),\n });\n}\n\nfunction diagnoseComponentStylesheetPipeline(\n changedFile: string,\n directModule: ModuleNode,\n stylesheetRegistry: AnalogStylesheetRegistry | undefined,\n wrapperModules: ModuleNode[],\n stylePreprocessor?: StylePreprocessor,\n): {\n file: string;\n sourcePath?: string;\n source?: ReturnType<typeof describeStylesheetContent>;\n registry?: ReturnType<typeof describeStylesheetContent>;\n dependencies: StylesheetDependency[];\n diagnostics: ReturnType<AnalogStylesheetRegistry['getDiagnosticsForSource']>;\n tags: string[];\n directModuleId?: string;\n directModuleUrl?: string;\n trackedRequestIds: string[];\n wrapperCount: number;\n anomalies: string[];\n hints: string[];\n} {\n const normalizedFile = normalizePath(changedFile.split('?')[0]);\n const sourceExists = existsSync(normalizedFile);\n const sourceCode = sourceExists\n ? readFileSync(normalizedFile, 'utf-8')\n : undefined;\n\n const directRequestPath = directModule.id\n ? getFilenameFromPath(directModule.id)\n : undefined;\n const sourcePath = directRequestPath\n ? (stylesheetRegistry?.resolveExternalSource(directRequestPath) ??\n stylesheetRegistry?.resolveExternalSource(\n directRequestPath.replace(/^\\//, ''),\n ))\n : normalizedFile;\n const registryCode = directRequestPath\n ? stylesheetRegistry?.getServedContent(directRequestPath)\n : undefined;\n const trackedRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? '') ?? [];\n const dependencies =\n stylesheetRegistry?.getDependenciesForSource(sourcePath ?? '') ?? [];\n const diagnostics =\n stylesheetRegistry?.getDiagnosticsForSource(sourcePath ?? '') ?? [];\n const tags = stylesheetRegistry?.getTagsForSource(sourcePath ?? '') ?? [];\n\n const anomalies: string[] = [];\n const hints: string[] = [];\n\n if (!sourceExists) {\n anomalies.push('source_file_missing');\n hints.push(\n 'The stylesheet watcher fired for a file that no longer exists on disk.',\n );\n }\n\n if (!registryCode) {\n anomalies.push('registry_content_missing');\n hints.push(\n 'The stylesheet registry has no served content for the direct module request path.',\n );\n }\n\n if (sourceCode && registryCode) {\n // Compare against the same served representation that the registry stores,\n // not the raw file on disk. Analog intentionally prepends `@reference`\n // and rewrites relative imports before the stylesheet reaches Vite, so a\n // raw-source hash comparison would flag a false positive on every healthy\n // update.\n let expectedRegistryCode = preprocessStylesheet(\n sourceCode,\n normalizedFile,\n stylePreprocessor,\n );\n expectedRegistryCode = rewriteRelativeCssImports(\n expectedRegistryCode,\n normalizedFile,\n );\n const sourceDigest = describeStylesheetContent(expectedRegistryCode).digest;\n const registryDigest = describeStylesheetContent(registryCode).digest;\n if (sourceDigest !== registryDigest) {\n anomalies.push('source_registry_mismatch');\n hints.push(\n 'The source file changed, but the served stylesheet content in the registry is still stale.',\n );\n }\n }\n\n if (trackedRequestIds.length === 0) {\n anomalies.push('no_tracked_requests');\n hints.push(\n 'No live stylesheet requests are tracked for this source file, so HMR has no browser-facing target.',\n );\n }\n\n if (\n trackedRequestIds.some((id) => id.includes('?ngcomp=')) &&\n wrapperModules.length === 0\n ) {\n anomalies.push('tracked_wrapper_missing_from_module_graph');\n hints.push(\n 'A wrapper request id is known, but Vite did not expose a live wrapper module during this HMR pass.',\n );\n }\n\n if (\n trackedRequestIds.every((id) => !id.includes('?ngcomp=')) &&\n wrapperModules.length === 0\n ) {\n anomalies.push('wrapper_not_yet_tracked');\n hints.push(\n 'Only direct stylesheet requests were tracked during this HMR pass; the wrapper request may be appearing too late.',\n );\n }\n\n return {\n file: changedFile,\n sourcePath,\n source: sourceCode\n ? describeStylesheetContent(\n rewriteRelativeCssImports(\n preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor),\n normalizedFile,\n ),\n )\n : undefined,\n registry: registryCode\n ? describeStylesheetContent(registryCode)\n : undefined,\n dependencies,\n diagnostics,\n tags,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n trackedRequestIds,\n wrapperCount: wrapperModules.length,\n anomalies,\n hints,\n };\n}\n\nexport async function findComponentStylesheetWrapperModules(\n server: ViteDevServer,\n changedFile: string,\n directModule: ModuleNode,\n fileModules: ModuleNode[],\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): Promise<ModuleNode[]> {\n const wrapperModules = new Map<string, ModuleNode>();\n\n // Fast path: if the wrapper JS module is already present in the resolved\n // fileModules set for this HMR cycle, use it directly.\n for (const mod of fileModules) {\n if (\n mod.id &&\n mod.type === 'js' &&\n isComponentStyleSheet(mod.id) &&\n isModuleForChangedResource(mod, changedFile, stylesheetRegistry)\n ) {\n wrapperModules.set(mod.id, mod);\n }\n }\n\n const directRequestIds = new Set<string>();\n if (directModule.id) {\n directRequestIds.add(directModule.id);\n }\n if (directModule.url) {\n directRequestIds.add(directModule.url);\n }\n\n const requestPath = directModule.id\n ? getFilenameFromPath(directModule.id)\n : undefined;\n const sourcePath = requestPath\n ? (stylesheetRegistry?.resolveExternalSource(requestPath) ??\n stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\\//, '')))\n : undefined;\n\n // HMR timing matters here. On a pure CSS edit, the browser often already has\n // the `?ngcomp=...` wrapper module loaded, but the registry may only know\n // about the `?direct&ngcomp=...` request at the moment the file watcher\n // fires. Pull in any already-tracked wrapper ids for the same source file,\n // then derive wrapper candidates from the known direct request ids.\n for (const requestId of stylesheetRegistry?.getRequestIdsForSource(\n sourcePath ?? '',\n ) ?? []) {\n if (requestId.includes('?ngcomp=')) {\n directRequestIds.add(requestId);\n }\n }\n\n const candidateWrapperIds = [...directRequestIds]\n .filter((id) => id.includes('?direct&ngcomp='))\n .map((id) => id.replace('?direct&ngcomp=', '?ngcomp='));\n\n const lookupHits: Array<{\n candidate: string;\n via?: 'url' | 'id';\n moduleId?: string;\n moduleType?: string;\n }> = [];\n\n for (const candidate of candidateWrapperIds) {\n // Wrapper modules are served by URL and can be absent from a straight\n // module-id lookup during HMR. Prefer URL resolution first, then fall back\n // to id lookup for compatibility with simpler module graph states.\n const mod =\n (await server.moduleGraph.getModuleByUrl(candidate)) ??\n server.moduleGraph.getModuleById(candidate);\n lookupHits.push({\n candidate,\n via: mod?.url === candidate ? 'url' : mod ? 'id' : undefined,\n moduleId: mod?.id,\n moduleType: mod?.type,\n });\n if (\n mod?.id &&\n mod.type === 'js' &&\n isComponentStyleSheet(mod.id) &&\n isModuleForChangedResource(mod, changedFile, stylesheetRegistry)\n ) {\n wrapperModules.set(mod.id, mod);\n }\n }\n\n debugHmrV('component stylesheet wrapper lookup', {\n file: changedFile,\n sourcePath,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n candidateWrapperIds,\n lookupHits,\n });\n\n if (wrapperModules.size === 0) {\n debugHmrV('component stylesheet wrapper lookup empty', {\n file: changedFile,\n sourcePath,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n candidateWrapperIds,\n });\n }\n\n return [...wrapperModules.values()];\n}\n\nfunction 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\n classNames.delete(id);\n}\n\nfunction sendCssUpdate(\n server: ViteDevServer,\n update: {\n path: string;\n acceptedPath: string;\n },\n) {\n const timestamp = Date.now();\n debugHmrV('ws send: css-update', {\n ...update,\n timestamp,\n });\n server.ws.send({\n type: 'update',\n updates: [\n {\n type: 'css-update',\n timestamp,\n path: update.path,\n acceptedPath: update.acceptedPath,\n },\n ],\n });\n}\n\nfunction sendFullReload(\n server: ViteDevServer,\n details: Record<string, unknown>,\n) {\n debugHmrV('ws send: full-reload', details);\n server.ws.send('analog:debug-full-reload', details);\n server.ws.send({ type: 'full-reload' });\n}\n\nfunction resolveComponentClassNamesForStyleOwner(\n ownerFile: string,\n sourcePath: string,\n): string[] {\n if (!existsSync(ownerFile)) {\n return [];\n }\n\n const ownerCode = readFileSync(ownerFile, 'utf-8');\n const components = getAngularComponentMetadata(ownerCode);\n const normalizedSourcePath = normalizePath(sourcePath);\n\n return components\n .filter((component) =>\n component.styleUrls.some(\n (styleUrl) =>\n normalizePath(resolve(dirname(ownerFile), styleUrl)) ===\n normalizedSourcePath,\n ),\n )\n .map((component) => component.className);\n}\n\ninterface TemplateClassBindingIssue {\n line: number;\n column: number;\n snippet: string;\n}\n\ninterface ActiveGraphComponentRecord {\n file: string;\n className: string;\n selector?: string;\n}\n\ninterface StyleOwnerRecord {\n sourcePath: string;\n ownerFile: string;\n}\n\ntype ComponentStylesheetHmrOutcome =\n | 'css-update'\n | 'owner-component-update'\n | 'full-reload';\n\nexport function findStaticClassAndBoundClassConflicts(\n template: string,\n): TemplateClassBindingIssue[] {\n const issues: TemplateClassBindingIssue[] = [];\n\n for (const { index, snippet } of findOpeningTagSnippets(template)) {\n if (!snippet.includes('[class]')) {\n continue;\n }\n\n const hasStaticClass = /\\sclass\\s*=\\s*(['\"])(?:(?!\\1)[\\s\\S])*\\1/.test(\n snippet,\n );\n const hasBoundClass = /\\s\\[class\\]\\s*=\\s*(['\"])(?:(?!\\1)[\\s\\S])*\\1/.test(\n snippet,\n );\n\n if (hasStaticClass && hasBoundClass) {\n const prefix = template.slice(0, index);\n const line = prefix.split('\\n').length;\n const lastNewline = prefix.lastIndexOf('\\n');\n const column = index - lastNewline;\n issues.push({\n line,\n column,\n snippet: snippet.replace(/\\s+/g, ' ').trim(),\n });\n }\n }\n\n return issues;\n}\n\nfunction throwTemplateClassBindingConflict(\n id: string,\n issue: TemplateClassBindingIssue,\n): never {\n throw new Error(\n [\n '[Analog Angular] Invalid template class binding.',\n `File: ${id}:${issue.line}:${issue.column}`,\n 'The same element uses both a static `class=\"...\"` attribute and a whole-element `[class]=\"...\"` binding.',\n 'That pattern can replace or conflict with static Tailwind classes, which makes styles appear to stop applying.',\n 'Use `[ngClass]` or explicit `[class.foo]` bindings instead of `[class]` when the element also has static classes.',\n `Snippet: ${issue.snippet}`,\n ].join('\\n'),\n );\n}\n\nexport function findBoundClassAndNgClassConflicts(\n template: string,\n): TemplateClassBindingIssue[] {\n const issues: TemplateClassBindingIssue[] = [];\n const hasWholeElementClassBinding = /\\[class\\]\\s*=/.test(template);\n\n if (!hasWholeElementClassBinding || !template.includes('[ngClass]')) {\n return issues;\n }\n\n for (const { index, snippet } of findOpeningTagSnippets(template)) {\n if (!/\\[class\\]\\s*=/.test(snippet) || !snippet.includes('[ngClass]')) {\n continue;\n }\n\n const prefix = template.slice(0, index);\n const line = prefix.split('\\n').length;\n const lastNewline = prefix.lastIndexOf('\\n');\n const column = index - lastNewline;\n issues.push({\n line,\n column,\n snippet: snippet.replace(/\\s+/g, ' ').trim(),\n });\n }\n\n return issues;\n}\n\nfunction findOpeningTagSnippets(\n template: string,\n): Array<{ index: number; snippet: string }> {\n const matches: Array<{ index: number; snippet: string }> = [];\n\n for (let index = 0; index < template.length; index++) {\n if (template[index] !== '<') {\n continue;\n }\n\n const tagStart = template[index + 1];\n if (!tagStart || !/[a-zA-Z]/.test(tagStart)) {\n continue;\n }\n\n let quote: '\"' | \"'\" | null = null;\n\n for (let end = index + 1; end < template.length; end++) {\n const char = template[end];\n\n if (quote) {\n if (char === quote) {\n quote = null;\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n\n if (char === '>') {\n matches.push({\n index,\n snippet: template.slice(index, end + 1),\n });\n index = end;\n break;\n }\n }\n }\n\n return matches;\n}\n\nfunction formatActiveGraphLocations(entries: Iterable<string>): string {\n return [...entries]\n .sort()\n .map((entry) => `- ${entry}`)\n .join('\\n');\n}\n\nfunction logComponentStylesheetHmrOutcome(details: {\n file: string;\n encapsulation: string;\n diagnosis: ReturnType<typeof diagnoseComponentStylesheetPipeline>;\n outcome: ComponentStylesheetHmrOutcome;\n directModuleId?: string;\n wrapperIds?: string[];\n ownerIds?: Array<string | undefined>;\n updateIds?: string[];\n}) {\n const pitfalls: string[] = [];\n const rejectedPreferredPaths: string[] = [];\n const hints: string[] = [];\n\n if (details.encapsulation === 'shadow') {\n pitfalls.push('shadow-encapsulation');\n rejectedPreferredPaths.push('css-update');\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'Shadow DOM styles cannot rely on Vite CSS patching because Angular applies them inside a shadow root.',\n );\n }\n\n if (details.diagnosis.anomalies.includes('wrapper_not_yet_tracked')) {\n pitfalls.push('wrapper-not-yet-tracked');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'The direct stylesheet module exists, but the browser-visible Angular wrapper module was not available in the live graph during this HMR pass.',\n );\n }\n\n if (\n details.diagnosis.anomalies.includes(\n 'tracked_wrapper_missing_from_module_graph',\n )\n ) {\n pitfalls.push('tracked-wrapper-missing-from-module-graph');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'A wrapper request id is known, but Vite could not resolve a live wrapper module for targeted CSS HMR.',\n );\n }\n\n if ((details.ownerIds?.filter(Boolean).length ?? 0) === 0) {\n pitfalls.push('no-owner-modules');\n if (details.outcome === 'full-reload') {\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'No owning TS component modules were available in the module graph for owner-based fallback.',\n );\n }\n } else if ((details.updateIds?.length ?? 0) === 0) {\n pitfalls.push('owner-modules-without-class-identities');\n if (details.outcome === 'full-reload') {\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'Owner modules were found, but Angular did not expose component class identities after recompilation, so no targeted component update could be sent.',\n );\n }\n }\n\n debugHmrV('component stylesheet hmr outcome', {\n file: details.file,\n outcome: details.outcome,\n encapsulation: details.encapsulation,\n directModuleId: details.directModuleId,\n wrapperIds: details.wrapperIds ?? [],\n ownerIds: details.ownerIds ?? [],\n updateIds: details.updateIds ?? [],\n preferredPath:\n details.encapsulation === 'shadow' ? 'full-reload' : 'css-update',\n rejectedPreferredPaths: [...new Set(rejectedPreferredPaths)],\n pitfalls: [...new Set(pitfalls)],\n anomalies: details.diagnosis.anomalies,\n hints: [...new Set([...details.diagnosis.hints, ...hints])],\n });\n}\n\nexport function findTemplateOwnerModules(\n server: ViteDevServer,\n resourceFile: string,\n): ModuleNode[] {\n const normalizedResourceFile = normalizePath(resourceFile.split('?')[0]);\n const candidateTsFiles = [\n normalizedResourceFile.replace(/\\.(html|htm)$/i, '.ts'),\n ];\n\n const modules = new Map<string, ModuleNode>();\n for (const candidate of candidateTsFiles) {\n const owners = server.moduleGraph.getModulesByFile(candidate);\n owners?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n }\n\n return [...modules.values()];\n}\n\nfunction findStyleOwnerModules(\n server: ViteDevServer,\n resourceFile: string,\n styleSourceOwners: Map<string, Set<string>>,\n): ModuleNode[] {\n const normalizedResourceFile = normalizePath(resourceFile.split('?')[0]);\n const candidateOwnerFiles = [\n ...(styleSourceOwners.get(normalizedResourceFile) ?? []),\n ];\n const modules = new Map<string, ModuleNode>();\n\n for (const ownerFile of candidateOwnerFiles) {\n const owners = server.moduleGraph.getModulesByFile(ownerFile);\n owners?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n }\n\n return [...modules.values()];\n}\n\nexport function getFileMetadata(\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n hmrEnabled?: boolean,\n disableTypeChecking?: boolean,\n) {\n const ts = require('typescript');\n return (\n file: string,\n ): {\n errors?: string[];\n warnings?: (string | ts.DiagnosticMessageChain)[];\n hmrUpdateCode?: string | null;\n hmrEligible?: boolean;\n } => {\n const sourceFile = program.getSourceFile(file);\n if (!sourceFile) {\n return {};\n }\n\n const diagnostics = getDiagnosticsForSourceFile(\n sourceFile,\n !!disableTypeChecking,\n program,\n angularCompiler,\n );\n\n const errors = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Error)\n .map((d) =>\n typeof d.messageText === 'object'\n ? d.messageText.messageText\n : d.messageText,\n );\n\n const warnings = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Warning)\n .map((d) => d.messageText);\n\n let hmrUpdateCode: string | null | undefined = undefined;\n\n let hmrEligible = false;\n if (hmrEnabled) {\n for (const node of sourceFile.statements) {\n if (ts.isClassDeclaration(node) && (node as any).name != null) {\n hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node as any);\n if (hmrUpdateCode) {\n const className = (node as any).name.getText();\n classNames.set(file, className);\n hmrEligible = true;\n debugHmr('NgtscProgram emitHmrUpdateModule', { file, className });\n }\n }\n }\n }\n\n return { errors, warnings, hmrUpdateCode, hmrEligible };\n };\n}\n\nfunction getDiagnosticsForSourceFile(\n sourceFile: ts.SourceFile,\n disableTypeChecking: boolean,\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n) {\n const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);\n\n if (disableTypeChecking) {\n // Syntax errors are cheap to compute and the app will not run if there are any\n // So always show these types of errors regardless if type checking is disabled\n return syntacticDiagnostics;\n }\n\n const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);\n const angularDiagnostics = angularCompiler\n ? angularCompiler.getDiagnosticsForFile(sourceFile, 1)\n : [];\n return [\n ...syntacticDiagnostics,\n ...semanticDiagnostics,\n ...angularDiagnostics,\n ];\n}\n\nfunction markModuleSelfAccepting(mod: ModuleNode): ModuleNode {\n // support Vite 6\n if ('_clientModule' in mod) {\n (mod as any)['_clientModule'].isSelfAccepting = true;\n }\n\n return {\n ...mod,\n isSelfAccepting: true,\n } as ModuleNode;\n}\n\nfunction isComponentStyleSheet(id: string): boolean {\n return id.includes('ngcomp=');\n}\n\nfunction getComponentStyleSheetMeta(id: string): {\n componentId: string;\n encapsulation: 'emulated' | 'shadow' | 'none';\n} {\n const params = new URL(id, 'http://localhost').searchParams;\n const encapsulationMapping = {\n '0': 'emulated',\n '2': 'none',\n '3': 'shadow',\n };\n return {\n componentId: params.get('ngcomp')!,\n encapsulation: encapsulationMapping[\n params.get('e') as keyof typeof encapsulationMapping\n ] as 'emulated' | 'shadow' | 'none',\n };\n}\n\n/**\n * Removes leading / and query string from a url path\n * e.g. /foo.scss?direct&ngcomp=ng-c3153525609&e=0 returns foo.scss\n * @param id\n */\nfunction getFilenameFromPath(id: string): string {\n try {\n return new URL(id, 'http://localhost').pathname.replace(/^\\//, '');\n } catch {\n // Defensive fallback: if the ID cannot be parsed as a URL (e.g., it\n // contains characters that are invalid in URLs but valid in file paths\n // on some platforms), strip the query string manually.\n const queryIndex = id.indexOf('?');\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id;\n return pathname.replace(/^\\//, '');\n }\n}\n\n/**\n * Checks for vitest run from the command line\n * @returns boolean\n */\nexport function isTestWatchMode(args: string[] = process.argv): boolean {\n // vitest --run\n const hasRun = args.find((arg) => arg.includes('--run'));\n if (hasRun) {\n return false;\n }\n\n // vitest --no-run\n const hasNoRun = args.find((arg) => arg.includes('--no-run'));\n if (hasNoRun) {\n return true;\n }\n\n // check for --watch=false or --no-watch\n const hasWatch = args.find((arg) => arg.includes('watch'));\n if (hasWatch && ['false', 'no'].some((neg) => hasWatch.includes(neg))) {\n return false;\n }\n\n // check for --watch false\n const watchIndex = args.findIndex((arg) => arg.includes('watch'));\n const watchArg = args[watchIndex + 1];\n if (watchArg && watchArg === 'false') {\n return false;\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,IAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AA0B9C,IAAY,kBAAL,yBAAA,iBAAA;AACL,iBAAA,gBAAA,UAAA,KAAA;AACA,iBAAA,gBAAA,YAAA,KAAA;AACA,iBAAA,gBAAA,eAAA,KAAA;AACA,iBAAA,gBAAA,cAAA,KAAA;AACA,iBAAA,gBAAA,SAAA,KAAA;;KACD;AAsID,SAAgB,qBACd,eACA,MACQ;CACR,MAAM,0BAA0B,cAAc,QAAQ,cAAc,CAAC;CACrE,MAAM,iBAAiB,cAAc,KAAK;AAE1C,KACE,mBAAmB,2BACnB,eAAe,WAAW,GAAG,wBAAwB,GAAG,CAExD,QAAO;AAGT,KAAI,eAAe,WAAW,IAAI,CAChC,QAAO,GAAG,0BAA0B;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