@analogjs/vite-plugin-angular 3.0.0 → 3.0.1-beta.2

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":"component-styles-plugin.js","names":[],"sources":["../../../src/lib/component-styles-plugin.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { union } from 'es-toolkit';\nimport {\n normalizePath,\n type ModuleNode,\n type Plugin,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n ensureAngularBuildContext,\n getFilenameFromPath,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport {\n getComponentStyleSheetMeta,\n isComponentStyleSheet,\n} from './encapsulation-plugin.js';\nimport type {\n StylePreprocessor,\n StylesheetDependency,\n} from './style-preprocessor.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheet,\n rewriteRelativeCssImports,\n} from './stylesheet-registry.js';\nimport { describeStylesheetContent } from './utils/compilation-shared.js';\nimport { debugHmr, debugHmrV, debugStylesV } from './utils/debug.js';\n\nexport interface ComponentStylesheetPipelineDiagnosis {\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\n/**\n * Self-contained Vite plugin that resolves and serves externalized Angular\n * component stylesheets (`?ngcomp=...`) from the shared `AngularBuildContext`\n * stylesheet registry and refreshes served records on source CSS edits.\n */\nexport function componentStylesPlugin(\n ctxOrOptions?: AngularBuildContext | AngularBuildContextOptions,\n): Plugin {\n const ctx = ensureAngularBuildContext(ctxOrOptions);\n\n return {\n name: '@analogjs/vite-plugin-angular:component-styles',\n enforce: 'pre',\n async configResolved(config) {\n await ctx.resolveConfig(config);\n },\n resolveId(id) {\n return ctx.styles.resolveComponentStyleId(id);\n },\n load(id) {\n return ctx.styles.loadComponentStyle(id);\n },\n handleHotUpdate(hmrCtx) {\n if (/\\.(css|less|sass|scss)$/.test(hmrCtx.file)) {\n debugHmr('stylesheet file changed', { file: hmrCtx.file });\n ctx.styles.refreshForFile(hmrCtx.file);\n }\n return undefined;\n },\n };\n}\n\nexport function markModuleSelfAccepting(mod: ModuleNode): ModuleNode {\n // support Vite 6\n if ('_clientModule' in mod) {\n (mod as unknown as { _clientModule: { isSelfAccepting: boolean } })[\n '_clientModule'\n ].isSelfAccepting = true;\n }\n\n return {\n ...mod,\n isSelfAccepting: true,\n } as ModuleNode;\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 ?? undefined,\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 stylesheetRegistry?.getServedSourcePath(requestPath) ??\n stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\\//, ''));\n\n return (\n normalizePath((sourcePath ?? '').split('?')[0]) === normalizedChangedFile\n );\n}\n\nfunction resolveDirectStylesheetSourcePath(\n normalizedFile: string,\n directModule: ModuleNode,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): { directRequestPath?: string; sourcePath: string | undefined } {\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 stylesheetRegistry?.getServedSourcePath(directRequestPath) ??\n stylesheetRegistry?.getServedSourcePath(\n directRequestPath.replace(/^\\//, ''),\n ))\n : normalizedFile;\n\n return { directRequestPath, sourcePath };\n}\n\nexport function diagnoseComponentStylesheetPipeline(\n changedFile: string,\n directModule: ModuleNode,\n stylesheetRegistry: AnalogStylesheetRegistry | undefined,\n wrapperModules: ModuleNode[],\n stylePreprocessor?: StylePreprocessor,\n): ComponentStylesheetPipelineDiagnosis {\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, sourcePath } = resolveDirectStylesheetSourcePath(\n normalizedFile,\n directModule,\n stylesheetRegistry,\n );\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 const registryDescription = registryCode\n ? describeStylesheetContent(registryCode)\n : undefined;\n let sourceDescription:\n | ReturnType<typeof describeStylesheetContent>\n | undefined;\n\n if (sourceCode !== undefined) {\n try {\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 sourceDescription = describeStylesheetContent(expectedRegistryCode);\n } catch {\n anomalies.push('source_preprocess_failed');\n hints.push(\n 'Diagnostic preprocessing of the source stylesheet failed; falling back to raw source summary.',\n );\n sourceDescription = describeStylesheetContent(sourceCode);\n }\n }\n\n if (\n sourceDescription &&\n registryDescription &&\n !anomalies.includes('source_preprocess_failed') &&\n sourceDescription.digest !== registryDescription.digest\n ) {\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 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: sourceDescription,\n registry: registryDescription,\n dependencies,\n diagnostics,\n tags,\n directModuleId: directModule.id ?? undefined,\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(\n requestPath.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(requestPath) ??\n stylesheetRegistry?.getServedSourcePath(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 ?? undefined,\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\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 sendCssUpdate(\n server: ViteDevServer,\n update: {\n path: string;\n acceptedPath: string;\n },\n): void {\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): void {\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\ntype ComponentStylesheetHmrOutcome = 'css-update' | 'full-reload';\n\nfunction logComponentStylesheetHmrOutcome(details: {\n file: string;\n encapsulation: string | undefined;\n diagnosis: ComponentStylesheetPipelineDiagnosis;\n outcome: ComponentStylesheetHmrOutcome;\n directModuleId?: string;\n wrapperIds?: string[];\n}): void {\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 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 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 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 async function handleDirectComponentStyleHmr(options: {\n server: ViteDevServer;\n file: string;\n directModule: ModuleNode;\n fileModules: ModuleNode[];\n stylesheetRegistry?: AnalogStylesheetRegistry;\n stylePreprocessor?: StylePreprocessor;\n}): Promise<ModuleNode[]> {\n const {\n server,\n file,\n directModule,\n fileModules,\n stylesheetRegistry,\n stylePreprocessor,\n } = options;\n const { encapsulation } = getComponentStyleSheetMeta(directModule.id!);\n\n // Angular exposes one component stylesheet through two module shapes:\n // 1. a `?direct&ngcomp=...` CSS module that Vite can patch with a normal `css-update`\n // 2. a `?ngcomp=...` JS wrapper module that embeds `__vite__css` for Angular's runtime\n //\n // Value: invalidate the browser-visible wrapper before patching the direct CSS\n // module so Angular re-evaluates the same live wrapper it is actually using.\n const wrapperModules = await findComponentStylesheetWrapperModules(\n server,\n file,\n directModule,\n fileModules,\n stylesheetRegistry,\n );\n const normalizedFile = normalizePath(file.split('?')[0]);\n const { sourcePath } = resolveDirectStylesheetSourcePath(\n normalizedFile,\n directModule,\n stylesheetRegistry,\n );\n const trackedRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? '') ?? [];\n\n let stylesheetDiagnosis: ComponentStylesheetPipelineDiagnosis | undefined;\n if (debugHmrV.enabled) {\n try {\n stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(\n file,\n directModule,\n stylesheetRegistry,\n wrapperModules,\n stylePreprocessor,\n );\n } catch (error) {\n debugHmrV('component stylesheet pipeline diagnosis failed', {\n file,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n debugStylesV('HMR: component stylesheet changed', {\n file: directModule.file,\n encapsulation,\n });\n debugHmrV('component stylesheet wrapper modules', {\n file,\n wrapperCount: wrapperModules.length,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n availableModuleIds: fileModules.map((mod) => mod.id),\n });\n if (stylesheetDiagnosis) {\n debugHmrV('component stylesheet pipeline diagnosis', stylesheetDiagnosis);\n }\n\n // Drop Vite's cached direct-module transform before wrapper lookup and patching continue.\n server.moduleGraph.invalidateModule(directModule);\n debugHmrV('component stylesheet direct module invalidated', {\n file,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n reason:\n 'Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues.',\n });\n\n // CSS-only HMR is safe only when the browser-visible wrapper is known and the\n // component is not using Shadow DOM.\n const trackedWrapperRequestIds = trackedRequestIds.filter((id) =>\n id.includes('?ngcomp='),\n );\n const canUseCssUpdate =\n encapsulation !== 'shadow' &&\n (wrapperModules.length > 0 || trackedWrapperRequestIds.length > 0);\n\n if (canUseCssUpdate) {\n wrapperModules.forEach((mod) => server.moduleGraph.invalidateModule(mod));\n debugHmrV('sending css-update for component stylesheet', {\n file,\n path: directModule.url,\n acceptedPath: directModule.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(server, {\n path: directModule.url,\n acceptedPath: directModule.file!,\n });\n if (stylesheetDiagnosis) {\n logComponentStylesheetHmrOutcome({\n file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'css-update',\n directModuleId: directModule.id ?? undefined,\n wrapperIds: wrapperModules\n .map((mod) => mod.id)\n .filter((id): id is string => id !== null),\n });\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\n return mod.file !== file || mod.id !== directModule.id;\n })\n .map((mod) => {\n if (mod.file === file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n }) as ModuleNode[],\n wrapperModules.map((mod) => markModuleSelfAccepting(mod)),\n );\n }\n\n // If the browser-visible `?ngcomp=...` wrapper cannot be trusted, prefer\n // correctness over a partial patch and reload.\n debugHmrV('component stylesheet hmr fallback: full reload', {\n 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: directModule.id,\n trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(file) ?? [],\n });\n if (stylesheetDiagnosis) {\n logComponentStylesheetHmrOutcome({\n file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'full-reload',\n directModuleId: directModule.id ?? undefined,\n wrapperIds: wrapperModules\n .map((mod) => mod.id)\n .filter((id): id is string => id !== null),\n });\n }\n sendFullReload(server, {\n file,\n encapsulation,\n reason:\n wrapperModules.length === 0\n ? 'missing-wrapper-module'\n : 'shadow-encapsulation',\n directId: directModule.id,\n trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(file) ?? [],\n });\n return [];\n}\n"],"mappings":";;;;;;;;;;;;;;AAoDA,SAAgB,sBACd,cACQ;CACR,MAAM,MAAM,0BAA0B,YAAY;CAElD,OAAO;EACL,MAAM;EACN,SAAS;EACT,MAAM,eAAe,QAAQ;GAC3B,MAAM,IAAI,cAAc,MAAM;EAChC;EACA,UAAU,IAAI;GACZ,OAAO,IAAI,OAAO,wBAAwB,EAAE;EAC9C;EACA,KAAK,IAAI;GACP,OAAO,IAAI,OAAO,mBAAmB,EAAE;EACzC;EACA,gBAAgB,QAAQ;GACtB,IAAI,0BAA0B,KAAK,OAAO,IAAI,GAAG;IAC/C,SAAS,2BAA2B,EAAE,MAAM,OAAO,KAAK,CAAC;IACzD,IAAI,OAAO,eAAe,OAAO,IAAI;GACvC;EAEF;CACF;AACF;AAEA,SAAgB,wBAAwB,KAA6B;CAEnE,IAAI,mBAAmB,KACrB,IACE,gBACD,CAAC,kBAAkB;CAGtB,OAAO;EACL,GAAG;EACH,iBAAiB;CACnB;AACF;;;;;;;;;;;;;AAcA,eAAsB,yBACpB,QACA,MACA,eAAsC,CAAC,GACvC,oBACuB;CACvB,MAAM,iBAAiB,cAAc,KAAK,MAAM,GAAG,CAAC,CAAC,EAAE;CACvD,MAAM,0BAAU,IAAI,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,MAAM,KAAA;EACnC,YAAY,eACT,KAAK,QAAQ,IAAI,EAAE,CAAC,CACpB,QAAQ,OAAqB,OAAO,IAAI;CAC7C,CAAC;CAEH,eAAe,QAAQ;EACrB;EACA;EACA,QACE,eAAe,WAAW,IACtB,2BACA;EACN,UAAU,aAAa;EACvB,mBAAmB,oBAAoB,uBAAuB,IAAI,KAAK,CAAC;CAC1E,CAAC;CACD,OAAO,CAAC;AACV"}
1
+ {"version":3,"file":"component-styles-plugin.js","names":[],"sources":["../../../src/lib/component-styles-plugin.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { union } from 'es-toolkit';\nimport {\n normalizePath,\n type ModuleNode,\n type Plugin,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n ensureAngularBuildContext,\n getFilenameFromPath,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport {\n getComponentStyleSheetMeta,\n isComponentStyleSheet,\n} from './encapsulation-plugin.js';\nimport type {\n StylePreprocessor,\n StylesheetDependency,\n} from './style-preprocessor.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheet,\n rewriteRelativeCssImports,\n} from './stylesheet-registry.js';\nimport { describeStylesheetContent } from './utils/compilation-shared.js';\nimport { debugHmr, debugHmrV, debugStylesV } from './utils/debug.js';\n\nexport interface ComponentStylesheetPipelineDiagnosis {\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\n/**\n * Self-contained Vite plugin that resolves and serves externalized Angular\n * component stylesheets (`?ngcomp=...`) from the shared `AngularBuildContext`\n * stylesheet registry and refreshes served records on source CSS edits.\n */\nexport function componentStylesPlugin(\n ctxOrOptions?: AngularBuildContext | AngularBuildContextOptions,\n): Plugin {\n const ctx = ensureAngularBuildContext(ctxOrOptions);\n\n return {\n name: '@analogjs/vite-plugin-angular:component-styles',\n enforce: 'pre',\n async configResolved(config) {\n await ctx.resolveConfig(config);\n },\n resolveId(id) {\n return ctx.styles.resolveComponentStyleId(id);\n },\n load(id) {\n return ctx.styles.loadComponentStyle(id);\n },\n handleHotUpdate(hmrCtx) {\n if (/\\.(css|less|sass|scss)$/.test(hmrCtx.file)) {\n debugHmr('stylesheet file changed', { file: hmrCtx.file });\n ctx.styles.refreshForFile(hmrCtx.file);\n }\n return undefined;\n },\n };\n}\n\nexport function markModuleSelfAccepting(mod: ModuleNode): ModuleNode {\n // support Vite 6\n if ('_clientModule' in mod) {\n (mod as unknown as { _clientModule: { isSelfAccepting: boolean } })[\n '_clientModule'\n ].isSelfAccepting = true;\n }\n\n return {\n ...mod,\n isSelfAccepting: true,\n } as ModuleNode;\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 ?? undefined,\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 stylesheetRegistry?.getServedSourcePath(requestPath) ??\n stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\\//, ''));\n\n return (\n normalizePath((sourcePath ?? '').split('?')[0]) === normalizedChangedFile\n );\n}\n\nfunction resolveDirectStylesheetSourcePath(\n normalizedFile: string,\n directModule: ModuleNode,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): { directRequestPath?: string; sourcePath: string | undefined } {\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 stylesheetRegistry?.getServedSourcePath(directRequestPath) ??\n stylesheetRegistry?.getServedSourcePath(\n directRequestPath.replace(/^\\//, ''),\n ))\n : normalizedFile;\n\n return { directRequestPath, sourcePath };\n}\n\nexport function diagnoseComponentStylesheetPipeline(\n changedFile: string,\n directModule: ModuleNode,\n stylesheetRegistry: AnalogStylesheetRegistry | undefined,\n wrapperModules: ModuleNode[],\n stylePreprocessor?: StylePreprocessor,\n): ComponentStylesheetPipelineDiagnosis {\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, sourcePath } = resolveDirectStylesheetSourcePath(\n normalizedFile,\n directModule,\n stylesheetRegistry,\n );\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 const registryDescription = registryCode\n ? describeStylesheetContent(registryCode)\n : undefined;\n let sourceDescription:\n | ReturnType<typeof describeStylesheetContent>\n | undefined;\n\n if (sourceCode !== undefined) {\n try {\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 sourceDescription = describeStylesheetContent(expectedRegistryCode);\n } catch {\n anomalies.push('source_preprocess_failed');\n hints.push(\n 'Diagnostic preprocessing of the source stylesheet failed; falling back to raw source summary.',\n );\n sourceDescription = describeStylesheetContent(sourceCode);\n }\n }\n\n if (\n sourceDescription &&\n registryDescription &&\n !anomalies.includes('source_preprocess_failed') &&\n sourceDescription.digest !== registryDescription.digest\n ) {\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 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: sourceDescription,\n registry: registryDescription,\n dependencies,\n diagnostics,\n tags,\n directModuleId: directModule.id ?? undefined,\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(\n requestPath.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(requestPath) ??\n stylesheetRegistry?.getServedSourcePath(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 ?? undefined,\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\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 sendCssUpdate(\n server: ViteDevServer,\n update: {\n path: string;\n acceptedPath: string;\n },\n): void {\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): void {\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\ntype ComponentStylesheetHmrOutcome = 'css-update' | 'full-reload';\n\nfunction logComponentStylesheetHmrOutcome(details: {\n file: string;\n encapsulation: string | undefined;\n diagnosis: ComponentStylesheetPipelineDiagnosis;\n outcome: ComponentStylesheetHmrOutcome;\n directModuleId?: string;\n wrapperIds?: string[];\n}): void {\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 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 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 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 async function handleDirectComponentStyleHmr(options: {\n server: ViteDevServer;\n file: string;\n directModule: ModuleNode;\n fileModules: ModuleNode[];\n stylesheetRegistry?: AnalogStylesheetRegistry;\n stylePreprocessor?: StylePreprocessor;\n}): Promise<ModuleNode[]> {\n const {\n server,\n file,\n directModule,\n fileModules,\n stylesheetRegistry,\n stylePreprocessor,\n } = options;\n const { encapsulation } = getComponentStyleSheetMeta(directModule.id!);\n\n // Angular can load one component stylesheet through two module shapes:\n // 1. a `?direct&ngcomp=...` CSS module, such as a browser `<link>`, that Vite\n // can patch with a normal `css-update`\n // 2. a `?ngcomp=...` JS wrapper module that embeds `__vite__css`\n //\n // Invalidate any live wrapper before patching the direct CSS module so it is\n // re-evaluated with the new content.\n const wrapperModules = await findComponentStylesheetWrapperModules(\n server,\n file,\n directModule,\n fileModules,\n stylesheetRegistry,\n );\n const normalizedFile = normalizePath(file.split('?')[0]);\n const { sourcePath } = resolveDirectStylesheetSourcePath(\n normalizedFile,\n directModule,\n stylesheetRegistry,\n );\n const trackedRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? '') ?? [];\n\n let stylesheetDiagnosis: ComponentStylesheetPipelineDiagnosis | undefined;\n if (debugHmrV.enabled) {\n try {\n stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(\n file,\n directModule,\n stylesheetRegistry,\n wrapperModules,\n stylePreprocessor,\n );\n } catch (error) {\n debugHmrV('component stylesheet pipeline diagnosis failed', {\n file,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n debugStylesV('HMR: component stylesheet changed', {\n file: directModule.file,\n encapsulation,\n });\n debugHmrV('component stylesheet wrapper modules', {\n file,\n wrapperCount: wrapperModules.length,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n availableModuleIds: fileModules.map((mod) => mod.id),\n });\n if (stylesheetDiagnosis) {\n debugHmrV('component stylesheet pipeline diagnosis', stylesheetDiagnosis);\n }\n\n // Drop Vite's cached direct-module transform before wrapper lookup and patching continue.\n server.moduleGraph.invalidateModule(directModule);\n debugHmrV('component stylesheet direct module invalidated', {\n file,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n reason:\n 'Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues.',\n });\n\n // A css-update needs a live direct request or a known wrapper. Vite's CSS\n // hot replacement does not search shadow roots.\n const trackedWrapperRequestIds = trackedRequestIds.filter((id) =>\n id.includes('?ngcomp='),\n );\n const isLiveDirectRequest = !!directModule.id?.includes('?direct&ngcomp=');\n const canUseCssUpdate =\n encapsulation !== 'shadow' &&\n (wrapperModules.length > 0 ||\n trackedWrapperRequestIds.length > 0 ||\n isLiveDirectRequest);\n\n if (canUseCssUpdate) {\n wrapperModules.forEach((mod) => server.moduleGraph.invalidateModule(mod));\n debugHmrV('sending css-update for component stylesheet', {\n file,\n path: directModule.url,\n acceptedPath: directModule.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 : trackedWrapperRequestIds.length > 0\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 : 'No wrapper module is known; patching the live direct stylesheet request.',\n });\n sendCssUpdate(server, {\n path: directModule.url,\n acceptedPath: directModule.file!,\n });\n if (stylesheetDiagnosis) {\n logComponentStylesheetHmrOutcome({\n file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'css-update',\n directModuleId: directModule.id ?? undefined,\n wrapperIds: wrapperModules\n .map((mod) => mod.id)\n .filter((id): id is string => id !== null),\n });\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\n return mod.file !== file || mod.id !== directModule.id;\n })\n .map((mod) => {\n if (mod.file === file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n }) as ModuleNode[],\n wrapperModules.map((mod) => markModuleSelfAccepting(mod)),\n );\n }\n\n const reason =\n encapsulation === 'shadow'\n ? 'shadow-encapsulation'\n : 'missing-wrapper-module';\n debugHmrV('component stylesheet hmr fallback: full reload', {\n file,\n encapsulation,\n reason,\n directId: directModule.id,\n trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(file) ?? [],\n });\n if (stylesheetDiagnosis) {\n logComponentStylesheetHmrOutcome({\n file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'full-reload',\n directModuleId: directModule.id ?? undefined,\n wrapperIds: wrapperModules\n .map((mod) => mod.id)\n .filter((id): id is string => id !== null),\n });\n }\n sendFullReload(server, {\n file,\n encapsulation,\n reason,\n directId: directModule.id,\n trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(file) ?? [],\n });\n return [];\n}\n"],"mappings":";;;;;;;;;;;;;;AAoDA,SAAgB,sBACd,cACQ;CACR,MAAM,MAAM,0BAA0B,YAAY;CAElD,OAAO;EACL,MAAM;EACN,SAAS;EACT,MAAM,eAAe,QAAQ;GAC3B,MAAM,IAAI,cAAc,MAAM;EAChC;EACA,UAAU,IAAI;GACZ,OAAO,IAAI,OAAO,wBAAwB,EAAE;EAC9C;EACA,KAAK,IAAI;GACP,OAAO,IAAI,OAAO,mBAAmB,EAAE;EACzC;EACA,gBAAgB,QAAQ;GACtB,IAAI,0BAA0B,KAAK,OAAO,IAAI,GAAG;IAC/C,SAAS,2BAA2B,EAAE,MAAM,OAAO,KAAK,CAAC;IACzD,IAAI,OAAO,eAAe,OAAO,IAAI;GACvC;EAEF;CACF;AACF;AAEA,SAAgB,wBAAwB,KAA6B;CAEnE,IAAI,mBAAmB,KACrB,IACE,gBACD,CAAC,kBAAkB;CAGtB,OAAO;EACL,GAAG;EACH,iBAAiB;CACnB;AACF;;;;;;;;;;;;;AAcA,eAAsB,yBACpB,QACA,MACA,eAAsC,CAAC,GACvC,oB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;EACA;EACA;EACA,UAAU,aAAa;EACvB,mBAAmB,oBAAoB,uBAAuB,IAAI,KAAK,CAAC;CAC1E,CAAC;CACD,IAAI,qBACF,iCAAiC;EAC/B;EACA;EACA,WAAW;EACX,SAAS;EACT,gBAAgB,aAAa,MAAM,KAAA;EACnC,YAAY,eACT,KAAK,QAAQ,IAAI,EAAE,CAAC,CACpB,QAAQ,OAAqB,OAAO,IAAI;CAC7C,CAAC;CAEH,eAAe,QAAQ;EACrB;EACA;EACA;EACA,UAAU,aAAa;EACvB,mBAAmB,oBAAoB,uBAAuB,IAAI,KAAK,CAAC;CAC1E,CAAC;CACD,OAAO,CAAC;AACV"}
@@ -1,9 +1,9 @@
1
1
  import { Plugin } from "vite";
2
2
  import { type AngularBuildContext } from "./angular-build-context.js";
3
- import { EmitFileResult } from "./models.js";
3
+ import { HmrUpdateResult } from "./models.js";
4
4
  export interface ComponentUpdates {
5
- classNames: Map<string, string>;
6
- fileEmitter: (file: string, className: string) => Pick<EmitFileResult, "hmrUpdateCode"> | undefined;
5
+ classNames: Map<string, Set<string>>;
6
+ fileEmitter: (file: string, className: string) => HmrUpdateResult | undefined;
7
7
  rootDir?: string;
8
8
  }
9
9
  export declare function liveReloadPlugin(ctxOrUpdates?: AngularBuildContext | ComponentUpdates): Plugin;
@@ -5,6 +5,19 @@ import { normalizePath } from "vite";
5
5
  // packages/vite-plugin-angular/src/lib/live-reload-plugin.ts
6
6
  var ANGULAR_COMPONENT_PREFIX = "/@ng/component";
7
7
  var FILE_PREFIX = "file:";
8
+ function createProxyMatchers(proxy) {
9
+ if (!proxy) return [];
10
+ const matchers = [];
11
+ for (const [context, opts] of Object.entries(proxy)) {
12
+ if (!opts) continue;
13
+ if (typeof opts === "object" && typeof opts.bypass === "function") continue;
14
+ if (context.startsWith("^")) {
15
+ const regex = new RegExp(context);
16
+ matchers.push((url) => regex.test(url));
17
+ } else matchers.push((url) => url.startsWith(context));
18
+ }
19
+ return matchers;
20
+ }
8
21
  function liveReloadPlugin(ctxOrUpdates) {
9
22
  const updates = isAngularBuildContext(ctxOrUpdates) ? ctxOrUpdates.hmr : ctxOrUpdates ?? {
10
23
  classNames: /* @__PURE__ */ new Map(),
@@ -19,9 +32,10 @@ function liveReloadPlugin(ctxOrUpdates) {
19
32
  debugHmr("middleware disabled: vite server.hmr is false");
20
33
  return;
21
34
  }
35
+ const proxyMatchers = createProxyMatchers(server.config.server.proxy);
22
36
  const angularComponentMiddleware = async (req, res, next) => {
23
37
  if (req.url === void 0 || res.writableEnded) return;
24
- if (!req.url.includes(ANGULAR_COMPONENT_PREFIX)) {
38
+ if (!req.url.includes(ANGULAR_COMPONENT_PREFIX) || proxyMatchers.some((match) => match(req.url))) {
25
39
  next();
26
40
  return;
27
41
  }
@@ -33,8 +47,22 @@ function liveReloadPlugin(ctxOrUpdates) {
33
47
  }
34
48
  const [fileId, className] = decodeURIComponent(componentId).split("@");
35
49
  const resolvedId = resolveFileId(fileId);
36
- if (!(!!server.moduleGraph.getModuleById(resolvedId)?.lastInvalidationTimestamp && updates.classNames.get(resolvedId))) {
37
- debugHmr("middleware: skipped (not invalidated)", { resolvedId });
50
+ const moduleNode = server.moduleGraph.getModuleById(resolvedId);
51
+ const knownClasses = updates.classNames.get(resolvedId);
52
+ if (!moduleNode && !knownClasses?.size) {
53
+ debugHmr("middleware: passed through (unknown component)", {
54
+ resolvedId,
55
+ className
56
+ });
57
+ next();
58
+ return;
59
+ }
60
+ const hasKnownClass = className ? !!knownClasses?.has(className) : !!knownClasses?.size;
61
+ if (!(!!moduleNode?.lastInvalidationTimestamp && hasKnownClass)) {
62
+ debugHmr("middleware: skipped (not invalidated)", {
63
+ resolvedId,
64
+ className
65
+ });
38
66
  res.setHeader("Content-Type", "text/javascript");
39
67
  res.setHeader("Cache-Control", "no-cache");
40
68
  res.end("");
@@ -43,6 +71,7 @@ function liveReloadPlugin(ctxOrUpdates) {
43
71
  const result = updates.fileEmitter(resolvedId, className);
44
72
  debugHmr("middleware: served component update", {
45
73
  resolvedId,
74
+ className,
46
75
  hasCode: !!result?.hmrUpdateCode
47
76
  });
48
77
  res.setHeader("Content-Type", "text/javascript");
@@ -1 +1 @@
1
- {"version":3,"file":"live-reload-plugin.js","names":[],"sources":["../../../src/lib/live-reload-plugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { ServerResponse } from 'node:http';\nimport { Connect, normalizePath, Plugin, ViteDevServer } from 'vite';\n\nimport {\n isAngularBuildContext,\n type AngularBuildContext,\n} from './angular-build-context.js';\nimport { EmitFileResult } from './models.js';\nimport { debugHmr } from './utils/debug.js';\n\nconst ANGULAR_COMPONENT_PREFIX = '/@ng/component';\nconst FILE_PREFIX = 'file:';\n\nexport interface ComponentUpdates {\n classNames: Map<string, string>;\n fileEmitter: (\n file: string,\n className: string,\n ) => Pick<EmitFileResult, 'hmrUpdateCode'> | undefined;\n rootDir?: string;\n}\n\nexport function liveReloadPlugin(\n ctxOrUpdates?: AngularBuildContext | ComponentUpdates,\n): Plugin {\n const updates: ComponentUpdates = isAngularBuildContext(ctxOrUpdates)\n ? ctxOrUpdates.hmr\n : (ctxOrUpdates ?? {\n classNames: new Map<string, string>(),\n fileEmitter: () => undefined,\n });\n\n const resolveFileId = (fileId: string): string =>\n normalizePath(resolve(updates.rootDir ?? process.cwd(), fileId));\n\n return {\n name: 'analogjs-live-reload-plugin',\n apply: 'serve',\n configureServer(server: ViteDevServer) {\n if (server.config.server.hmr === false) {\n debugHmr('middleware disabled: vite server.hmr is false');\n return;\n }\n\n const angularComponentMiddleware: Connect.HandleFunction = async (\n req: Connect.IncomingMessage,\n res: ServerResponse<Connect.IncomingMessage>,\n next: Connect.NextFunction,\n ) => {\n if (req.url === undefined || res.writableEnded) {\n return;\n }\n\n if (!req.url.includes(ANGULAR_COMPONENT_PREFIX)) {\n next();\n\n return;\n }\n\n const requestUrl = new URL(req.url, 'http://localhost');\n const componentId = requestUrl.searchParams.get('c');\n\n if (!componentId) {\n res.statusCode = 400;\n res.end();\n\n return;\n }\n\n const [fileId, className] = decodeURIComponent(componentId).split('@');\n const resolvedId = resolveFileId(fileId);\n const invalidated =\n !!server.moduleGraph.getModuleById(resolvedId)\n ?.lastInvalidationTimestamp && updates.classNames.get(resolvedId);\n\n // don't send an HMR update until the file has been invalidated\n if (!invalidated) {\n debugHmr('middleware: skipped (not invalidated)', { resolvedId });\n res.setHeader('Content-Type', 'text/javascript');\n res.setHeader('Cache-Control', 'no-cache');\n res.end('');\n return;\n }\n\n const result = updates.fileEmitter(resolvedId, className);\n debugHmr('middleware: served component update', {\n resolvedId,\n hasCode: !!result?.hmrUpdateCode,\n });\n res.setHeader('Content-Type', 'text/javascript');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(`${result?.hmrUpdateCode || ''}`);\n };\n\n server.middlewares.use(angularComponentMiddleware);\n },\n resolveId(id, _importer, options) {\n if (\n options?.ssr &&\n id.startsWith(FILE_PREFIX) &&\n id.includes(ANGULAR_COMPONENT_PREFIX)\n ) {\n return `\\0${id}`;\n }\n\n return undefined;\n },\n load(id, options) {\n if (options?.ssr && id.includes(ANGULAR_COMPONENT_PREFIX)) {\n const requestUrl = new URL(id.slice(1), 'http://localhost');\n const componentId = requestUrl.searchParams.get('c');\n\n if (!componentId) {\n return;\n }\n\n const [fileId, className] = decodeURIComponent(componentId).split('@');\n const result = updates.fileEmitter(resolveFileId(fileId), className);\n\n return result?.hmrUpdateCode || '';\n }\n\n return;\n },\n };\n}\n"],"mappings":";;;;;AAWA,IAAM,2BAA2B;AACjC,IAAM,cAAc;AAWpB,SAAgB,iBACd,cACQ;CACR,MAAM,UAA4B,sBAAsB,YAAY,IAChE,aAAa,MACZ,gBAAgB;EACf,4BAAY,IAAI,IAAoB;EACpC,mBAAmB,KAAA;CACrB;CAEJ,MAAM,iBAAiB,WACrB,cAAc,QAAQ,QAAQ,WAAW,QAAQ,IAAI,GAAG,MAAM,CAAC;CAEjE,OAAO;EACL,MAAM;EACN,OAAO;EACP,gBAAgB,QAAuB;GACrC,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AG,MAAM,CAAC,GAAG,kBACpB,CAAA,CAAW,aAAa,IAAI,GAAG;IAEnD,IAAI,CAAC,aACH;IAGF,MAAM,CAAC,QAAQ,aAAa,mBAAmB,WAAW,CAAC,CAAC,MAAM,GAAG;IAGrE,OAFe,QAAQ,YAAY,cAAc,MAAM,GAAG,SAEnD,CAAA,EAAQ,iBAAiB;GAClC;EAGF;CACF;AACF"}
1
+ {"version":3,"file":"live-reload-plugin.js","names":[],"sources":["../../../src/lib/live-reload-plugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { ServerResponse } from 'node:http';\nimport { Connect, normalizePath, Plugin, ViteDevServer } from 'vite';\n\nimport {\n isAngularBuildContext,\n type AngularBuildContext,\n} from './angular-build-context.js';\nimport { HmrUpdateResult } from './models.js';\nimport { debugHmr } from './utils/debug.js';\n\nconst ANGULAR_COMPONENT_PREFIX = '/@ng/component';\nconst FILE_PREFIX = 'file:';\n\nexport interface ComponentUpdates {\n classNames: Map<string, Set<string>>;\n fileEmitter: (file: string, className: string) => HmrUpdateResult | undefined;\n rootDir?: string;\n}\n\nfunction createProxyMatchers(\n proxy: ViteDevServer['config']['server']['proxy'],\n): Array<(url: string) => boolean> {\n if (!proxy) {\n return [];\n }\n\n const matchers: Array<(url: string) => boolean> = [];\n for (const [context, opts] of Object.entries(proxy)) {\n if (!opts) {\n continue;\n }\n // Skip proxy rules with custom bypass handlers that may route local\n // requests back to this dev server.\n if (typeof opts === 'object' && typeof opts.bypass === 'function') {\n continue;\n }\n if (context.startsWith('^')) {\n const regex = new RegExp(context);\n matchers.push((url) => regex.test(url));\n } else {\n matchers.push((url) => url.startsWith(context));\n }\n }\n return matchers;\n}\n\nexport function liveReloadPlugin(\n ctxOrUpdates?: AngularBuildContext | ComponentUpdates,\n): Plugin {\n const updates: ComponentUpdates = isAngularBuildContext(ctxOrUpdates)\n ? ctxOrUpdates.hmr\n : (ctxOrUpdates ?? {\n classNames: new Map<string, Set<string>>(),\n fileEmitter: () => undefined,\n });\n\n const resolveFileId = (fileId: string): string =>\n normalizePath(resolve(updates.rootDir ?? process.cwd(), fileId));\n\n return {\n name: 'analogjs-live-reload-plugin',\n apply: 'serve',\n configureServer(server: ViteDevServer) {\n if (server.config.server.hmr === false) {\n debugHmr('middleware disabled: vite server.hmr is false');\n return;\n }\n\n const proxyMatchers = createProxyMatchers(server.config.server.proxy);\n\n const angularComponentMiddleware: Connect.HandleFunction = async (\n req: Connect.IncomingMessage,\n res: ServerResponse<Connect.IncomingMessage>,\n next: Connect.NextFunction,\n ) => {\n if (req.url === undefined || res.writableEnded) {\n return;\n }\n\n if (\n !req.url.includes(ANGULAR_COMPONENT_PREFIX) ||\n proxyMatchers.some((match) => match(req.url!))\n ) {\n next();\n\n return;\n }\n\n const requestUrl = new URL(req.url, 'http://localhost');\n const componentId = requestUrl.searchParams.get('c');\n\n if (!componentId) {\n res.statusCode = 400;\n res.end();\n\n return;\n }\n\n const [fileId, className] = decodeURIComponent(componentId).split('@');\n const resolvedId = resolveFileId(fileId);\n const moduleNode = server.moduleGraph.getModuleById(resolvedId);\n const knownClasses = updates.classNames.get(resolvedId);\n\n if (!moduleNode && !knownClasses?.size) {\n debugHmr('middleware: passed through (unknown component)', {\n resolvedId,\n className,\n });\n next();\n return;\n }\n\n const hasKnownClass = className\n ? !!knownClasses?.has(className)\n : !!knownClasses?.size;\n const invalidated =\n !!moduleNode?.lastInvalidationTimestamp && hasKnownClass;\n\n // don't send an HMR update until the file has been invalidated\n if (!invalidated) {\n debugHmr('middleware: skipped (not invalidated)', {\n resolvedId,\n className,\n });\n res.setHeader('Content-Type', 'text/javascript');\n res.setHeader('Cache-Control', 'no-cache');\n res.end('');\n return;\n }\n\n const result = updates.fileEmitter(resolvedId, className);\n debugHmr('middleware: served component update', {\n resolvedId,\n className,\n hasCode: !!result?.hmrUpdateCode,\n });\n res.setHeader('Content-Type', 'text/javascript');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(`${result?.hmrUpdateCode || ''}`);\n };\n\n server.middlewares.use(angularComponentMiddleware);\n },\n resolveId(id, _importer, options) {\n if (\n options?.ssr &&\n id.startsWith(FILE_PREFIX) &&\n id.includes(ANGULAR_COMPONENT_PREFIX)\n ) {\n return `\\0${id}`;\n }\n\n return undefined;\n },\n load(id, options) {\n if (options?.ssr && id.includes(ANGULAR_COMPONENT_PREFIX)) {\n const requestUrl = new URL(id.slice(1), 'http://localhost');\n const componentId = requestUrl.searchParams.get('c');\n\n if (!componentId) {\n return;\n }\n\n const [fileId, className] = decodeURIComponent(componentId).split('@');\n const result = updates.fileEmitter(resolveFileId(fileId), className);\n\n return result?.hmrUpdateCode || '';\n }\n\n return;\n },\n };\n}\n"],"mappings":";;;;;AAWA,IAAM,2BAA2B;AACjC,IAAM,cAAc;AAQpB,SAAS,oBACP,OACiC;CACjC,IAAI,CAAC,OACH,OAAO,CAAC;CAGV,MAAM,WAA4C,CAAC;CACnD,KAAK,MAAM,CAAC,SAAS,SAAS,OAAO,QAAQ,KAAK,GAAG;EACnD,IAAI,CAAC,MACH;EAIF,IAAI,OAAO,SAAS,YAAY,OAAO,KAAK,WAAW,YACrD;EAEF,IAAI,QAAQ,WAAW,GAAG,GAAG;GAC3B,MAAM,QAAQ,IAAI,OAAO,OAAO;GAChC,SAAS,MAAM,QAAQ,MAAM,KAAK,GAAG,CAAC;EACxC,OACE,SAAS,MAAM,QAAQ,IAAI,WAAW,OAAO,CAAC;CAElD;CACA,OAAO;AACT;AAEA,SAAgB,iBACd,cACQ;CACR,MAAM,UAA4B,sBAAsB,YAAY,IAChE,aAAa,MACZ,gBAAgB;EACf,4BAAY,IAAI,IAAyB;EACzC,mBAAmB,KAAA;CACrB;CAEJ,MAAM,iBAAiB,WACrB,cAAc,QAAQ,QAAQ,WAAW,QAAQ,IAAI,GAAG,MAAM,CAAC;CAEjE,OAAO;EACL,MAAM;EACN,OAAO;EACP,gBAAgB,QAAuB;GACrC,IAAI,OAAO,OAAO,OAAO,QAAQ,OAAO;IACtC,SAAS,+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AI;GAC1C;GAEA,OAAO,YAAY,IAAI,0BAA0B;EACnD;EACA,UAAU,IAAI,WAAW,SAAS;GAChC,IACE,SAAS,OACT,GAAG,WAAW,WAAW,KACzB,GAAG,SAAS,wBAAwB,GAEpC,OAAO,KAAK;EAIhB;EACA,KAAK,IAAI,SAAS;GAChB,IAAI,SAAS,OAAO,GAAG,SAAS,wBAAwB,GAAG;IAEzD,MAAM,cAAc,IADG,IAAI,GAAG,MAAM,CAAC,GAAG,kBACpB,CAAA,CAAW,aAAa,IAAI,GAAG;IAEnD,IAAI,CAAC,aACH;IAGF,MAAM,CAAC,QAAQ,aAAa,mBAAmB,WAAW,CAAC,CAAC,MAAM,GAAG;IAGrE,OAFe,QAAQ,YAAY,cAAc,MAAM,GAAG,SAEnD,CAAA,EAAQ,iBAAiB;GAClC;EAGF;CACF;AACF"}
@@ -1,4 +1,7 @@
1
1
  import type ts from "typescript";
2
+ export interface HmrUpdateResult {
3
+ hmrUpdateCode?: string | null;
4
+ }
2
5
  export interface EmitFileResult {
3
6
  content?: string;
4
7
  map?: string;
@@ -6,6 +9,6 @@ export interface EmitFileResult {
6
9
  hash?: Uint8Array;
7
10
  errors?: (string | ts.DiagnosticMessageChain)[];
8
11
  warnings?: (string | ts.DiagnosticMessageChain)[];
9
- hmrUpdateCode?: string | null;
12
+ hmrUpdateCodes?: Map<string, string>;
10
13
  hmrEligible?: boolean | null;
11
14
  }
@@ -441,7 +441,12 @@ function ngpCompilePlugin(optionsOrCtx) {
441
441
  updates.forEach(({ file, className }, index) => {
442
442
  const moduleFile = sourceModules.get(file)?.sourceFile ?? file;
443
443
  hmrUpdateCode.set(`${moduleFile}@${className}`, codes[index]);
444
- componentUpdates.classNames.set(moduleFile, className);
444
+ let fileClasses = componentUpdates.classNames.get(moduleFile);
445
+ if (!fileClasses) {
446
+ fileClasses = /* @__PURE__ */ new Set();
447
+ componentUpdates.classNames.set(moduleFile, fileClasses);
448
+ }
449
+ fileClasses.add(className);
445
450
  server.moduleGraph.getModulesByFile(moduleFile)?.forEach((mod) => server.moduleGraph.invalidateModule(mod));
446
451
  server.ws.send("angular:component-update", {
447
452
  id: encodeURIComponent(`${moduleFile}@${className}`),
@@ -1 +1 @@
1
- {"version":3,"file":"ngp-compile-plugin.js","names":["fsPromises"],"sources":["../../../src/lib/ngp-compile-plugin.ts"],"sourcesContent":["import * as compilerCli from '@angular/compiler-cli';\nimport { existsSync, promises as fsPromises, realpathSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type MagicString from 'magic-string';\nimport { glob } from 'tinyglobby';\nimport * as vite from 'vite';\nimport {\n discoverAnalogIntegrations,\n type ComponentRegistryEntries,\n type TransformFilter,\n} from './analog-plugin-interop.js';\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport { ComponentScanner } from './component-scanner.js';\nimport type { FastCompileResolve } from './fast-compile-api.js';\nimport type { FastCompilePluginOptions } from './fast-compile-plugin.js';\nimport type {\n NgpCompileApi,\n NgpLoweredModule,\n NgpSourceFormat,\n} from './ngp-compile-api.js';\nimport type { StylePreprocessor } from './style-preprocessor.js';\nimport { preprocessStylesheet } from './stylesheet-registry.js';\nimport { isIgnoredHmrFile } from './utils/compilation-shared.js';\nimport {\n createDepOptimizerConfig,\n getTsConfigPath,\n isProdMode,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { angularFullVersion } from './utils/devkit.js';\nimport { findHmrComponentUpdates } from './utils/hmr-component-updates.js';\nimport {\n LspTypeChecker,\n type FileChangeType,\n type SourceLocation,\n} from './utils/lsp-type-checker.js';\nimport {\n canonicalPath,\n createNgpHostFs,\n fromWasmPath,\n toWasmPath,\n type NgpHostFs,\n} from './utils/ngp-host-fs.js';\nimport { isRolldown } from './utils/rolldown.js';\nimport type { ComponentUpdates } from './live-reload-plugin.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from './virtual-modules-plugin.js';\n\n// The unpublished NGP API is loaded at runtime. Model only the surface we use.\ninterface NgpDiagnostic {\n category: number;\n messageText: string;\n}\n\ninterface NgpFile {\n filePath: string;\n diagnostics?: NgpDiagnostic[];\n classes: {\n className?: string;\n component?: {\n templateUrl?: { resolvedPath: string };\n styleUrls?: { resolvedPath: string }[];\n stylesFromUrls?: string[];\n styles?: string[];\n };\n }[];\n}\n\ninterface NgpChunk {\n files: NgpFile[];\n removedFiles?: string[];\n}\n\ninterface NgpResult {\n magicString: MagicString;\n diagnostics?: NgpDiagnostic[];\n tcb?: { code: string } | null;\n hmrUpdateModule?: string | null;\n}\n\ninterface NgpAnalyzer {\n getFileContent(path: string): Promise<string>;\n updateFileContent(\n updates: { filePath: string; content: string }[],\n ): Promise<string[]>;\n invalidateFiles(\n updates: { filePath: string; updateType: number }[],\n ): Promise<string[]>;\n close(): void;\n}\n\ninterface NgpCompiler {\n // Parsed templates by file, cleared by NGP's own update methods\n fileCache: Map<string, unknown>;\n analyzeOptimized(): AsyncIterable<NgpChunk>;\n analyzeOptimizedDelta(): AsyncIterable<NgpChunk>;\n prepareChunk(chunk: NgpChunk): Promise<unknown>;\n processFile(\n path: string,\n content: string,\n ...args: [undefined, NgpFile, unknown] | [NgpFile, unknown]\n ): Promise<NgpResult>;\n}\n\ninterface ComponentUpdate {\n file: string;\n className: string;\n}\n\ninterface NgpAnalyzerOptions {\n nativeBinding?: string;\n backend?: 'wasm';\n wasmBinding?: string;\n enableHmr?: boolean;\n hostFs?: NgpHostFs;\n}\n\n/** NGP's `FileUpdateType`. */\nconst FILE_CREATED = 0;\nconst FILE_DELETED = 1;\nconst FILE_CHANGED = 2;\n\n/** A module of a registered source format, lowered to its program file. */\ninterface SourceModule {\n sourceFile: string;\n /** The source it was lowered from. */\n source: string;\n format: NgpSourceFormat;\n lowered: NgpLoweredModule;\n}\n\ninterface NgpApi {\n createAnalyzer(\n tsconfig: string,\n options: NgpAnalyzerOptions,\n ): Promise<NgpAnalyzer>;\n HybridCompiler: new (\n analyzer: NgpAnalyzer,\n options: Record<string, unknown> & {\n optimize: boolean;\n enableHmr: boolean;\n },\n ) => NgpCompiler;\n buildTypeCheckingConfig(options: Record<string, unknown>): unknown;\n}\n\nfunction isFastCompileOptions(\n value: unknown,\n): value is FastCompilePluginOptions {\n return (\n typeof value === 'object' &&\n value !== null &&\n !isAngularBuildContext(value) &&\n 'tsconfigGetter' in value &&\n typeof (value as FastCompilePluginOptions).tsconfigGetter === 'function'\n );\n}\n\n// Interim NGP build bundled with this package until @angular/ngp is published\nconst BUNDLED_NGP = new URL('../../ngp/', import.meta.url);\n\n/**\n * @param needsHostFs Whether source formats are registered, which only the\n * WebAssembly backend can read through `hostFs`.\n */\nasync function loadNgp(\n tsconfig: string,\n needsHostFs: boolean,\n): Promise<{ api: NgpApi; analyzerOptions: NgpAnalyzerOptions }> {\n const nativeBinding = process.env['ANALOG_NGP_NATIVE_BINDING'];\n if (nativeBinding && needsHostFs) {\n throw new Error(\n \"[@analogjs/vite-plugin-angular]: Source formats such as TSRX can't be compiled with a native NGP analyzer build. Unset ANALOG_NGP_NATIVE_BINDING to use NGP's default WebAssembly analyzer.\",\n );\n }\n let modulePath = process.env['ANALOG_NGP_COMPILER'];\n if (!modulePath) {\n try {\n modulePath = createRequire(tsconfig).resolve('@angular/ngp');\n } catch {\n if (angularFullVersion < 220200) {\n throw new Error(\n \"[@analogjs/vite-plugin-angular]: compilation: 'ngp' requires Angular v22.2 or later.\",\n );\n }\n return {\n api: await import(new URL('api.mjs', BUNDLED_NGP).href),\n analyzerOptions: nativeBinding\n ? { nativeBinding }\n : {\n backend: 'wasm',\n wasmBinding: fileURLToPath(\n new URL('ng_analyze.cjs', BUNDLED_NGP),\n ),\n },\n };\n }\n }\n return {\n api: await import(pathToFileURL(resolve(modulePath)).href),\n analyzerOptions: nativeBinding\n ? { nativeBinding }\n : needsHostFs\n ? { backend: 'wasm' }\n : {},\n };\n}\n\nfunction transpile(\n source: string,\n filePath: string,\n map?: Parameters<typeof vite.transformWithEsbuild>[3],\n) {\n return vite.transformWithOxc\n ? vite.transformWithOxc(\n source,\n filePath,\n { lang: 'ts', sourcemap: true },\n map,\n )\n : vite.transformWithEsbuild(\n source,\n filePath,\n { loader: 'ts', sourcemap: true },\n map,\n );\n}\n\nexport function ngpCompilePlugin(\n optionsOrCtx?:\n | AngularBuildContext\n | FastCompilePluginOptions\n | AngularBuildContextOptions,\n): vite.Plugin {\n const sharedCtx = isAngularBuildContext(optionsOrCtx)\n ? optionsOrCtx\n : isFastCompileOptions(optionsOrCtx)\n ? undefined\n : createAngularBuildContext({\n jit: false,\n ...optionsOrCtx,\n compilationBackend: 'ngp',\n });\n\n const options: FastCompilePluginOptions = sharedCtx\n ? sharedCtx.options\n : (optionsOrCtx as FastCompilePluginOptions);\n\n if (options.jit || options.fastCompileMode === 'partial') {\n throw new Error(\n \"compilation: 'ngp' requires jit: false and fastCompileMode: 'full'.\",\n );\n }\n\n let configContext: TsConfigResolutionContext | undefined;\n let resolvedConfig: vite.ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let componentRegistries: ComponentRegistryEntries[] = [];\n let stylePreprocessor: StylePreprocessor | undefined;\n let watchMode = false;\n let hmr = false;\n let activeBuilds = 0;\n let analyzer: NgpAnalyzer | undefined;\n let compiler: NgpCompiler | undefined;\n let typeChecker: LspTypeChecker | undefined;\n let api: NgpApi;\n let toAnalyzerPath = (path: string) => path;\n let fromAnalyzerPath = vite.normalizePath;\n const filesByPath = new Map<string, { file: NgpFile; chunk: NgpChunk }>();\n const chunkContexts = new Map<NgpChunk, Promise<unknown>>();\n const output = new Map<string, Promise<NgpResult>>();\n const emittedMaps = new Map<string, string>();\n // Last compiled source of each file, compared on edits for HMR\n const sources = new Map<string, string>();\n // Watched files mapped to the source files that depend on them\n const dependents = new Map<string, Set<string>>();\n const hmrUpdateCode = new Map<string, string>();\n const classNames = sharedCtx\n ? sharedCtx.hmr.classNames\n : new Map<string, string>();\n const fileEmitter = (file: string, className: string) => ({\n hmrUpdateCode: hmrUpdateCode.get(`${file}@${className}`),\n });\n sharedCtx?.hmr.setFileEmitter(fileEmitter);\n\n const componentUpdates: ComponentUpdates = {\n classNames,\n fileEmitter,\n };\n let pending = Promise.resolve();\n const excluded = [\n /node_modules/,\n /[?&]raw\\b/,\n /type=script/,\n /@ng\\/component/,\n ];\n const filter = vite.createFilter(TS_EXT_REGEX, excluded);\n const sourceFilter = vite.createFilter(null, excluded);\n\n // Source formats registered through `api.ngp`, the component registry their\n // lowering looks selectors up in, and their modules by program file\n // (`x.tsrx` → `x.tsrx.ts`)\n const sourceFormats: NgpSourceFormat[] = [];\n const scanner = new ComponentScanner();\n const sourceModules = new Map<string, SourceModule>();\n // Per program file: how often it was removed, which cancels a lowering in\n // progress, and the lowered code the analyzer has\n const removals = new Map<string, number>();\n const analyzed = new Map<string, string>();\n // Which modules of each format NGP compiles: its `include` under the tsconfig's directory\n const includes = new Map<NgpSourceFormat, (file: string) => boolean>();\n const moduleFormatOf = (file: string): NgpSourceFormat | undefined =>\n sourceFormats.find(\n (format) => format.test(file) && includes.get(format)?.(file),\n );\n let devServer: vite.ViteDevServer | undefined;\n // The program files a file change lowered again, for the hot update after it\n const reloweredByChange = new Map<string, string[]>();\n const programFileOf = (file: string): string | undefined => {\n const programFile = `${file}.ts`;\n return sourceModules.has(programFile) ? programFile : undefined;\n };\n const sourceFileOf = (file: string): string =>\n sourceModules.get(file)?.sourceFile ?? file;\n\n function resolveTsConfigPath(): string {\n if (sharedCtx) {\n return sharedCtx.resolveTsConfigPath();\n }\n const ctx = configContext ?? {\n root: resolvedConfig?.root || '.',\n isProd: isProdMode(resolvedConfig?.mode),\n isLib: !!resolvedConfig?.build?.lib,\n };\n return getTsConfigPath(\n ctx.root,\n options.tsconfigGetter(),\n ctx.isProd,\n options.isTest,\n ctx.isLib,\n options.workspaceRoot,\n );\n }\n\n const ngp: NgpCompileApi = {\n registerSourceFormat(format) {\n if (!sourceFormats.includes(format)) {\n sourceFormats.push(format);\n scanner.registerSourceFormat(format);\n }\n },\n };\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: resolveTsConfigPath,\n getSourceMap: (id: string): string | undefined =>\n emittedMaps.get(vite.normalizePath(id)),\n hasEmitted: (id: string): boolean =>\n filesByPath.has(vite.normalizePath(id)),\n output,\n ready: (): Promise<void> => pending,\n componentUpdates,\n ngp,\n };\n\n /** Lowers a module of a source format. Returns whether its TypeScript changed. */\n async function lowerSourceModule(\n sourceFile: string,\n source: string,\n format: NgpSourceFormat,\n resolve: FastCompileResolve,\n ): Promise<boolean> {\n const programFile = `${sourceFile}.ts`;\n if (existsSync(programFile)) {\n throw new Error(\n `[@analogjs/vite-plugin-angular]: ${programFile} has the name NGP compiles ${sourceFile} as. Rename one of them.`,\n );\n }\n const removed = removals.get(programFile);\n const lowered = await format.lower(source, sourceFile, {\n scanImports: (specifiers) =>\n scanner.scanImports(specifiers, sourceFile, resolve),\n resolveSelector: (className, moduleSpecifier, containingFile) =>\n scanner.lookupSelector(\n className,\n sharedCtx?.componentRegistries ?? componentRegistries,\n moduleSpecifier !== undefined\n ? {\n moduleSpecifier,\n containingFile: containingFile ?? sourceFile,\n }\n : undefined,\n ),\n });\n // Removed while it was lowered\n if (removals.get(programFile) !== removed) return false;\n const changed =\n sourceModules.get(programFile)?.lowered.code !== lowered.code;\n sourceModules.set(programFile, { sourceFile, source, format, lowered });\n return changed;\n }\n\n /** Lowers every module of the registered source formats under `root`. */\n async function lowerSourceModules(\n root: string,\n resolve: FastCompileResolve,\n ): Promise<void> {\n scanner.reset(root);\n sourceModules.clear();\n const sourceRoot = vite.normalizePath(realpathSync(root));\n await Promise.all(\n sourceFormats.map(async (format) => {\n includes.set(\n format,\n vite.createFilter(format.include, '**/node_modules/**', {\n resolve: sourceRoot,\n }),\n );\n const files = await glob(format.include, {\n cwd: sourceRoot,\n absolute: true,\n ignore: ['**/node_modules/**'],\n });\n await Promise.all(\n files.map(async (file) => {\n const sourceFile = canonicalPath(file);\n const source = await fsPromises.readFile(sourceFile, 'utf-8');\n await lowerSourceModule(sourceFile, source, format, resolve);\n }),\n );\n }),\n );\n // The analyzer reads them through `hostFs` when it's created\n analyzed.clear();\n for (const [programFile, { lowered }] of sourceModules) {\n analyzed.set(programFile, lowered.code);\n }\n }\n\n /**\n * Lowers the source modules a change to `file` affects again: the module\n * itself, and those that looked up selectors in it. Returns the program\n * files whose TypeScript changed.\n */\n async function relowerSourceModules(\n file: string,\n resolve: FastCompileResolve,\n ): Promise<string[]> {\n const affected = [file, ...(scanner.importersByFile.get(file) ?? [])]\n .map(programFileOf)\n .filter((programFile) => programFile !== undefined);\n scanner.invalidate(file);\n const changed = await Promise.all(\n affected.map(async (programFile) => {\n const sourceModule = sourceModules.get(programFile);\n if (!sourceModule) return [];\n const { sourceFile, format } = sourceModule;\n const source = await readSource(sourceFile);\n if (source === undefined) return [];\n const relowered = await lowerSourceModule(\n sourceFile,\n source,\n format,\n resolve,\n );\n return relowered ? [programFile] : [];\n }),\n );\n return changed.flat();\n }\n\n // Lowering and the analyzer updates that follow it, one change at a time, so\n // the modules a change lowers again reach the analyzer together\n let sourceWork: Promise<unknown> = Promise.resolve();\n function withSourceLock<T>(work: () => Promise<T>): Promise<T> {\n const run = sourceWork.catch(() => undefined).then(work);\n sourceWork = run;\n return run;\n }\n\n /** Sends the analyzer the lowered modules it doesn't have yet. */\n async function syncProgramFiles(): Promise<void> {\n const updates = [...sourceModules]\n .filter(\n ([filePath, { lowered }]) => analyzed.get(filePath) !== lowered.code,\n )\n .map(([filePath, { lowered }]) => ({ filePath, content: lowered.code }));\n if (updates.length === 0) return;\n for (const { filePath, content } of updates)\n analyzed.set(filePath, content);\n await enqueueIndex(() =>\n analyzer!.updateFileContent(\n updates.map(({ filePath, content }) => ({\n filePath: toAnalyzerPath(filePath),\n content,\n })),\n ),\n );\n }\n\n /** Reads a source file, or `undefined` if it was removed. */\n function readSource(file: string): Promise<string | undefined> {\n return fsPromises\n .readFile(file, 'utf-8')\n .catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n }\n\n /** Lowers a module added after the build started, if NGP compiles it. */\n async function addSourceModule(\n sourceFile: string,\n format: NgpSourceFormat,\n source: string,\n resolve: FastCompileResolve,\n ): Promise<void> {\n const programFile = `${sourceFile}.ts`;\n await lowerSourceModule(sourceFile, source, format, resolve);\n const sourceModule = sourceModules.get(programFile);\n // Removed while it was lowered\n if (!sourceModule) return;\n // The analyzer reads it through `hostFs`\n analyzed.set(programFile, sourceModule.lowered.code);\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: toAnalyzerPath(programFile), updateType: FILE_CREATED },\n ]),\n );\n }\n\n /** Drops a removed module, and any lowering of it still in progress. */\n async function removeSourceModule(sourceFile: string): Promise<void> {\n const programFile = `${sourceFile}.ts`;\n removals.set(programFile, (removals.get(programFile) ?? 0) + 1);\n analyzed.delete(programFile);\n if (!sourceModules.delete(programFile)) return;\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: toAnalyzerPath(programFile), updateType: FILE_DELETED },\n ]),\n );\n }\n\n /**\n * Lowers a module for its transform, as fast compile does on every\n * transform, so the selectors it looks up are current. A transform that\n * started before a hot update can carry the previous code; it compiles the\n * latest lowering instead.\n */\n async function lowerForTransform(\n sourceFile: string,\n format: NgpSourceFormat,\n code: string,\n resolve: FastCompileResolve,\n ): Promise<NgpLoweredModule | undefined> {\n const programFile = `${sourceFile}.ts`;\n if (!sourceModules.has(programFile)) {\n // Requested before its `create` event, or added during `vite build --watch`\n await addSourceModule(sourceFile, format, code, resolve);\n } else if (code === (await readSource(sourceFile))) {\n await lowerSourceModule(sourceFile, code, format, resolve);\n }\n return sourceModules.get(programFile)?.lowered;\n }\n\n /** Maps a type error in a program file to the source module's location. */\n function toSourceLocation(location: SourceLocation): SourceLocation {\n const sourceModule = sourceModules.get(vite.normalizePath(location.file));\n const mapped = sourceModule?.lowered.toSourceLocation(\n location.line - 1,\n location.character - 1,\n );\n return mapped\n ? {\n file: sourceModule!.sourceFile,\n line: mapped.line + 1,\n character: mapped.column + 1,\n }\n : location;\n }\n\n sharedCtx?.registerCompiler({\n name: '@analogjs/vite-plugin-angular-ngp',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n async function prepareResources(\n file: NgpFile,\n watch: (path: string) => void,\n ): Promise<NgpFile> {\n const hostFilePath = fromAnalyzerPath(file.filePath);\n watch(hostFilePath);\n const activeConfig = sharedCtx?.resolvedConfig ?? resolvedConfig;\n const activeStylePreprocessor =\n sharedCtx?.stylePreprocessor ?? stylePreprocessor;\n\n return {\n ...file,\n classes: await Promise.all(\n file.classes.map(async (metadata, classIndex) => {\n const component = metadata.component;\n if (!component) return metadata;\n if (component.templateUrl)\n watch(fromAnalyzerPath(component.templateUrl.resolvedPath));\n for (const style of component.styleUrls ?? [])\n watch(fromAnalyzerPath(style.resolvedPath));\n const preprocess = async (\n content: string,\n path: string,\n order: number,\n inline: boolean,\n ) => {\n const preprocessed = preprocessStylesheet(\n content,\n path,\n activeStylePreprocessor,\n {\n filename: path,\n containingFile: hostFilePath,\n resourceFile: inline ? undefined : path,\n className: metadata.className,\n order,\n inline,\n },\n );\n const result = await vite.preprocessCSS(\n preprocessed,\n path,\n activeConfig,\n );\n result.deps?.forEach(watch);\n return result.code;\n };\n return {\n ...metadata,\n component: {\n ...component,\n styles:\n component.styles &&\n (await Promise.all(\n component.styles.map((style, index) =>\n preprocess(\n style,\n `${hostFilePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`,\n index,\n true,\n ),\n ),\n )),\n stylesFromUrls:\n component.stylesFromUrls &&\n (await Promise.all(\n component.stylesFromUrls.map((style, index) =>\n preprocess(\n style,\n fromAnalyzerPath(\n component.styleUrls![index].resolvedPath,\n ),\n index,\n false,\n ),\n ),\n )),\n },\n };\n }),\n ),\n };\n }\n\n async function indexChunks(update?: () => Promise<string[]>): Promise<void> {\n if (update) {\n const invalidated = await update();\n for (const filePath of invalidated) {\n output.delete(fromAnalyzerPath(filePath));\n compiler!.fileCache.delete(filePath);\n }\n chunkContexts.clear();\n } else {\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n const angularOptions = compilerCli.readConfiguration(\n resolveTsConfigPath(),\n ).options as Record<string, unknown>;\n compiler = new api.HybridCompiler(analyzer!, {\n ...angularOptions,\n optimize: true,\n enableHmr: hmr,\n tcbConfig: api.buildTypeCheckingConfig(angularOptions),\n });\n }\n const chunks = update\n ? compiler!.analyzeOptimizedDelta()\n : compiler!.analyzeOptimized();\n for await (const chunk of chunks) {\n for (const file of chunk.files) {\n const normPath = fromAnalyzerPath(file.filePath);\n filesByPath.set(normPath, { file, chunk });\n output.delete(normPath);\n compiler!.fileCache.delete(file.filePath);\n }\n for (const removed of chunk.removedFiles ?? []) {\n const normPath = fromAnalyzerPath(removed);\n filesByPath.delete(normPath);\n output.delete(normPath);\n }\n }\n }\n\n function enqueueIndex(update: () => Promise<string[]>): Promise<void> {\n pending = pending.catch(() => {}).then(() => indexChunks(update));\n return pending;\n }\n\n function getChunkContext(chunk: NgpChunk): Promise<unknown> {\n let context = chunkContexts.get(chunk);\n if (!context) {\n context = compiler!.prepareChunk(chunk);\n chunkContexts.set(chunk, context);\n }\n return context;\n }\n\n async function checkTypes(\n filePath: string,\n sourceCode: string,\n tcbCode?: string | null,\n ): Promise<void> {\n typeChecker ??= new LspTypeChecker(\n resolveTsConfigPath(),\n options.typeChecker,\n {\n inMemoryFiles: () =>\n new Map(\n [...sourceModules].map(([file, { lowered }]) => [\n file,\n lowered.code,\n ]),\n ),\n mapLocation: toSourceLocation,\n },\n );\n typeChecker.queueFile(filePath, sourceCode, tcbCode);\n if (!watchMode) return;\n const typeErrors = await typeChecker.flushQueue(true);\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n }\n\n async function processFile(\n normPath: string,\n activeCompiler: NgpCompiler,\n watch: (path: string) => void,\n ) {\n const { file: analyzed, chunk } = filesByPath.get(normPath)!;\n const [file, context, content] = await Promise.all([\n prepareResources(analyzed, (path) => {\n const key = sourceFileOf(vite.normalizePath(path));\n dependents.set(key, (dependents.get(key) ?? new Set()).add(normPath));\n watch(key);\n }),\n getChunkContext(chunk),\n analyzer!.getFileContent(analyzed.filePath),\n ]);\n sources.set(normPath, content);\n const result =\n activeCompiler.processFile.length >= 5\n ? await activeCompiler.processFile(\n file.filePath,\n content,\n undefined,\n file,\n context,\n )\n : await activeCompiler.processFile(\n file.filePath,\n content,\n file,\n context,\n );\n return { file, content, result };\n }\n\n function compileFile(\n normPath: string,\n watch: (path: string) => void,\n ): Promise<NgpResult> | undefined {\n if (!filesByPath.has(normPath)) return undefined;\n let task = output.get(normPath);\n if (!task) {\n task = (async () => {\n // Analyzer updates queued before this compile land first\n await pending;\n if (!filesByPath.has(normPath)) {\n throw new Error(`${sourceFileOf(normPath)} was removed.`);\n }\n const { file, content, result } = await processFile(\n normPath,\n compiler!,\n watch,\n );\n const errors = [\n ...(file.diagnostics ?? []),\n ...(result.diagnostics ?? []),\n ].filter((diagnostic) => diagnostic.category === 1);\n if (errors.length) {\n throw new Error(\n `${sourceFileOf(normPath)}: ${errors.map((error) => error.messageText).join('\\n')}`,\n );\n }\n if (options.disableTypeChecking !== true) {\n await checkTypes(\n fromAnalyzerPath(file.filePath),\n content,\n result.tcb?.code,\n );\n }\n return result;\n })();\n output.set(normPath, task);\n }\n return task;\n }\n\n function componentNames(normPath: string): string[] {\n return (filesByPath.get(normPath)?.file.classes ?? []).flatMap(\n ({ className, component }) => (component && className ? [className] : []),\n );\n }\n\n // Components to update in place, following the Angular CLI's rule\n async function findComponentUpdates(\n normPath: string,\n read: () => string | Promise<string>,\n ): Promise<ComponentUpdate[]> {\n if (!TS_EXT_REGEX.test(normPath)) {\n return [...(dependents.get(normPath) ?? [])].flatMap((file) =>\n componentNames(file).map((className) => ({ file, className })),\n );\n }\n const stale = sources.get(normPath);\n if (stale === undefined) return [];\n const matchedClassNames = findHmrComponentUpdates(\n normPath,\n stale,\n await read(),\n new Set(componentNames(normPath)),\n );\n return (matchedClassNames ?? []).map((className) => ({\n file: normPath,\n className,\n }));\n }\n\n async function emitHmrUpdate(file: string, className: string) {\n // NGP emits only the update module of the class named by `hmrUpdateTarget`,\n // and only when it doesn't reuse the file's previously processed output\n const target = Object.assign(\n Object.create(Object.getPrototypeOf(compiler)),\n compiler,\n { hmrUpdateTarget: className, reuseProcessedFiles: false },\n );\n const { result } = await processFile(file, target, () => {});\n return (\n result.hmrUpdateModule &&\n (await transpile(result.hmrUpdateModule, file)).code\n );\n }\n\n async function sendComponentUpdates(\n updates: ComponentUpdate[],\n server: vite.ViteDevServer,\n ): Promise<boolean> {\n try {\n for (const file of new Set(updates.map((update) => update.file))) {\n await compileFile(file, () => {});\n }\n const codes = await Promise.all(\n updates.map(({ file, className }) => emitHmrUpdate(file, className)),\n );\n if (codes.some((code) => !code)) return false;\n updates.forEach(({ file, className }, index) => {\n // Components of a source module update through the module itself\n const sourceFile = sourceModules.get(file)?.sourceFile;\n const moduleFile = sourceFile ?? file;\n hmrUpdateCode.set(`${moduleFile}@${className}`, codes[index]!);\n componentUpdates.classNames.set(moduleFile, className);\n server.moduleGraph\n .getModulesByFile(moduleFile)\n ?.forEach((mod) => server.moduleGraph.invalidateModule(mod));\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(`${moduleFile}@${className}`),\n timestamp: Date.now(),\n });\n });\n return true;\n } catch {\n // A full reload reports the compilation error\n return false;\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-ngp',\n enforce: 'pre',\n api: compilerApi,\n config(config, { command, mode }) {\n watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n if (sharedCtx) {\n sharedCtx.initConfig(config, { command, mode });\n } else {\n configContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config.build?.lib,\n };\n }\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: resolveTsConfigPath(),\n isProd,\n jit: false,\n watchMode,\n isTest: options.isTest,\n isAstroIntegration: options.isAstroIntegration,\n });\n return {\n ...(isRolldown() ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n hmr =\n watchMode &&\n options.liveReload &&\n !options.isTest &&\n config.server.hmr !== false;\n const integrations = sharedCtx\n ? await sharedCtx.resolveConfig(config)\n : await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n componentRegistries = integrations.componentRegistries;\n stylePreprocessor = integrations.stylePreprocessor;\n },\n configureServer(server) {\n const changeTypes: Record<string, FileChangeType> = {\n add: 1,\n change: 2,\n unlink: 3,\n };\n devServer = server;\n server.watcher.on('all', (event, path) => {\n const type = changeTypes[event];\n if (type) typeChecker?.notifyFileChanged(path, type);\n });\n server.httpServer?.on('close', () => {\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n });\n },\n // Runs on the dev server with or without HMR, and in `vite build --watch`\n async watchChange(id, { event }) {\n if (!analyzer || sourceFormats.length === 0) return;\n const file = canonicalPath(id);\n const resolve: FastCompileResolve = (spec, importer) =>\n this.resolve(spec, importer, { skipSelf: true });\n await withSourceLock(async () => {\n scanner.invalidate(file);\n const format = moduleFormatOf(file);\n if (event === 'update') {\n reloweredByChange.set(\n file,\n await relowerSourceModules(file, resolve),\n );\n } else if (event === 'delete') {\n await removeSourceModule(file);\n } else if (\n event === 'create' &&\n format &&\n !sourceModules.has(`${file}.ts`)\n ) {\n const source = await readSource(file);\n if (source !== undefined) {\n await addSourceModule(file, format, source, resolve);\n }\n }\n await syncProgramFiles();\n });\n // Modules that looked up selectors in `file` lower again when transformed\n for (const importer of scanner.importersByFile.get(file) ?? []) {\n devServer?.moduleGraph\n .getModulesByFile(importer)\n ?.forEach((mod) => devServer!.moduleGraph.invalidateModule(mod));\n }\n },\n async buildStart() {\n activeBuilds++;\n if (!analyzer) {\n const tsconfig = resolveTsConfigPath();\n const hasSourceFormats = sourceFormats.length > 0;\n const ngp = await loadNgp(tsconfig, hasSourceFormats);\n const isWasm = ngp.analyzerOptions.backend === 'wasm';\n toAnalyzerPath = isWasm ? toWasmPath : (path) => path;\n fromAnalyzerPath = isWasm ? fromWasmPath : vite.normalizePath;\n api = ngp.api;\n if (hasSourceFormats) {\n await lowerSourceModules(dirname(tsconfig), (specifier, importer) =>\n this.resolve(specifier, importer, { skipSelf: true }),\n );\n }\n analyzer = await api.createAnalyzer(toAnalyzerPath(tsconfig), {\n ...ngp.analyzerOptions,\n enableHmr: hmr,\n hostFs:\n hasSourceFormats || isWasm\n ? createNgpHostFs(\n hasSourceFormats\n ? (path) => sourceModules.get(path)?.lowered.code\n : undefined,\n )\n : undefined,\n });\n pending = indexChunks();\n }\n await pending;\n for (const path of dependents.keys()) {\n this.addWatchFile(path);\n }\n },\n resolveId(id, importer) {\n return resolveAngularVirtualId(id, importer, {\n jit: false,\n resolvedConfig: sharedCtx?.resolvedConfig ?? resolvedConfig,\n });\n },\n async load(id) {\n return loadAngularVirtualModule(\n this,\n id,\n sharedCtx?.resolvedConfig ?? resolvedConfig,\n );\n },\n async transform(code, id) {\n const activeTransformFilter =\n sharedCtx?.transformFilter ?? transformFilter;\n const filePath = vite.normalizePath(id.split('?')[0]);\n const sourceFormat = scanner.sourceFormatOf(filePath);\n if (\n !(sourceFormat ? sourceFilter(id) : filter(id)) ||\n activeTransformFilter?.(code, id) === false\n ) {\n return;\n }\n await pending;\n let lowered: NgpLoweredModule | undefined;\n let compiledFile = filePath;\n if (sourceFormat) {\n const sourceFile = canonicalPath(filePath);\n const format = moduleFormatOf(sourceFile);\n if (!format) {\n this.error(\n `${filePath} is outside ${dirname(resolveTsConfigPath())}, where '${sourceFormat.name}' modules are compiled from.`,\n );\n }\n lowered = await withSourceLock(async () => {\n const result = await lowerForTransform(\n sourceFile,\n format,\n code,\n (spec, importer) =>\n this.resolve(spec, importer, { skipSelf: true }),\n );\n await syncProgramFiles();\n return result;\n });\n if (!lowered) {\n this.error(`${filePath} was removed while it was compiled.`);\n }\n if (lowered.error) {\n this.error({\n message: lowered.error.message,\n id: filePath,\n loc: lowered.error.loc && { file: filePath, ...lowered.error.loc },\n });\n }\n compiledFile = `${sourceFile}.ts`;\n // Transform the module again when a component it looked up changes\n for (const dependency of scanner.dependenciesOf(sourceFile)) {\n this.addWatchFile(dependency);\n }\n }\n const compiledCode = lowered ? lowered.code : code;\n const watch = (path: string) => this.addWatchFile(path);\n let result: NgpResult | undefined;\n try {\n result = await compileFile(compiledFile, watch);\n } catch (error) {\n // A failed compile stays cached until its file is updated, so only\n // report it if it compiled this content\n if (\n !sources.has(compiledFile) ||\n sources.get(compiledFile) === compiledCode\n ) {\n throw error;\n }\n }\n if (\n filesByPath.has(compiledFile) &&\n sources.get(compiledFile) !== compiledCode\n ) {\n if (lowered) analyzed.set(compiledFile, compiledCode);\n await enqueueIndex(() =>\n analyzer!.updateFileContent([\n {\n filePath: toAnalyzerPath(compiledFile),\n content: compiledCode,\n },\n ]),\n );\n result = await compileFile(compiledFile, watch);\n } else if (!result && lowered) {\n this.error(\n `${filePath} is not part of the TypeScript program of ${resolveTsConfigPath()}. Import it, or add it to the tsconfig's \\`include\\`.`,\n );\n } else if (!result && options.disableTypeChecking !== true) {\n await checkTypes(filePath, code);\n }\n let source = result?.magicString.toString() ?? code;\n if (result) {\n const analyzerFile = filesByPath.get(compiledFile)!.file.filePath;\n if (analyzerFile !== filePath) {\n // Component HMR ids name the analyzer's file; the dev server knows the module\n source = source.replaceAll(\n encodeURIComponent(`${analyzerFile}@`),\n encodeURIComponent(`${filePath}@`),\n );\n }\n }\n const map = result?.magicString.generateMap({\n source: compiledFile,\n includeContent: true,\n hires: true,\n });\n const transpiled = await transpile(source, compiledFile, map);\n const outputMap =\n lowered && transpiled.map\n ? lowered.mapToSource(JSON.stringify(transpiled.map))\n : transpiled.map;\n if (outputMap) {\n emittedMaps.set(\n filePath,\n typeof outputMap === 'string' ? outputMap : JSON.stringify(outputMap),\n );\n }\n return {\n code: transpiled.code,\n map: outputMap as vite.Rollup.SourceMapInput,\n };\n },\n async handleHotUpdate(ctx) {\n if (\n sharedCtx\n ? sharedCtx.hmr.isIgnoredFile(ctx.file)\n : isIgnoredHmrFile(ctx.file)\n ) {\n return [];\n }\n const normPath = vite.normalizePath(ctx.file);\n const sourceFile = canonicalPath(ctx.file);\n const programFile = programFileOf(sourceFile);\n const updates = await withSourceLock(async () => {\n // Lowered again in `watchChange`, which runs first\n const relowered = reloweredByChange.get(sourceFile) ?? [];\n reloweredByChange.delete(sourceFile);\n const lowered = programFile\n ? sourceModules.get(programFile)?.lowered\n : undefined;\n // In place only for a module that lowered without errors, which no\n // other module was lowered again against\n const componentUpdates =\n hmr &&\n !lowered?.error &&\n relowered.every((file) => file === programFile)\n ? await findComponentUpdates(\n programFile ?? normPath,\n lowered ? () => lowered.code : ctx.read,\n )\n : [];\n if (!programFile) {\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: toAnalyzerPath(ctx.file), updateType: FILE_CHANGED },\n ]),\n );\n }\n await syncProgramFiles();\n return componentUpdates;\n });\n if (updates.length && (await sendComponentUpdates(updates, ctx.server))) {\n return [];\n }\n hmrUpdateCode.clear();\n componentUpdates.classNames.clear();\n ctx.server.moduleGraph.invalidateAll();\n ctx.server.ws.send({ type: 'full-reload' });\n return [];\n },\n async buildEnd(error) {\n if (error || watchMode || !typeChecker) return;\n const typeErrors = await typeChecker.flushQueue();\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n },\n async closeBundle() {\n activeBuilds = Math.max(0, activeBuilds - 1);\n if (watchMode || activeBuilds > 0) return;\n await pending.catch(() => {});\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n emittedMaps.clear();\n sources.clear();\n dependents.clear();\n sourceModules.clear();\n analyzed.clear();\n releaseCssPreprocessorWorkers();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiIA,IAAM,eAAe;AACrB,IAAM,eAAe;AACrB,IAAM,eAAe;AA0BrB,SAAS,qBACP,OACmC;CACnC,OACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,sBAAsB,KAAK,KAC5B,oBAAoB,SACpB,OAAQ,MAAmC,mBAAmB;AAElE;AAGA,IAAM,cAAc,IAAA,IAAA,cAAA,KAAA,YAAA,GAAA;;;;;AAMpB,eAAe,QACb,UACA,aAC+D;CAC/D,MAAM,gBAAgB,QAAQ,IAAI;CAClC,IAAI,iBAAiB,aACnB,MAAM,IAAI,MACR,6LACF;CAEF,IAAI,aAAa,QAAQ,IAAI;CAC7B,IAAI,CAAC,YACH,IAAI;EACF,aAAa,cAAc,QAAQ,CAAC,CAAC,QAAQ,cAAc;CAC7D,QAAQ;EACN,IAAI,qBAAqB,QACvB,MAAM,IAAI,MACR,sFACF;EAEF,OAAO;GACL,KAAK,MAAM,OAAO,IAAI,IAAI,WAAW,WAAW,CAAC,CAAC;GAClD,iBAAiB,gBACb,EAAE,cAAc,IAChB;IACE,SAAS;IACT,aAAa,cACX,IAAI,IAAI,kBAAkB,WAAW,CACvC;GACF;EACN;CACF;CAEF,OAAO;EACL,KAAK,MAAM,OAAO,cAAc,QAAQ,UAAU,CAAC,CAAC,CAAC;EACrD,iBAAiB,gBACb,EAAE,cAAc,IAChB,cACE,EAAE,SAAS,OAAO,IAClB,CAAC;CACT;AACF;AAEA,SAAS,UACP,QACA,UACA,KACA;CACA,OAAO,KAAK,mBACR,KAAK,iBACH,QACA,UACA;EAAE,MAAM;EAAM,WAAW;CAAK,GAC9B,GACF,IACA,KAAK,qBACH,QACA,UACA;EAAE,QAAQ;EAAM,WAAW;CA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,MAAM,mBACJ,OACA,CAAC,SAAS,SACV,UAAU,OAAO,SAAS,SAAS,WAAW,IAC1C,MAAM,qBACJ,eAAe,UACf,gBAAgB,QAAQ,OAAO,IAAI,IACrC,IACA,CAAC;IACP,IAAI,CAAC,aACH,MAAM,mBACJ,SAAU,gBAAgB,CACxB;KAAE,UAAU,eAAe,IAAI,IAAI;KAAG,YAAY;IAAa,CACjE,CAAC,CACH;IAEF,MAAM,iBAAiB;IACvB,OAAO;GACT,CAAC;GACD,IAAI,QAAQ,UAAW,MAAM,qBAAqB,SAAS,IAAI,MAAM,GACnE,OAAO,CAAC;GAEV,cAAc,MAAM;GACpB,iBAAiB,WAAW,MAAM;GAClC,IAAI,OAAO,YAAY,cAAc;GACrC,IAAI,OAAO,GAAG,KAAK,EAAE,MAAM,cAAc,CAAC;GAC1C,OAAO,CAAC;EACV;EACA,MAAM,SAAS,OAAO;GACpB,IAAI,SAAS,aAAa,CAAC,aAAa;GACxC,MAAM,aAAa,MAAM,YAAY,WAAW;GAChD,IAAI,WAAW,QACb,MAAM,IAAI,MAAM,WAAW,KAAK,IAAI,CAAC;EAEzC;EACA,MAAM,cAAc;GAClB,eAAe,KAAK,IAAI,GAAG,eAAe,CAAC;GAC3C,IAAI,aAAa,eAAe,GAAG;GACnC,MAAM,QAAQ,YAAY,CAAC,CAAC;GAC5B,aAAa,MAAM;GACnB,cAAc,KAAA;GACd,UAAU,MAAM;GAChB,WAAW,KAAA;GACX,WAAW,KAAA;GACX,YAAY,MAAM;GAClB,cAAc,MAAM;GACpB,OAAO,MAAM;GACb,YAAY,MAAM;GAClB,QAAQ,MAAM;GACd,WAAW,MAAM;GACjB,cAAc,MAAM;GACpB,SAAS,MAAM;GACf,8BAA8B;EAChC;CACF;AACF"}
1
+ {"version":3,"file":"ngp-compile-plugin.js","names":["fsPromises"],"sources":["../../../src/lib/ngp-compile-plugin.ts"],"sourcesContent":["import * as compilerCli from '@angular/compiler-cli';\nimport { existsSync, promises as fsPromises, realpathSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type MagicString from 'magic-string';\nimport { glob } from 'tinyglobby';\nimport * as vite from 'vite';\nimport {\n discoverAnalogIntegrations,\n type ComponentRegistryEntries,\n type TransformFilter,\n} from './analog-plugin-interop.js';\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport { ComponentScanner } from './component-scanner.js';\nimport type { FastCompileResolve } from './fast-compile-api.js';\nimport type { FastCompilePluginOptions } from './fast-compile-plugin.js';\nimport type {\n NgpCompileApi,\n NgpLoweredModule,\n NgpSourceFormat,\n} from './ngp-compile-api.js';\nimport type { StylePreprocessor } from './style-preprocessor.js';\nimport { preprocessStylesheet } from './stylesheet-registry.js';\nimport { isIgnoredHmrFile } from './utils/compilation-shared.js';\nimport {\n createDepOptimizerConfig,\n getTsConfigPath,\n isProdMode,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { angularFullVersion } from './utils/devkit.js';\nimport { findHmrComponentUpdates } from './utils/hmr-component-updates.js';\nimport {\n LspTypeChecker,\n type FileChangeType,\n type SourceLocation,\n} from './utils/lsp-type-checker.js';\nimport {\n canonicalPath,\n createNgpHostFs,\n fromWasmPath,\n toWasmPath,\n type NgpHostFs,\n} from './utils/ngp-host-fs.js';\nimport { isRolldown } from './utils/rolldown.js';\nimport type { ComponentUpdates } from './live-reload-plugin.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from './virtual-modules-plugin.js';\n\n// The unpublished NGP API is loaded at runtime. Model only the surface we use.\ninterface NgpDiagnostic {\n category: number;\n messageText: string;\n}\n\ninterface NgpFile {\n filePath: string;\n diagnostics?: NgpDiagnostic[];\n classes: {\n className?: string;\n component?: {\n templateUrl?: { resolvedPath: string };\n styleUrls?: { resolvedPath: string }[];\n stylesFromUrls?: string[];\n styles?: string[];\n };\n }[];\n}\n\ninterface NgpChunk {\n files: NgpFile[];\n removedFiles?: string[];\n}\n\ninterface NgpResult {\n magicString: MagicString;\n diagnostics?: NgpDiagnostic[];\n tcb?: { code: string } | null;\n hmrUpdateModule?: string | null;\n}\n\ninterface NgpAnalyzer {\n getFileContent(path: string): Promise<string>;\n updateFileContent(\n updates: { filePath: string; content: string }[],\n ): Promise<string[]>;\n invalidateFiles(\n updates: { filePath: string; updateType: number }[],\n ): Promise<string[]>;\n close(): void;\n}\n\ninterface NgpCompiler {\n // Parsed templates by file, cleared by NGP's own update methods\n fileCache: Map<string, unknown>;\n analyzeOptimized(): AsyncIterable<NgpChunk>;\n analyzeOptimizedDelta(): AsyncIterable<NgpChunk>;\n prepareChunk(chunk: NgpChunk): Promise<unknown>;\n processFile(\n path: string,\n content: string,\n ...args: [undefined, NgpFile, unknown] | [NgpFile, unknown]\n ): Promise<NgpResult>;\n}\n\ninterface ComponentUpdate {\n file: string;\n className: string;\n}\n\ninterface NgpAnalyzerOptions {\n nativeBinding?: string;\n backend?: 'wasm';\n wasmBinding?: string;\n enableHmr?: boolean;\n hostFs?: NgpHostFs;\n}\n\n/** NGP's `FileUpdateType`. */\nconst FILE_CREATED = 0;\nconst FILE_DELETED = 1;\nconst FILE_CHANGED = 2;\n\n/** A module of a registered source format, lowered to its program file. */\ninterface SourceModule {\n sourceFile: string;\n /** The source it was lowered from. */\n source: string;\n format: NgpSourceFormat;\n lowered: NgpLoweredModule;\n}\n\ninterface NgpApi {\n createAnalyzer(\n tsconfig: string,\n options: NgpAnalyzerOptions,\n ): Promise<NgpAnalyzer>;\n HybridCompiler: new (\n analyzer: NgpAnalyzer,\n options: Record<string, unknown> & {\n optimize: boolean;\n enableHmr: boolean;\n },\n ) => NgpCompiler;\n buildTypeCheckingConfig(options: Record<string, unknown>): unknown;\n}\n\nfunction isFastCompileOptions(\n value: unknown,\n): value is FastCompilePluginOptions {\n return (\n typeof value === 'object' &&\n value !== null &&\n !isAngularBuildContext(value) &&\n 'tsconfigGetter' in value &&\n typeof (value as FastCompilePluginOptions).tsconfigGetter === 'function'\n );\n}\n\n// Interim NGP build bundled with this package until @angular/ngp is published\nconst BUNDLED_NGP = new URL('../../ngp/', import.meta.url);\n\n/**\n * @param needsHostFs Whether source formats are registered, which only the\n * WebAssembly backend can read through `hostFs`.\n */\nasync function loadNgp(\n tsconfig: string,\n needsHostFs: boolean,\n): Promise<{ api: NgpApi; analyzerOptions: NgpAnalyzerOptions }> {\n const nativeBinding = process.env['ANALOG_NGP_NATIVE_BINDING'];\n if (nativeBinding && needsHostFs) {\n throw new Error(\n \"[@analogjs/vite-plugin-angular]: Source formats such as TSRX can't be compiled with a native NGP analyzer build. Unset ANALOG_NGP_NATIVE_BINDING to use NGP's default WebAssembly analyzer.\",\n );\n }\n let modulePath = process.env['ANALOG_NGP_COMPILER'];\n if (!modulePath) {\n try {\n modulePath = createRequire(tsconfig).resolve('@angular/ngp');\n } catch {\n if (angularFullVersion < 220200) {\n throw new Error(\n \"[@analogjs/vite-plugin-angular]: compilation: 'ngp' requires Angular v22.2 or later.\",\n );\n }\n return {\n api: await import(new URL('api.mjs', BUNDLED_NGP).href),\n analyzerOptions: nativeBinding\n ? { nativeBinding }\n : {\n backend: 'wasm',\n wasmBinding: fileURLToPath(\n new URL('ng_analyze.cjs', BUNDLED_NGP),\n ),\n },\n };\n }\n }\n return {\n api: await import(pathToFileURL(resolve(modulePath)).href),\n analyzerOptions: nativeBinding\n ? { nativeBinding }\n : needsHostFs\n ? { backend: 'wasm' }\n : {},\n };\n}\n\nfunction transpile(\n source: string,\n filePath: string,\n map?: Parameters<typeof vite.transformWithEsbuild>[3],\n) {\n return vite.transformWithOxc\n ? vite.transformWithOxc(\n source,\n filePath,\n { lang: 'ts', sourcemap: true },\n map,\n )\n : vite.transformWithEsbuild(\n source,\n filePath,\n { loader: 'ts', sourcemap: true },\n map,\n );\n}\n\nexport function ngpCompilePlugin(\n optionsOrCtx?:\n | AngularBuildContext\n | FastCompilePluginOptions\n | AngularBuildContextOptions,\n): vite.Plugin {\n const sharedCtx = isAngularBuildContext(optionsOrCtx)\n ? optionsOrCtx\n : isFastCompileOptions(optionsOrCtx)\n ? undefined\n : createAngularBuildContext({\n jit: false,\n ...optionsOrCtx,\n compilationBackend: 'ngp',\n });\n\n const options: FastCompilePluginOptions = sharedCtx\n ? sharedCtx.options\n : (optionsOrCtx as FastCompilePluginOptions);\n\n if (options.jit || options.fastCompileMode === 'partial') {\n throw new Error(\n \"compilation: 'ngp' requires jit: false and fastCompileMode: 'full'.\",\n );\n }\n\n let configContext: TsConfigResolutionContext | undefined;\n let resolvedConfig: vite.ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let componentRegistries: ComponentRegistryEntries[] = [];\n let stylePreprocessor: StylePreprocessor | undefined;\n let watchMode = false;\n let hmr = false;\n let activeBuilds = 0;\n let analyzer: NgpAnalyzer | undefined;\n let compiler: NgpCompiler | undefined;\n let typeChecker: LspTypeChecker | undefined;\n let api: NgpApi;\n let toAnalyzerPath = (path: string) => path;\n let fromAnalyzerPath = vite.normalizePath;\n const filesByPath = new Map<string, { file: NgpFile; chunk: NgpChunk }>();\n const chunkContexts = new Map<NgpChunk, Promise<unknown>>();\n const output = new Map<string, Promise<NgpResult>>();\n const emittedMaps = new Map<string, string>();\n // Last compiled source of each file, compared on edits for HMR\n const sources = new Map<string, string>();\n // Watched files mapped to the source files that depend on them\n const dependents = new Map<string, Set<string>>();\n const hmrUpdateCode = new Map<string, string>();\n const classNames = sharedCtx\n ? sharedCtx.hmr.classNames\n : new Map<string, Set<string>>();\n const fileEmitter = (file: string, className: string) => ({\n hmrUpdateCode: hmrUpdateCode.get(`${file}@${className}`),\n });\n sharedCtx?.hmr.setFileEmitter(fileEmitter);\n\n const componentUpdates: ComponentUpdates = {\n classNames,\n fileEmitter,\n };\n let pending = Promise.resolve();\n const excluded = [\n /node_modules/,\n /[?&]raw\\b/,\n /type=script/,\n /@ng\\/component/,\n ];\n const filter = vite.createFilter(TS_EXT_REGEX, excluded);\n const sourceFilter = vite.createFilter(null, excluded);\n\n // Source formats registered through `api.ngp`, the component registry their\n // lowering looks selectors up in, and their modules by program file\n // (`x.tsrx` → `x.tsrx.ts`)\n const sourceFormats: NgpSourceFormat[] = [];\n const scanner = new ComponentScanner();\n const sourceModules = new Map<string, SourceModule>();\n // Per program file: how often it was removed, which cancels a lowering in\n // progress, and the lowered code the analyzer has\n const removals = new Map<string, number>();\n const analyzed = new Map<string, string>();\n // Which modules of each format NGP compiles: its `include` under the tsconfig's directory\n const includes = new Map<NgpSourceFormat, (file: string) => boolean>();\n const moduleFormatOf = (file: string): NgpSourceFormat | undefined =>\n sourceFormats.find(\n (format) => format.test(file) && includes.get(format)?.(file),\n );\n let devServer: vite.ViteDevServer | undefined;\n // The program files a file change lowered again, for the hot update after it\n const reloweredByChange = new Map<string, string[]>();\n const programFileOf = (file: string): string | undefined => {\n const programFile = `${file}.ts`;\n return sourceModules.has(programFile) ? programFile : undefined;\n };\n const sourceFileOf = (file: string): string =>\n sourceModules.get(file)?.sourceFile ?? file;\n\n function resolveTsConfigPath(): string {\n if (sharedCtx) {\n return sharedCtx.resolveTsConfigPath();\n }\n const ctx = configContext ?? {\n root: resolvedConfig?.root || '.',\n isProd: isProdMode(resolvedConfig?.mode),\n isLib: !!resolvedConfig?.build?.lib,\n };\n return getTsConfigPath(\n ctx.root,\n options.tsconfigGetter(),\n ctx.isProd,\n options.isTest,\n ctx.isLib,\n options.workspaceRoot,\n );\n }\n\n const ngp: NgpCompileApi = {\n registerSourceFormat(format) {\n if (!sourceFormats.includes(format)) {\n sourceFormats.push(format);\n scanner.registerSourceFormat(format);\n }\n },\n };\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: resolveTsConfigPath,\n getSourceMap: (id: string): string | undefined =>\n emittedMaps.get(vite.normalizePath(id)),\n hasEmitted: (id: string): boolean =>\n filesByPath.has(vite.normalizePath(id)),\n output,\n ready: (): Promise<void> => pending,\n componentUpdates,\n ngp,\n };\n\n /** Lowers a module of a source format. Returns whether its TypeScript changed. */\n async function lowerSourceModule(\n sourceFile: string,\n source: string,\n format: NgpSourceFormat,\n resolve: FastCompileResolve,\n ): Promise<boolean> {\n const programFile = `${sourceFile}.ts`;\n if (existsSync(programFile)) {\n throw new Error(\n `[@analogjs/vite-plugin-angular]: ${programFile} has the name NGP compiles ${sourceFile} as. Rename one of them.`,\n );\n }\n const removed = removals.get(programFile);\n const lowered = await format.lower(source, sourceFile, {\n scanImports: (specifiers) =>\n scanner.scanImports(specifiers, sourceFile, resolve),\n resolveSelector: (className, moduleSpecifier, containingFile) =>\n scanner.lookupSelector(\n className,\n sharedCtx?.componentRegistries ?? componentRegistries,\n moduleSpecifier !== undefined\n ? {\n moduleSpecifier,\n containingFile: containingFile ?? sourceFile,\n }\n : undefined,\n ),\n });\n // Removed while it was lowered\n if (removals.get(programFile) !== removed) return false;\n const changed =\n sourceModules.get(programFile)?.lowered.code !== lowered.code;\n sourceModules.set(programFile, { sourceFile, source, format, lowered });\n return changed;\n }\n\n /** Lowers every module of the registered source formats under `root`. */\n async function lowerSourceModules(\n root: string,\n resolve: FastCompileResolve,\n ): Promise<void> {\n scanner.reset(root);\n sourceModules.clear();\n const sourceRoot = vite.normalizePath(realpathSync(root));\n await Promise.all(\n sourceFormats.map(async (format) => {\n includes.set(\n format,\n vite.createFilter(format.include, '**/node_modules/**', {\n resolve: sourceRoot,\n }),\n );\n const files = await glob(format.include, {\n cwd: sourceRoot,\n absolute: true,\n ignore: ['**/node_modules/**'],\n });\n await Promise.all(\n files.map(async (file) => {\n const sourceFile = canonicalPath(file);\n const source = await fsPromises.readFile(sourceFile, 'utf-8');\n await lowerSourceModule(sourceFile, source, format, resolve);\n }),\n );\n }),\n );\n // The analyzer reads them through `hostFs` when it's created\n analyzed.clear();\n for (const [programFile, { lowered }] of sourceModules) {\n analyzed.set(programFile, lowered.code);\n }\n }\n\n /**\n * Lowers the source modules a change to `file` affects again: the module\n * itself, and those that looked up selectors in it. Returns the program\n * files whose TypeScript changed.\n */\n async function relowerSourceModules(\n file: string,\n resolve: FastCompileResolve,\n ): Promise<string[]> {\n const affected = [file, ...(scanner.importersByFile.get(file) ?? [])]\n .map(programFileOf)\n .filter((programFile) => programFile !== undefined);\n scanner.invalidate(file);\n const changed = await Promise.all(\n affected.map(async (programFile) => {\n const sourceModule = sourceModules.get(programFile);\n if (!sourceModule) return [];\n const { sourceFile, format } = sourceModule;\n const source = await readSource(sourceFile);\n if (source === undefined) return [];\n const relowered = await lowerSourceModule(\n sourceFile,\n source,\n format,\n resolve,\n );\n return relowered ? [programFile] : [];\n }),\n );\n return changed.flat();\n }\n\n // Lowering and the analyzer updates that follow it, one change at a time, so\n // the modules a change lowers again reach the analyzer together\n let sourceWork: Promise<unknown> = Promise.resolve();\n function withSourceLock<T>(work: () => Promise<T>): Promise<T> {\n const run = sourceWork.catch(() => undefined).then(work);\n sourceWork = run;\n return run;\n }\n\n /** Sends the analyzer the lowered modules it doesn't have yet. */\n async function syncProgramFiles(): Promise<void> {\n const updates = [...sourceModules]\n .filter(\n ([filePath, { lowered }]) => analyzed.get(filePath) !== lowered.code,\n )\n .map(([filePath, { lowered }]) => ({ filePath, content: lowered.code }));\n if (updates.length === 0) return;\n for (const { filePath, content } of updates)\n analyzed.set(filePath, content);\n await enqueueIndex(() =>\n analyzer!.updateFileContent(\n updates.map(({ filePath, content }) => ({\n filePath: toAnalyzerPath(filePath),\n content,\n })),\n ),\n );\n }\n\n /** Reads a source file, or `undefined` if it was removed. */\n function readSource(file: string): Promise<string | undefined> {\n return fsPromises\n .readFile(file, 'utf-8')\n .catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n }\n\n /** Lowers a module added after the build started, if NGP compiles it. */\n async function addSourceModule(\n sourceFile: string,\n format: NgpSourceFormat,\n source: string,\n resolve: FastCompileResolve,\n ): Promise<void> {\n const programFile = `${sourceFile}.ts`;\n await lowerSourceModule(sourceFile, source, format, resolve);\n const sourceModule = sourceModules.get(programFile);\n // Removed while it was lowered\n if (!sourceModule) return;\n // The analyzer reads it through `hostFs`\n analyzed.set(programFile, sourceModule.lowered.code);\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: toAnalyzerPath(programFile), updateType: FILE_CREATED },\n ]),\n );\n }\n\n /** Drops a removed module, and any lowering of it still in progress. */\n async function removeSourceModule(sourceFile: string): Promise<void> {\n const programFile = `${sourceFile}.ts`;\n removals.set(programFile, (removals.get(programFile) ?? 0) + 1);\n analyzed.delete(programFile);\n if (!sourceModules.delete(programFile)) return;\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: toAnalyzerPath(programFile), updateType: FILE_DELETED },\n ]),\n );\n }\n\n /**\n * Lowers a module for its transform, as fast compile does on every\n * transform, so the selectors it looks up are current. A transform that\n * started before a hot update can carry the previous code; it compiles the\n * latest lowering instead.\n */\n async function lowerForTransform(\n sourceFile: string,\n format: NgpSourceFormat,\n code: string,\n resolve: FastCompileResolve,\n ): Promise<NgpLoweredModule | undefined> {\n const programFile = `${sourceFile}.ts`;\n if (!sourceModules.has(programFile)) {\n // Requested before its `create` event, or added during `vite build --watch`\n await addSourceModule(sourceFile, format, code, resolve);\n } else if (code === (await readSource(sourceFile))) {\n await lowerSourceModule(sourceFile, code, format, resolve);\n }\n return sourceModules.get(programFile)?.lowered;\n }\n\n /** Maps a type error in a program file to the source module's location. */\n function toSourceLocation(location: SourceLocation): SourceLocation {\n const sourceModule = sourceModules.get(vite.normalizePath(location.file));\n const mapped = sourceModule?.lowered.toSourceLocation(\n location.line - 1,\n location.character - 1,\n );\n return mapped\n ? {\n file: sourceModule!.sourceFile,\n line: mapped.line + 1,\n character: mapped.column + 1,\n }\n : location;\n }\n\n sharedCtx?.registerCompiler({\n name: '@analogjs/vite-plugin-angular-ngp',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n async function prepareResources(\n file: NgpFile,\n watch: (path: string) => void,\n ): Promise<NgpFile> {\n const hostFilePath = fromAnalyzerPath(file.filePath);\n watch(hostFilePath);\n const activeConfig = sharedCtx?.resolvedConfig ?? resolvedConfig;\n const activeStylePreprocessor =\n sharedCtx?.stylePreprocessor ?? stylePreprocessor;\n\n return {\n ...file,\n classes: await Promise.all(\n file.classes.map(async (metadata, classIndex) => {\n const component = metadata.component;\n if (!component) return metadata;\n if (component.templateUrl)\n watch(fromAnalyzerPath(component.templateUrl.resolvedPath));\n for (const style of component.styleUrls ?? [])\n watch(fromAnalyzerPath(style.resolvedPath));\n const preprocess = async (\n content: string,\n path: string,\n order: number,\n inline: boolean,\n ) => {\n const preprocessed = preprocessStylesheet(\n content,\n path,\n activeStylePreprocessor,\n {\n filename: path,\n containingFile: hostFilePath,\n resourceFile: inline ? undefined : path,\n className: metadata.className,\n order,\n inline,\n },\n );\n const result = await vite.preprocessCSS(\n preprocessed,\n path,\n activeConfig,\n );\n result.deps?.forEach(watch);\n return result.code;\n };\n return {\n ...metadata,\n component: {\n ...component,\n styles:\n component.styles &&\n (await Promise.all(\n component.styles.map((style, index) =>\n preprocess(\n style,\n `${hostFilePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`,\n index,\n true,\n ),\n ),\n )),\n stylesFromUrls:\n component.stylesFromUrls &&\n (await Promise.all(\n component.stylesFromUrls.map((style, index) =>\n preprocess(\n style,\n fromAnalyzerPath(\n component.styleUrls![index].resolvedPath,\n ),\n index,\n false,\n ),\n ),\n )),\n },\n };\n }),\n ),\n };\n }\n\n async function indexChunks(update?: () => Promise<string[]>): Promise<void> {\n if (update) {\n const invalidated = await update();\n for (const filePath of invalidated) {\n output.delete(fromAnalyzerPath(filePath));\n compiler!.fileCache.delete(filePath);\n }\n chunkContexts.clear();\n } else {\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n const angularOptions = compilerCli.readConfiguration(\n resolveTsConfigPath(),\n ).options as Record<string, unknown>;\n compiler = new api.HybridCompiler(analyzer!, {\n ...angularOptions,\n optimize: true,\n enableHmr: hmr,\n tcbConfig: api.buildTypeCheckingConfig(angularOptions),\n });\n }\n const chunks = update\n ? compiler!.analyzeOptimizedDelta()\n : compiler!.analyzeOptimized();\n for await (const chunk of chunks) {\n for (const file of chunk.files) {\n const normPath = fromAnalyzerPath(file.filePath);\n filesByPath.set(normPath, { file, chunk });\n output.delete(normPath);\n compiler!.fileCache.delete(file.filePath);\n }\n for (const removed of chunk.removedFiles ?? []) {\n const normPath = fromAnalyzerPath(removed);\n filesByPath.delete(normPath);\n output.delete(normPath);\n }\n }\n }\n\n function enqueueIndex(update: () => Promise<string[]>): Promise<void> {\n pending = pending.catch(() => {}).then(() => indexChunks(update));\n return pending;\n }\n\n function getChunkContext(chunk: NgpChunk): Promise<unknown> {\n let context = chunkContexts.get(chunk);\n if (!context) {\n context = compiler!.prepareChunk(chunk);\n chunkContexts.set(chunk, context);\n }\n return context;\n }\n\n async function checkTypes(\n filePath: string,\n sourceCode: string,\n tcbCode?: string | null,\n ): Promise<void> {\n typeChecker ??= new LspTypeChecker(\n resolveTsConfigPath(),\n options.typeChecker,\n {\n inMemoryFiles: () =>\n new Map(\n [...sourceModules].map(([file, { lowered }]) => [\n file,\n lowered.code,\n ]),\n ),\n mapLocation: toSourceLocation,\n },\n );\n typeChecker.queueFile(filePath, sourceCode, tcbCode);\n if (!watchMode) return;\n const typeErrors = await typeChecker.flushQueue(true);\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n }\n\n async function processFile(\n normPath: string,\n activeCompiler: NgpCompiler,\n watch: (path: string) => void,\n ) {\n const { file: analyzed, chunk } = filesByPath.get(normPath)!;\n const [file, context, content] = await Promise.all([\n prepareResources(analyzed, (path) => {\n const key = sourceFileOf(vite.normalizePath(path));\n dependents.set(key, (dependents.get(key) ?? new Set()).add(normPath));\n watch(key);\n }),\n getChunkContext(chunk),\n analyzer!.getFileContent(analyzed.filePath),\n ]);\n sources.set(normPath, content);\n const result =\n activeCompiler.processFile.length >= 5\n ? await activeCompiler.processFile(\n file.filePath,\n content,\n undefined,\n file,\n context,\n )\n : await activeCompiler.processFile(\n file.filePath,\n content,\n file,\n context,\n );\n return { file, content, result };\n }\n\n function compileFile(\n normPath: string,\n watch: (path: string) => void,\n ): Promise<NgpResult> | undefined {\n if (!filesByPath.has(normPath)) return undefined;\n let task = output.get(normPath);\n if (!task) {\n task = (async () => {\n // Analyzer updates queued before this compile land first\n await pending;\n if (!filesByPath.has(normPath)) {\n throw new Error(`${sourceFileOf(normPath)} was removed.`);\n }\n const { file, content, result } = await processFile(\n normPath,\n compiler!,\n watch,\n );\n const errors = [\n ...(file.diagnostics ?? []),\n ...(result.diagnostics ?? []),\n ].filter((diagnostic) => diagnostic.category === 1);\n if (errors.length) {\n throw new Error(\n `${sourceFileOf(normPath)}: ${errors.map((error) => error.messageText).join('\\n')}`,\n );\n }\n if (options.disableTypeChecking !== true) {\n await checkTypes(\n fromAnalyzerPath(file.filePath),\n content,\n result.tcb?.code,\n );\n }\n return result;\n })();\n output.set(normPath, task);\n }\n return task;\n }\n\n function componentNames(normPath: string): string[] {\n return (filesByPath.get(normPath)?.file.classes ?? []).flatMap(\n ({ className, component }) => (component && className ? [className] : []),\n );\n }\n\n // Components to update in place, following the Angular CLI's rule\n async function findComponentUpdates(\n normPath: string,\n read: () => string | Promise<string>,\n ): Promise<ComponentUpdate[]> {\n if (!TS_EXT_REGEX.test(normPath)) {\n return [...(dependents.get(normPath) ?? [])].flatMap((file) =>\n componentNames(file).map((className) => ({ file, className })),\n );\n }\n const stale = sources.get(normPath);\n if (stale === undefined) return [];\n const matchedClassNames = findHmrComponentUpdates(\n normPath,\n stale,\n await read(),\n new Set(componentNames(normPath)),\n );\n return (matchedClassNames ?? []).map((className) => ({\n file: normPath,\n className,\n }));\n }\n\n async function emitHmrUpdate(file: string, className: string) {\n // NGP emits only the update module of the class named by `hmrUpdateTarget`,\n // and only when it doesn't reuse the file's previously processed output\n const target = Object.assign(\n Object.create(Object.getPrototypeOf(compiler)),\n compiler,\n { hmrUpdateTarget: className, reuseProcessedFiles: false },\n );\n const { result } = await processFile(file, target, () => {});\n return (\n result.hmrUpdateModule &&\n (await transpile(result.hmrUpdateModule, file)).code\n );\n }\n\n async function sendComponentUpdates(\n updates: ComponentUpdate[],\n server: vite.ViteDevServer,\n ): Promise<boolean> {\n try {\n for (const file of new Set(updates.map((update) => update.file))) {\n await compileFile(file, () => {});\n }\n const codes = await Promise.all(\n updates.map(({ file, className }) => emitHmrUpdate(file, className)),\n );\n if (codes.some((code) => !code)) return false;\n updates.forEach(({ file, className }, index) => {\n // Components of a source module update through the module itself\n const sourceFile = sourceModules.get(file)?.sourceFile;\n const moduleFile = sourceFile ?? file;\n hmrUpdateCode.set(`${moduleFile}@${className}`, codes[index]!);\n let fileClasses = componentUpdates.classNames.get(moduleFile);\n if (!fileClasses) {\n fileClasses = new Set<string>();\n componentUpdates.classNames.set(moduleFile, fileClasses);\n }\n fileClasses.add(className);\n server.moduleGraph\n .getModulesByFile(moduleFile)\n ?.forEach((mod) => server.moduleGraph.invalidateModule(mod));\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(`${moduleFile}@${className}`),\n timestamp: Date.now(),\n });\n });\n return true;\n } catch {\n // A full reload reports the compilation error\n return false;\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-ngp',\n enforce: 'pre',\n api: compilerApi,\n config(config, { command, mode }) {\n watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n if (sharedCtx) {\n sharedCtx.initConfig(config, { command, mode });\n } else {\n configContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config.build?.lib,\n };\n }\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: resolveTsConfigPath(),\n isProd,\n jit: false,\n watchMode,\n isTest: options.isTest,\n isAstroIntegration: options.isAstroIntegration,\n });\n return {\n ...(isRolldown() ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n hmr =\n watchMode &&\n options.liveReload &&\n !options.isTest &&\n config.server.hmr !== false;\n const integrations = sharedCtx\n ? await sharedCtx.resolveConfig(config)\n : await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n componentRegistries = integrations.componentRegistries;\n stylePreprocessor = integrations.stylePreprocessor;\n },\n configureServer(server) {\n const changeTypes: Record<string, FileChangeType> = {\n add: 1,\n change: 2,\n unlink: 3,\n };\n devServer = server;\n server.watcher.on('all', (event, path) => {\n const type = changeTypes[event];\n if (type) typeChecker?.notifyFileChanged(path, type);\n });\n server.httpServer?.on('close', () => {\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n });\n },\n // Runs on the dev server with or without HMR, and in `vite build --watch`\n async watchChange(id, { event }) {\n if (!analyzer || sourceFormats.length === 0) return;\n const file = canonicalPath(id);\n const resolve: FastCompileResolve = (spec, importer) =>\n this.resolve(spec, importer, { skipSelf: true });\n await withSourceLock(async () => {\n scanner.invalidate(file);\n const format = moduleFormatOf(file);\n if (event === 'update') {\n reloweredByChange.set(\n file,\n await relowerSourceModules(file, resolve),\n );\n } else if (event === 'delete') {\n await removeSourceModule(file);\n } else if (\n event === 'create' &&\n format &&\n !sourceModules.has(`${file}.ts`)\n ) {\n const source = await readSource(file);\n if (source !== undefined) {\n await addSourceModule(file, format, source, resolve);\n }\n }\n await syncProgramFiles();\n });\n // Modules that looked up selectors in `file` lower again when transformed\n for (const importer of scanner.importersByFile.get(file) ?? []) {\n devServer?.moduleGraph\n .getModulesByFile(importer)\n ?.forEach((mod) => devServer!.moduleGraph.invalidateModule(mod));\n }\n },\n async buildStart() {\n activeBuilds++;\n if (!analyzer) {\n const tsconfig = resolveTsConfigPath();\n const hasSourceFormats = sourceFormats.length > 0;\n const ngp = await loadNgp(tsconfig, hasSourceFormats);\n const isWasm = ngp.analyzerOptions.backend === 'wasm';\n toAnalyzerPath = isWasm ? toWasmPath : (path) => path;\n fromAnalyzerPath = isWasm ? fromWasmPath : vite.normalizePath;\n api = ngp.api;\n if (hasSourceFormats) {\n await lowerSourceModules(dirname(tsconfig), (specifier, importer) =>\n this.resolve(specifier, importer, { skipSelf: true }),\n );\n }\n analyzer = await api.createAnalyzer(toAnalyzerPath(tsconfig), {\n ...ngp.analyzerOptions,\n enableHmr: hmr,\n hostFs:\n hasSourceFormats || isWasm\n ? createNgpHostFs(\n hasSourceFormats\n ? (path) => sourceModules.get(path)?.lowered.code\n : undefined,\n )\n : undefined,\n });\n pending = indexChunks();\n }\n await pending;\n for (const path of dependents.keys()) {\n this.addWatchFile(path);\n }\n },\n resolveId(id, importer) {\n return resolveAngularVirtualId(id, importer, {\n jit: false,\n resolvedConfig: sharedCtx?.resolvedConfig ?? resolvedConfig,\n });\n },\n async load(id) {\n return loadAngularVirtualModule(\n this,\n id,\n sharedCtx?.resolvedConfig ?? resolvedConfig,\n );\n },\n async transform(code, id) {\n const activeTransformFilter =\n sharedCtx?.transformFilter ?? transformFilter;\n const filePath = vite.normalizePath(id.split('?')[0]);\n const sourceFormat = scanner.sourceFormatOf(filePath);\n if (\n !(sourceFormat ? sourceFilter(id) : filter(id)) ||\n activeTransformFilter?.(code, id) === false\n ) {\n return;\n }\n await pending;\n let lowered: NgpLoweredModule | undefined;\n let compiledFile = filePath;\n if (sourceFormat) {\n const sourceFile = canonicalPath(filePath);\n const format = moduleFormatOf(sourceFile);\n if (!format) {\n this.error(\n `${filePath} is outside ${dirname(resolveTsConfigPath())}, where '${sourceFormat.name}' modules are compiled from.`,\n );\n }\n lowered = await withSourceLock(async () => {\n const result = await lowerForTransform(\n sourceFile,\n format,\n code,\n (spec, importer) =>\n this.resolve(spec, importer, { skipSelf: true }),\n );\n await syncProgramFiles();\n return result;\n });\n if (!lowered) {\n this.error(`${filePath} was removed while it was compiled.`);\n }\n if (lowered.error) {\n this.error({\n message: lowered.error.message,\n id: filePath,\n loc: lowered.error.loc && { file: filePath, ...lowered.error.loc },\n });\n }\n compiledFile = `${sourceFile}.ts`;\n // Transform the module again when a component it looked up changes\n for (const dependency of scanner.dependenciesOf(sourceFile)) {\n this.addWatchFile(dependency);\n }\n }\n const compiledCode = lowered ? lowered.code : code;\n const watch = (path: string) => this.addWatchFile(path);\n let result: NgpResult | undefined;\n try {\n result = await compileFile(compiledFile, watch);\n } catch (error) {\n // A failed compile stays cached until its file is updated, so only\n // report it if it compiled this content\n if (\n !sources.has(compiledFile) ||\n sources.get(compiledFile) === compiledCode\n ) {\n throw error;\n }\n }\n if (\n filesByPath.has(compiledFile) &&\n sources.get(compiledFile) !== compiledCode\n ) {\n if (lowered) analyzed.set(compiledFile, compiledCode);\n await enqueueIndex(() =>\n analyzer!.updateFileContent([\n {\n filePath: toAnalyzerPath(compiledFile),\n content: compiledCode,\n },\n ]),\n );\n result = await compileFile(compiledFile, watch);\n } else if (!result && lowered) {\n this.error(\n `${filePath} is not part of the TypeScript program of ${resolveTsConfigPath()}. Import it, or add it to the tsconfig's \\`include\\`.`,\n );\n } else if (!result && options.disableTypeChecking !== true) {\n await checkTypes(filePath, code);\n }\n let source = result?.magicString.toString() ?? code;\n if (result) {\n const analyzerFile = filesByPath.get(compiledFile)!.file.filePath;\n if (analyzerFile !== filePath) {\n // Component HMR ids name the analyzer's file; the dev server knows the module\n source = source.replaceAll(\n encodeURIComponent(`${analyzerFile}@`),\n encodeURIComponent(`${filePath}@`),\n );\n }\n }\n const map = result?.magicString.generateMap({\n source: compiledFile,\n includeContent: true,\n hires: true,\n });\n const transpiled = await transpile(source, compiledFile, map);\n const outputMap =\n lowered && transpiled.map\n ? lowered.mapToSource(JSON.stringify(transpiled.map))\n : transpiled.map;\n if (outputMap) {\n emittedMaps.set(\n filePath,\n typeof outputMap === 'string' ? outputMap : JSON.stringify(outputMap),\n );\n }\n return {\n code: transpiled.code,\n map: outputMap as vite.Rollup.SourceMapInput,\n };\n },\n async handleHotUpdate(ctx) {\n if (\n sharedCtx\n ? sharedCtx.hmr.isIgnoredFile(ctx.file)\n : isIgnoredHmrFile(ctx.file)\n ) {\n return [];\n }\n const normPath = vite.normalizePath(ctx.file);\n const sourceFile = canonicalPath(ctx.file);\n const programFile = programFileOf(sourceFile);\n const updates = await withSourceLock(async () => {\n // Lowered again in `watchChange`, which runs first\n const relowered = reloweredByChange.get(sourceFile) ?? [];\n reloweredByChange.delete(sourceFile);\n const lowered = programFile\n ? sourceModules.get(programFile)?.lowered\n : undefined;\n // In place only for a module that lowered without errors, which no\n // other module was lowered again against\n const componentUpdates =\n hmr &&\n !lowered?.error &&\n relowered.every((file) => file === programFile)\n ? await findComponentUpdates(\n programFile ?? normPath,\n lowered ? () => lowered.code : ctx.read,\n )\n : [];\n if (!programFile) {\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: toAnalyzerPath(ctx.file), updateType: FILE_CHANGED },\n ]),\n );\n }\n await syncProgramFiles();\n return componentUpdates;\n });\n if (updates.length && (await sendComponentUpdates(updates, ctx.server))) {\n return [];\n }\n hmrUpdateCode.clear();\n componentUpdates.classNames.clear();\n ctx.server.moduleGraph.invalidateAll();\n ctx.server.ws.send({ type: 'full-reload' });\n return [];\n },\n async buildEnd(error) {\n if (error || watchMode || !typeChecker) return;\n const typeErrors = await typeChecker.flushQueue();\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n },\n async closeBundle() {\n activeBuilds = Math.max(0, activeBuilds - 1);\n if (watchMode || activeBuilds > 0) return;\n await pending.catch(() => {});\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n emittedMaps.clear();\n sources.clear();\n dependents.clear();\n sourceModules.clear();\n analyzed.clear();\n releaseCssPreprocessorWorkers();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;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