@analogjs/vite-plugin-angular 3.0.0-beta.13 → 3.0.0-beta.15

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,4 +1,5 @@
1
1
  import { Plugin } from "vite";
2
+ import type { TypeCheckerOption } from "./utils/lsp-type-checker.js";
2
3
  export interface FastCompilePluginOptions {
3
4
  tsconfigGetter: () => string;
4
5
  workspaceRoot: string;
@@ -8,6 +9,8 @@ export interface FastCompilePluginOptions {
8
9
  isTest: boolean;
9
10
  isAstroIntegration: boolean;
10
11
  fastCompileMode?: "full" | "partial";
12
+ disableTypeChecking?: boolean;
13
+ typeChecker?: TypeCheckerOption;
11
14
  }
12
15
  /**
13
16
  * Directory that `compilerOptions.paths` targets resolve against. Mirrors
@@ -1 +1 @@
1
- {"version":3,"file":"fast-compile-plugin.js","names":[],"sources":["../../../src/lib/fast-compile-plugin.ts"],"sourcesContent":["import { promises as fsPromises } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { parseSync } from 'oxc-parser';\nimport * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport { normalizePath, Plugin, preprocessCSS, ResolvedConfig } from 'vite';\n\nimport {\n compile,\n scanFile,\n declaresNonStandaloneComponent,\n scanPackageDts,\n collectImportedPackages,\n collectRelativeReExports,\n collectReExports,\n collectAllImports,\n jitTransform,\n inlineResourceUrls,\n extractInlineStyles,\n generateHmrCode,\n debugCompile,\n debugRegistry,\n ANGULAR_DECORATOR_CALL_RE,\n type ComponentRegistry,\n} from './compiler/index.js';\n\nimport {\n TS_EXT_REGEX,\n EXCLUDED_TS_EXT_REGEX,\n getTsConfigPath,\n createDepOptimizerConfig,\n isProdMode,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { VIRTUAL_RAW_PREFIX, toVirtualRawId } from './utils/virtual-ids.js';\nimport {\n loadVirtualRawModule,\n rewriteHtmlRawImport,\n} from './utils/virtual-resources.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\nimport {\n discoverAnalogIntegrations,\n type ComponentRegistryEntries,\n type TransformFilter,\n} from './analog-plugin-interop.js';\n\nexport interface FastCompilePluginOptions {\n tsconfigGetter: () => string;\n workspaceRoot: string;\n inlineStylesExtension: string;\n jit: boolean;\n liveReload: boolean;\n isTest: boolean;\n isAstroIntegration: boolean;\n fastCompileMode?: 'full' | 'partial';\n}\n\ntype ResolveImport = (spec: string, importer: string) => Promise<string | null>;\n\n/**\n * Directory that `compilerOptions.paths` targets resolve against. Mirrors\n * TypeScript: `baseUrl` when set, otherwise the directory of the config\n * that declares `paths` (`pathsBasePath`, since `baseUrl` is optional\n * from TS 4.1).\n */\nexport function getPathsBasePath(\n options: { baseUrl?: string; pathsBasePath?: string } | undefined,\n fallback: string,\n): string {\n return options?.baseUrl ?? options?.pathsBasePath ?? fallback;\n}\n\nexport function fastCompilePlugin(\n pluginOptions: FastCompilePluginOptions,\n): Plugin {\n let resolvedConfig: ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let componentRegistries: ComponentRegistryEntries[] = [];\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n let watchMode = false;\n\n // fast-compile plugin state\n const registry: ComponentRegistry = new Map();\n const resourceToSource = new Map<string, string>();\n const scannedDtsPackages = new Set<string>();\n let projectRoot = '';\n let useDefineForClassFields = true;\n let tsConfig: ReturnType<typeof compilerCli.readConfiguration>;\n\n // Files scanned on demand (mapped to the barrel chain they pulled in), which\n // modules were compiled against each scanned file, and the one-time\n // whole-project scan non-standalone components fall back to.\n const lazyScans = new Map<string, Promise<Set<string>>>();\n const importersByFile = new Map<string, Set<string>>();\n let projectScan: Promise<void> | undefined;\n\n /**\n * Scan a file into the registry, then recursively walk its relative\n * `export *` / `export { … } from './x'` chain so any underlying\n * directive classes also land in the registry. Used both at\n * `buildStart` (for tsconfig path entries) and at dev time (file\n * `add` and `handleHotUpdate`) so newly added barrels stay in sync\n * without requiring a server restart.\n *\n * The `visited` set prevents infinite recursion within a single\n * top-level call. Each fresh scan should pass an empty set (so HMR\n * re-scans aren't blocked by buildStart's earlier visits).\n *\n * `fileContents`/`scanResults` are cold-start dedup caches scoped to a\n * single `initFastCompile` call. HMR/watcher callers must omit them so\n * an edited file is always re-read from disk.\n */\n async function scanBarrelExports(\n file: string,\n visited: Set<string> = new Set(),\n overwrite = false,\n fileContents?: Map<string, string>,\n scanResults?: Map<string, ReturnType<typeof scanFile>>,\n ): Promise<void> {\n if (visited.has(file)) return;\n visited.add(file);\n let code: string;\n try {\n code =\n fileContents?.get(file) ?? (await fsPromises.readFile(file, 'utf-8'));\n fileContents?.set(file, code);\n } catch (e) {\n if (debugRegistry.enabled) {\n debugRegistry(\n 'scanBarrelExports: failed to read %s: %s',\n file,\n (e as Error)?.message,\n );\n }\n return;\n }\n // Single parse shared by scanFile and collectRelativeReExports. On a\n // parse error each consumer re-parses on its own, preserving their\n // individual failure semantics (scanFile throws past its pre-filter;\n // collectRelativeReExports swallows and returns []).\n let program: ReturnType<typeof parseSync>['program'] | undefined;\n try {\n program = parseSync(file, code).program;\n } catch {\n program = undefined;\n }\n let entries = scanResults?.get(file);\n if (!entries) {\n entries = scanFile(code, file, program);\n scanResults?.set(file, entries);\n }\n for (const entry of entries) {\n // At buildStart we want stable registry entries (don't overwrite\n // an earlier scan with a barrel re-scan); HMR explicitly asks\n // for overwrite so updated metadata replaces stale entries.\n if (overwrite || !registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n // Collect every relative re-export specifier via OXC AST so\n // recursive scans can't trip over each other (a shared `/g` regex\n // would have its `lastIndex` reset by each recursive call and\n // silently skip half of an outer barrel's re-exports, which\n // previously left directives like `HlmRadioGroup` unregistered).\n const dir = dirname(file);\n for (const rel of collectRelativeReExports(code, file, program)) {\n // NodeNext-style libraries write `export * from './foo.js'`\n // even though the source is `./foo.ts`. Strip the ESM\n // extension before probing or the candidates would be\n // `foo.js.ts` / `foo.js/index.ts`, which never exist.\n const normalizedRel = rel.replace(/\\.(?:js|mjs)$/u, '');\n const reExportCandidates = [\n resolve(dir, normalizedRel + '.ts'),\n resolve(dir, normalizedRel, 'index.ts'),\n ];\n let resolved = false;\n for (const candidate of reExportCandidates) {\n try {\n await fsPromises.access(candidate);\n await scanBarrelExports(\n candidate,\n visited,\n overwrite,\n fileContents,\n scanResults,\n );\n resolved = true;\n break;\n } catch {\n // try next candidate\n }\n }\n if (!resolved && debugRegistry.enabled) {\n debugRegistry(\n 'scanBarrelExports: %s re-export %s did not resolve to %o',\n file,\n rel,\n reExportCandidates,\n );\n }\n }\n }\n\n async function initFastCompile() {\n if (pluginOptions.jit) return; // JIT: no registry scan needed\n\n registry.clear();\n scannedDtsPackages.clear();\n lazyScans.clear();\n importersByFile.clear();\n projectScan = undefined;\n const resolvedTsConfigPath = resolveTsConfigPath();\n projectRoot = dirname(resolvedTsConfigPath);\n tsConfig = compilerCli.readConfiguration(resolvedTsConfigPath);\n useDefineForClassFields = tsConfig.options?.useDefineForClassFields ?? true;\n }\n\n /** Scan all source files reachable from the tsconfig into the registry. */\n async function scanProject() {\n const config = tsConfig;\n // Collect candidate files: tsconfig rootNames PLUS the entry points\n // named in `compilerOptions.paths`. App tsconfigs typically only\n // include the app's own sources, so workspace library entry barrels\n // (e.g. `HlmSelectImports = [HlmSelect, HlmSelectContent, ...] as\n // const`) live outside `rootNames` and would otherwise miss the\n // initial scan. The compiler then can't see that `HlmSelectImports`\n // is a tuple barrel and emits the bare identifier into the parent\n // component's `dependencies()` list, where Angular's runtime\n // silently drops it because arrays don't have a directive def.\n const candidates = new Set<string>(config.rootNames);\n const tsPaths = config.options?.paths;\n const baseUrl = getPathsBasePath(config.options, projectRoot);\n // Cold-start dedup caches shared by the three scan phases below\n // (candidates scan, walkImports, scanBarrelExports). Scoped to this\n // init call only — HMR/watcher re-scans must hit disk fresh.\n const fileContents = new Map<string, string>();\n const scanResults = new Map<string, ReturnType<typeof scanFile>>();\n if (tsPaths) {\n for (const targets of Object.values(tsPaths)) {\n for (const target of targets as string[]) {\n // Skip wildcard patterns — entry barrels are normally exact\n // file paths like \"libs/helm/select/src/index.ts\".\n if (target.includes('*')) continue;\n candidates.add(resolve(baseUrl, target));\n }\n }\n }\n const results = await Promise.all(\n Array.from(candidates).map(async (file) => {\n try {\n const code = await fsPromises.readFile(file, 'utf-8');\n fileContents.set(file, code);\n const entries = scanFile(code, file);\n scanResults.set(file, entries);\n return entries;\n } catch (e) {\n if (debugRegistry.enabled) {\n debugRegistry(\n 'initFastCompile: skipping unreadable %s: %s',\n file,\n (e as Error)?.message,\n );\n }\n return []; // Skip unreadable files\n }\n }),\n );\n\n for (const entries of results) {\n for (const entry of entries) {\n registry.set(entry.className, entry);\n }\n }\n\n // Walk the transitive import graph from the root files so the registry also\n // contains declarations that live in files not directly in tsconfig\n // `files`/`include` (transitively-imported app sources) and in workspace\n // libraries reached through wildcard `paths` (e.g. `@bitwarden/*`). Without\n // this, a non-standalone component's owning module can't classify its\n // declarations and `ɵɵsetComponentScope` is never emitted for it. Only\n // relative imports and `paths`-mapped (project/workspace) bare specifiers are\n // followed; true `node_modules` packages are left to the lazy `.d.ts` scanner.\n // Return *all* candidate base paths a bare specifier maps to. A `paths`\n // entry can list several fallback targets (e.g. a built `dist` path first\n // and the workspace `src` second); the caller probes them in order.\n const resolvePathSpecifier = (spec: string): string[] => {\n if (!tsPaths) return [];\n for (const [key, targets] of Object.entries(tsPaths)) {\n const list = targets as string[];\n if (key.endsWith('/*')) {\n const prefix = key.slice(0, -1);\n if (spec.startsWith(prefix)) {\n // `split('*').join(...)` substitutes the single tsconfig `*`\n // wildcard without `String.replace`'s first-match-only behavior or\n // `$`-pattern interpretation of the replacement.\n return list.map((t) =>\n resolve(baseUrl, t.split('*').join(spec.slice(prefix.length))),\n );\n }\n } else if (key === spec) {\n return list.map((t) => resolve(baseUrl, t));\n }\n }\n return [];\n };\n const probeToSource = async (base: string): Promise<string | null> => {\n const candidates = base.endsWith('.ts')\n ? [base]\n : [base + '.ts', resolve(base, 'index.ts')];\n for (const candidate of candidates) {\n try {\n await fsPromises.access(candidate);\n return candidate;\n } catch {\n // try next candidate\n }\n }\n return null;\n };\n // Memoize fs probes per absolute base path. The cache stores the\n // Promise (not the settled value) so concurrent walks racing on the\n // same base collapse into a single probe.\n const baseResolveCache = new Map<string, Promise<string | null>>();\n const resolveToSource = (base: string): Promise<string | null> => {\n let probe = baseResolveCache.get(base);\n if (!probe) {\n probe = probeToSource(base);\n baseResolveCache.set(base, probe);\n }\n return probe;\n };\n // Probe each `paths` target in order; first one that resolves to source wins.\n const resolveFirstSource = async (\n bases: string[],\n ): Promise<string | null> => {\n for (const base of bases) {\n const resolved = await resolveToSource(base);\n if (resolved) return resolved;\n }\n return null;\n };\n const importWalkVisited = new Set<string>();\n // Paths-mapped resolution doesn't depend on the importer, so bare\n // specifiers can be memoized by their raw text. Relative specifiers\n // must NOT be — the same './foo' resolves differently per directory.\n const bareSpecResolveCache = new Map<string, Promise<string | null>>();\n const walkImports = async (file: string): Promise<void> => {\n if (importWalkVisited.has(file)) return;\n importWalkVisited.add(file);\n let code: string;\n try {\n code =\n fileContents.get(file) ?? (await fsPromises.readFile(file, 'utf-8'));\n fileContents.set(file, code);\n } catch {\n return;\n }\n // Single parse shared by scanFile, collectImportedPackages, and\n // collectAllImports. On a parse error each consumer re-parses on\n // its own, preserving their individual failure semantics.\n let program: ReturnType<typeof parseSync>['program'] | undefined;\n try {\n program = parseSync(file, code).program;\n } catch {\n program = undefined;\n }\n let entries = scanResults.get(file);\n if (!entries) {\n entries = scanFile(code, file, program);\n scanResults.set(file, entries);\n }\n for (const entry of entries) {\n if (!registry.has(entry.className))\n registry.set(entry.className, entry);\n }\n // Pre-scan the `.d.ts` of every external package this file imports (and,\n // transitively, packages those packages' NgModules re-export — e.g.\n // BrowserModule → CommonModule → NgIf). Doing this at buildStart means the\n // registry is complete before any component transforms, so non-standalone\n // component scope resolves regardless of file transform order.\n for (const pkg of collectImportedPackages(code, file, program)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n try {\n for (const entry of scanPackageDts(\n pkg,\n projectRoot,\n scannedDtsPackages,\n )) {\n if (!registry.has(entry.className))\n registry.set(entry.className, entry);\n }\n } catch {\n // Package may not have .d.ts or not be Angular\n }\n }\n const dir = dirname(file);\n const targets = await Promise.all(\n collectAllImports(code, file, program).map((spec) => {\n if (spec.startsWith('.')) {\n return resolveToSource(\n resolve(dir, spec.replace(/\\.(?:js|mjs)$/u, '')),\n );\n }\n let resolved = bareSpecResolveCache.get(spec);\n if (!resolved) {\n resolved = resolveFirstSource(resolvePathSpecifier(spec));\n bareSpecResolveCache.set(spec, resolved);\n }\n return resolved;\n }),\n );\n await Promise.all(\n targets.filter((t): t is string => !!t).map((t) => walkImports(t)),\n );\n };\n await Promise.all(config.rootNames.map((file) => walkImports(file)));\n\n // Library barrels typically `export * from './lib/...'` rather than\n // declaring directives directly, so the entry file alone gives us\n // the tuple consts but not the directive classes they reference.\n // Walk the relative `export *` chain so the underlying classes also\n // land in the registry. Use a SHARED visited set across all\n // barrels so recursive walks don't double-scan a file that's\n // re-exported from multiple entry points.\n const buildStartVisited = new Set<string>();\n if (tsPaths) {\n const barrelCandidates: string[] = [];\n for (const targets of Object.values(tsPaths)) {\n for (const target of targets as string[]) {\n if (target.includes('*')) continue;\n barrelCandidates.push(resolve(baseUrl, target));\n }\n }\n await Promise.all(\n barrelCandidates.map((c) =>\n scanBarrelExports(\n c,\n buildStartVisited,\n false,\n fileContents,\n scanResults,\n ),\n ),\n );\n }\n debugRegistry(\n 'initFastCompile done: %d entries from %d candidate files',\n registry.size,\n candidates.size,\n );\n }\n\n function ensureDtsRegistryForSource(\n code: string,\n id: string,\n program?: ReturnType<typeof parseSync>['program'],\n ) {\n for (const pkg of collectImportedPackages(code, id, program)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n\n try {\n const dtsEntries = scanPackageDts(pkg, projectRoot, scannedDtsPackages);\n for (const entry of dtsEntries) {\n if (!registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n } catch {\n // Package may not have .d.ts files or may not be Angular\n }\n }\n }\n\n /**\n * Scan the source files `id` imports into the registry on demand and record\n * `id` as their importer, so a metadata change in any of them recompiles it.\n */\n async function resolveImportedDeclarations(\n code: string,\n id: string,\n program: ReturnType<typeof parseSync>['program'],\n resolveImport: ResolveImport,\n ) {\n await Promise.all(\n collectAllImports(code, id, program).map(async (spec) => {\n const file = await resolveImport(spec, id);\n if (!file) return;\n for (const scanned of await scanOnDemand(file, resolveImport)) {\n let importers = importersByFile.get(scanned);\n if (!importers) {\n importers = new Set();\n importersByFile.set(scanned, importers);\n }\n importers.add(id);\n }\n }),\n );\n }\n\n function scanOnDemand(\n file: string,\n resolveImport: ResolveImport,\n ): Promise<Set<string>> {\n let scan = lazyScans.get(file);\n if (!scan) {\n scan = scanWithReExports(file, resolveImport);\n lazyScans.set(file, scan);\n }\n return scan;\n }\n\n /**\n * Scan a file and everything it re-exports, resolving specifiers through\n * Vite so path aliases work. Tuple barrels and NgModules can list classes\n * their file imports without re-exporting, so their imports are followed\n * too. Returns every file scanned.\n */\n async function scanWithReExports(\n file: string,\n resolveImport: ResolveImport,\n ): Promise<Set<string>> {\n const visited = new Set<string>();\n const visit = async (current: string): Promise<void> => {\n if (visited.has(current)) return;\n visited.add(current);\n let code: string;\n let program: ReturnType<typeof parseSync>['program'];\n try {\n code = await fsPromises.readFile(current, 'utf-8');\n program = parseSync(current, code).program;\n } catch {\n return;\n }\n const entries = scanFile(code, current, program);\n for (const entry of entries) {\n if (!registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n ensureDtsRegistryForSource(code, current, program);\n const followsImports = entries.some(\n (e) => e.kind === 'tuple' || e.kind === 'ngmodule',\n );\n const specifiers = followsImports\n ? collectAllImports(code, current, program)\n : collectReExports(code, current, program);\n for (const spec of specifiers) {\n const dep = await resolveImport(spec, current);\n if (dep) await visit(dep);\n }\n };\n await visit(file);\n return visited;\n }\n\n function registryEntriesOf(file: string) {\n return [...registry.values()].filter((e) => e.fileName === file);\n }\n\n async function handleFastCompileTransform(\n code: string,\n id: string,\n resolveImport: ResolveImport,\n ): Promise<{ code: string; map: any } | undefined> {\n if (!ANGULAR_DECORATOR_CALL_RE.test(code)) {\n // Non-Angular file — strip TS-only syntax ourselves so barrels\n // like `export { Foo, type Bar } from './x'` and other TS-only\n // forms don't leak unstripped to Rolldown. In rolldown-vite the\n // built-in `vite:oxc` strip is registered as a Rust-side native\n // plugin (`viteTransformPlugin` from `rolldown/experimental`); if\n // its hook-filter treats files our `transform.filter.id.include`\n // claimed as already-handled, no JS-side fallback runs and raw\n // TS reaches the parser → `SyntaxError: Unexpected identifier`.\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(code, id, {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n })\n : await vite.transformWithEsbuild(code, id, {\n loader: 'ts',\n sourcemap: true,\n });\n return { code: stripped.code, map: stripped.map };\n }\n\n // JIT mode\n if (pluginOptions.jit) {\n const result = jitTransform(code, id);\n // Strip TypeScript-only syntax (e.g. `readonly`, parameter property\n // modifiers, type annotations on fields) so the output is valid JS\n // for Rolldown. `angularVitestSourcemapPlugin` normally runs this\n // strip downstream in tests, but it is intentionally skipped on\n // StackBlitz / WebContainer — and the production build pipeline\n // does not register it either — so the JIT path must self-strip\n // to stay safe across environments.\n //\n // Pass the jitTransform map as `inMap` so OXC/esbuild emit a map\n // composed with the original `.ts` source — without this, debug\n // stack traces and breakpoints land on the wrong lines once the\n // strip removes any TS-only token. `jitTransform` returns\n // `map: null` for files with no Angular class (no edits made);\n // passing that to OXC/esbuild as `inMap` throws, so coerce to\n // `undefined` in that case.\n const inMap = result.map ?? undefined;\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(\n result.code,\n id,\n {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n },\n inMap,\n )\n : await vite.transformWithEsbuild(\n result.code,\n id,\n { loader: 'ts', sourcemap: true },\n inMap,\n );\n return { code: stripped.code, map: stripped.map };\n }\n\n // Inline external templateUrl/styleUrl(s) into the source before compilation.\n // `styleExtensions` carries the source extension of each inlined external\n // style so it can be preprocessed by its own file type (e.g. an external\n // `.scss` styleUrl) regardless of the `inlineStylesExtension` option.\n const inlined = await inlineResourceUrls(code, id);\n code = inlined.code;\n const { styleExtensions } = inlined;\n\n // Track inlined resources for HMR. `compile()` only reports resources it\n // reads through its own fallback (a templateUrl/styleUrl the inliner did\n // NOT already inline), so files inlined here must be recorded here or a\n // later edit to them never invalidates the owning module.\n for (const dep of inlined.resourceDependencies) {\n resourceToSource.set(dep, id);\n }\n\n // Single OXC parse of the post-inline source, shared by every AST\n // consumer below. `inlineResourceUrls` parsed the PRE-inline string,\n // so its program can never be reused here.\n const { program: oxcProgram } = parseSync(id, code);\n\n // Pre-resolve inline styles that need preprocessing (SCSS/Sass/Less). Run\n // whenever a style needs a non-`css` preprocessor — either the configured\n // `inlineStylesExtension` for truly-inline styles, or an external styleUrl's\n // own extension.\n let resolvedInlineStyles: Map<number, string> | undefined;\n\n const inlineExt = pluginOptions.inlineStylesExtension;\n const styleNeedsPreprocess = (ext: string) => ext !== '' && ext !== 'css';\n\n if (styleNeedsPreprocess(inlineExt) || styleExtensions.size > 0) {\n const styleStrings = extractInlineStyles(code, id, oxcProgram);\n\n if (styleStrings.length > 0) {\n resolvedInlineStyles = new Map();\n for (let i = 0; i < styleStrings.length; i++) {\n // External styleUrls are preprocessed by their own extension; truly\n // inline `styles: [...]` fall back to `inlineStylesExtension`.\n const ext = styleExtensions.get(i) ?? inlineExt;\n if (!styleNeedsPreprocess(ext)) continue;\n try {\n const fakePath = id.replace(/\\.ts$/, `.inline-${i}.${ext}`);\n const processed = await preprocessCSS(\n styleStrings[i],\n fakePath,\n resolvedConfig,\n );\n resolvedInlineStyles.set(i, processed.code);\n } catch (e) {\n if (debugCompile.enabled) {\n debugCompile(\n 'inline style #%d preprocessing failed in %s: %s',\n i,\n id,\n (e as Error)?.message,\n );\n }\n // Skip styles that can't be preprocessed\n }\n }\n if (resolvedInlineStyles.size === 0) resolvedInlineStyles = undefined;\n }\n }\n\n ensureDtsRegistryForSource(code, id, oxcProgram);\n\n for (const entry of scanFile(code, id, oxcProgram)) {\n registry.set(entry.className, entry);\n }\n await resolveImportedDeclarations(code, id, oxcProgram, resolveImport);\n if (declaresNonStandaloneComponent(oxcProgram)) {\n projectScan ??= scanProject();\n await projectScan;\n }\n\n // Merge registries contributed through `analog.setup()` into this\n // compile's lookup view. Out-of-tree compilers register directive\n // metadata for classes fastCompile can't reach through its\n // tsconfig-driven scan (e.g. `.tsrx` files compiled by `@tsrx/analog`).\n // Without this merge, a TS `@Component({ imports: [X] })` that\n // references such a class hits `_unresolved-${className}` as its\n // selector and the tag never matches at runtime.\n let compileRegistry: ComponentRegistry = registry;\n if (componentRegistries.some((external) => external.size > 0)) {\n compileRegistry = new Map(registry);\n for (const external of componentRegistries) {\n for (const [k, v] of external) compileRegistry.set(k, v);\n }\n }\n\n const result = compile(code, id, {\n registry: compileRegistry,\n resolvedInlineStyles,\n useDefineForClassFields,\n compilationMode: pluginOptions.fastCompileMode,\n oxcProgram,\n });\n\n // Track resource dependencies for HMR\n for (const dep of result.resourceDependencies) {\n resourceToSource.set(dep, id);\n }\n\n // Strip TypeScript-only syntax and compose the compiler map with the\n // final generated code so downstream breakpoints map back to the source.\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(\n result.code,\n id,\n {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n },\n result.map,\n )\n : await vite.transformWithEsbuild(\n result.code,\n id,\n { loader: 'ts', sourcemap: true },\n result.map,\n );\n let outputCode = stripped.code;\n\n // Append HMR code in dev mode\n if (watchMode && pluginOptions.liveReload) {\n const fileDeclarations = registryEntriesOf(id);\n if (fileDeclarations.length > 0) {\n const localDepClassNames = fileDeclarations.map((e) => e.className);\n outputCode += generateHmrCode(fileDeclarations, localDepClassNames);\n }\n }\n\n return { code: outputCode, map: stripped.map };\n }\n\n function resolveTsConfigPath() {\n const { root, isProd, isLib } = tsConfigResolutionContext!;\n return getTsConfigPath(\n root,\n pluginOptions.tsconfigGetter(),\n isProd,\n pluginOptions.isTest,\n isLib,\n pluginOptions.workspaceRoot,\n );\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-fast-compile',\n api: { getTsConfigPath: resolveTsConfigPath },\n enforce: 'pre' as const,\n async config(config, { command }) {\n watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n const preliminaryTsConfigPath = resolveTsConfigPath();\n\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd,\n jit: pluginOptions.jit,\n watchMode,\n isTest: pluginOptions.isTest,\n isAstroIntegration: pluginOptions.isAstroIntegration,\n });\n\n // No `resolve.conditions` extension here: the `style` condition is\n // scoped to `.css`-extension requests by\n // `cssExtensionStyleResolverPlugin`, registered once at the\n // `angular()` factory level (which is the only public entry point\n // that wires this plugin in).\n return {\n ...(vite.rolldownVersion ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n const integrations = await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n componentRegistries = integrations.componentRegistries;\n },\n async buildStart() {\n await initFastCompile();\n },\n closeBundle() {\n if (!watchMode) {\n releaseCssPreprocessorWorkers();\n }\n },\n async handleHotUpdate(ctx) {\n // Resource file changes → invalidate parent .ts module\n if (resourceToSource.has(ctx.file)) {\n const parentSource = resourceToSource.get(ctx.file)!;\n const parentModule = ctx.server.moduleGraph.getModuleById(parentSource);\n if (parentModule) {\n return [parentModule];\n }\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n\n // Remove old entries from this file\n const oldEntries = registryEntriesOf(fileId);\n for (const entry of oldEntries) {\n registry.delete(entry.className);\n }\n\n // Rescan the changed file via the barrel-aware scanner so an\n // edited barrel re-export picks up newly-referenced files.\n // Pass overwrite=true so updated metadata replaces stale\n // entries from the previous scan.\n await scanBarrelExports(fileId, new Set(), true);\n\n // Importers compiled the old selector/inputs/outputs into their\n // templates, so recompile them when this file's metadata changed.\n // Cached scans that pulled in this file may now be incomplete.\n lazyScans.clear();\n const metadataChanged =\n JSON.stringify(oldEntries) !==\n JSON.stringify(registryEntriesOf(fileId));\n if (metadataChanged) {\n const importerModules = [\n ...(importersByFile.get(fileId) ?? []),\n ].flatMap((importer) => [\n ...(ctx.server.moduleGraph.getModulesByFile(importer) ?? []),\n ]);\n return [...ctx.modules, ...importerModules];\n }\n }\n\n // Let Vite handle the rest — the transform hook will recompile\n return ctx.modules;\n },\n resolveId(id, importer) {\n if (id.startsWith(VIRTUAL_RAW_PREFIX)) {\n return `\\0${id}`;\n }\n\n if (pluginOptions.jit && id.startsWith('angular:jit:')) {\n const filePath = normalizePath(\n resolve(dirname(importer as string), id.split(';')[1]),\n );\n if (id.includes(':style')) {\n markStylePathSafe(resolvedConfig, filePath);\n return filePath + '?inline';\n }\n return toVirtualRawId(filePath);\n }\n\n const rawRewrite = rewriteHtmlRawImport(id, importer);\n if (rawRewrite) return rawRewrite;\n\n // User `.scss?inline` / `.css?inline` imports: resolve and mark\n // safe so Vite's native CSS pipeline handles them.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id) && importer) {\n const filePath = id.split('?')[0];\n const resolved = isAbsolute(filePath)\n ? normalizePath(filePath)\n : normalizePath(resolve(dirname(importer), filePath));\n markStylePathSafe(resolvedConfig, resolved);\n return resolved + '?inline';\n }\n\n return undefined;\n },\n async load(id) {\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Vitest fallback: module-runner can skip resolveId, so the bare\n // ?inline query reaches load. Mark safe and let Vite handle it.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id)) {\n markStylePathSafe(resolvedConfig, id.split('?')[0]);\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n // `?raw` ids already carry Vite's native raw-loader output\n // (`export default \"<source>\"`). Recompiling them as Angular/TS\n // would strip that default export, so leave them to Vite (#2356).\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (transformFilter && !transformFilter(code, id)) {\n return;\n }\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n return handleFastCompileTransform(code, id, async (spec, importer) => {\n const resolved = await this.resolve(spec, importer, {\n skipSelf: true,\n });\n if (!resolved || resolved.external) return null;\n const file = normalizePath(resolved.id.split('?')[0]);\n // Package declarations come from the lazy `.d.ts` scanner instead.\n return TS_EXT_REGEX.test(file) &&\n !EXCLUDED_TS_EXT_REGEX.test(file) &&\n !file.includes('/node_modules/')\n ? file\n : null;\n });\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,SAAgB,iBACd,SACA,UACQ;CACR,OAAO,SAAS,WAAW,SAAS,iBAAiB;AACvD;AAEA,SAAgB,kBACd,eACQ;CACR,IAAI;CACJ,IAAI;CACJ,IAAI,sBAAkD,CAAC;CACvD,IAAI,4BAA8D;CAClE,IAAI,YAAY;CAGhB,MAAM,2BAA8B,IAAI,IAAI;CAC5C,MAAM,mCAAmB,IAAI,IAAoB;CACjD,MAAM,qCAAqB,IAAI,IAAY;CAC3C,IAAI,cAAc;CAClB,IAAI,0BAA0B;CAC9B,IAAI;CAKJ,MAAM,4BAAY,IAAI,IAAkC;CACxD,MAAM,kCAAkB,IAAI,IAAyB;CACrD,IAAI;;;;;;;;;;;;;;;;;CAkBJ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AAC,EAAE;EAItD;EACA,WAAW;GACT,QAAQ,EACN,IAAI;IACF,SAAS,CAAC,YAAY;IAItB,SAAS;KACP;KACA;KACA;KACA;IACF;GACF,EACF;GACA,MAAM,QAAQ,MAAM,IAAI;IACtB,IAAI,mBAAmB,CAAC,gBAAgB,MAAM,EAAE,GAC9C;IAGF,IAAI,GAAG,SAAS,MAAM,GACpB,KAAK,GAAG,QAAQ,UAAU,EAAE;IAE9B,OAAO,2BAA2B,MAAM,IAAI,OAAO,MAAM,aAAa;KACpE,MAAM,WAAW,MAAM,KAAK,QAAQ,MAAM,UAAU,EAClD,UAAU,KACZ,CAAC;KACD,IAAI,CAAC,YAAY,SAAS,UAAU,OAAO;KAC3C,MAAM,OAAO,cAAc,SAAS,GAAG,MAAM,GAAG,CAAC,CAAC,EAAE;KAEpD,OAAO,aAAa,KAAK,IAAI,KAC3B,CAAC,sBAAsB,KAAK,IAAI,KAChC,CAAC,KAAK,SAAS,gBAAgB,IAC7B,OACA;IACN,CAAC;GACH;EACF;CACF;AACF"}
1
+ {"version":3,"file":"fast-compile-plugin.js","names":[],"sources":["../../../src/lib/fast-compile-plugin.ts"],"sourcesContent":["import { promises as fsPromises } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { parseSync } from 'oxc-parser';\nimport * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport { normalizePath, Plugin, preprocessCSS, ResolvedConfig } from 'vite';\n\nimport {\n compile,\n scanFile,\n declaresNonStandaloneComponent,\n scanPackageDts,\n collectImportedPackages,\n collectRelativeReExports,\n collectReExports,\n collectAllImports,\n jitTransform,\n inlineResourceUrls,\n extractInlineStyles,\n generateHmrCode,\n debugCompile,\n debugRegistry,\n ANGULAR_DECORATOR_CALL_RE,\n type ComponentRegistry,\n} from './compiler/index.js';\n\nimport {\n TS_EXT_REGEX,\n EXCLUDED_TS_EXT_REGEX,\n getTsConfigPath,\n createDepOptimizerConfig,\n isProdMode,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { VIRTUAL_RAW_PREFIX, toVirtualRawId } from './utils/virtual-ids.js';\nimport {\n loadVirtualRawModule,\n rewriteHtmlRawImport,\n} from './utils/virtual-resources.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\nimport type { TypeCheckerOption } from './utils/lsp-type-checker.js';\nimport {\n discoverAnalogIntegrations,\n type ComponentRegistryEntries,\n type TransformFilter,\n} from './analog-plugin-interop.js';\n\nexport interface FastCompilePluginOptions {\n tsconfigGetter: () => string;\n workspaceRoot: string;\n inlineStylesExtension: string;\n jit: boolean;\n liveReload: boolean;\n isTest: boolean;\n isAstroIntegration: boolean;\n fastCompileMode?: 'full' | 'partial';\n disableTypeChecking?: boolean;\n typeChecker?: TypeCheckerOption;\n}\n\ntype ResolveImport = (spec: string, importer: string) => Promise<string | null>;\n\n/**\n * Directory that `compilerOptions.paths` targets resolve against. Mirrors\n * TypeScript: `baseUrl` when set, otherwise the directory of the config\n * that declares `paths` (`pathsBasePath`, since `baseUrl` is optional\n * from TS 4.1).\n */\nexport function getPathsBasePath(\n options: { baseUrl?: string; pathsBasePath?: string } | undefined,\n fallback: string,\n): string {\n return options?.baseUrl ?? options?.pathsBasePath ?? fallback;\n}\n\nexport function fastCompilePlugin(\n pluginOptions: FastCompilePluginOptions,\n): Plugin {\n let resolvedConfig: ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let componentRegistries: ComponentRegistryEntries[] = [];\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n let watchMode = false;\n\n // fast-compile plugin state\n const registry: ComponentRegistry = new Map();\n const resourceToSource = new Map<string, string>();\n const scannedDtsPackages = new Set<string>();\n let projectRoot = '';\n let useDefineForClassFields = true;\n let tsConfig: ReturnType<typeof compilerCli.readConfiguration>;\n\n // Files scanned on demand (mapped to the barrel chain they pulled in), which\n // modules were compiled against each scanned file, and the one-time\n // whole-project scan non-standalone components fall back to.\n const lazyScans = new Map<string, Promise<Set<string>>>();\n const importersByFile = new Map<string, Set<string>>();\n let projectScan: Promise<void> | undefined;\n\n /**\n * Scan a file into the registry, then recursively walk its relative\n * `export *` / `export { … } from './x'` chain so any underlying\n * directive classes also land in the registry. Used both at\n * `buildStart` (for tsconfig path entries) and at dev time (file\n * `add` and `handleHotUpdate`) so newly added barrels stay in sync\n * without requiring a server restart.\n *\n * The `visited` set prevents infinite recursion within a single\n * top-level call. Each fresh scan should pass an empty set (so HMR\n * re-scans aren't blocked by buildStart's earlier visits).\n *\n * `fileContents`/`scanResults` are cold-start dedup caches scoped to a\n * single `initFastCompile` call. HMR/watcher callers must omit them so\n * an edited file is always re-read from disk.\n */\n async function scanBarrelExports(\n file: string,\n visited: Set<string> = new Set(),\n overwrite = false,\n fileContents?: Map<string, string>,\n scanResults?: Map<string, ReturnType<typeof scanFile>>,\n ): Promise<void> {\n if (visited.has(file)) return;\n visited.add(file);\n let code: string;\n try {\n code =\n fileContents?.get(file) ?? (await fsPromises.readFile(file, 'utf-8'));\n fileContents?.set(file, code);\n } catch (e) {\n if (debugRegistry.enabled) {\n debugRegistry(\n 'scanBarrelExports: failed to read %s: %s',\n file,\n (e as Error)?.message,\n );\n }\n return;\n }\n // Single parse shared by scanFile and collectRelativeReExports. On a\n // parse error each consumer re-parses on its own, preserving their\n // individual failure semantics (scanFile throws past its pre-filter;\n // collectRelativeReExports swallows and returns []).\n let program: ReturnType<typeof parseSync>['program'] | undefined;\n try {\n program = parseSync(file, code).program;\n } catch {\n program = undefined;\n }\n let entries = scanResults?.get(file);\n if (!entries) {\n entries = scanFile(code, file, program);\n scanResults?.set(file, entries);\n }\n for (const entry of entries) {\n // At buildStart we want stable registry entries (don't overwrite\n // an earlier scan with a barrel re-scan); HMR explicitly asks\n // for overwrite so updated metadata replaces stale entries.\n if (overwrite || !registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n // Collect every relative re-export specifier via OXC AST so\n // recursive scans can't trip over each other (a shared `/g` regex\n // would have its `lastIndex` reset by each recursive call and\n // silently skip half of an outer barrel's re-exports, which\n // previously left directives like `HlmRadioGroup` unregistered).\n const dir = dirname(file);\n for (const rel of collectRelativeReExports(code, file, program)) {\n // NodeNext-style libraries write `export * from './foo.js'`\n // even though the source is `./foo.ts`. Strip the ESM\n // extension before probing or the candidates would be\n // `foo.js.ts` / `foo.js/index.ts`, which never exist.\n const normalizedRel = rel.replace(/\\.(?:js|mjs)$/u, '');\n const reExportCandidates = [\n resolve(dir, normalizedRel + '.ts'),\n resolve(dir, normalizedRel, 'index.ts'),\n ];\n let resolved = false;\n for (const candidate of reExportCandidates) {\n try {\n await fsPromises.access(candidate);\n await scanBarrelExports(\n candidate,\n visited,\n overwrite,\n fileContents,\n scanResults,\n );\n resolved = true;\n break;\n } catch {\n // try next candidate\n }\n }\n if (!resolved && debugRegistry.enabled) {\n debugRegistry(\n 'scanBarrelExports: %s re-export %s did not resolve to %o',\n file,\n rel,\n reExportCandidates,\n );\n }\n }\n }\n\n async function initFastCompile() {\n if (pluginOptions.jit) return; // JIT: no registry scan needed\n\n registry.clear();\n scannedDtsPackages.clear();\n lazyScans.clear();\n importersByFile.clear();\n projectScan = undefined;\n const resolvedTsConfigPath = resolveTsConfigPath();\n projectRoot = dirname(resolvedTsConfigPath);\n tsConfig = compilerCli.readConfiguration(resolvedTsConfigPath);\n useDefineForClassFields = tsConfig.options?.useDefineForClassFields ?? true;\n }\n\n /** Scan all source files reachable from the tsconfig into the registry. */\n async function scanProject() {\n const config = tsConfig;\n // Collect candidate files: tsconfig rootNames PLUS the entry points\n // named in `compilerOptions.paths`. App tsconfigs typically only\n // include the app's own sources, so workspace library entry barrels\n // (e.g. `HlmSelectImports = [HlmSelect, HlmSelectContent, ...] as\n // const`) live outside `rootNames` and would otherwise miss the\n // initial scan. The compiler then can't see that `HlmSelectImports`\n // is a tuple barrel and emits the bare identifier into the parent\n // component's `dependencies()` list, where Angular's runtime\n // silently drops it because arrays don't have a directive def.\n const candidates = new Set<string>(config.rootNames);\n const tsPaths = config.options?.paths;\n const baseUrl = getPathsBasePath(config.options, projectRoot);\n // Cold-start dedup caches shared by the three scan phases below\n // (candidates scan, walkImports, scanBarrelExports). Scoped to this\n // init call only — HMR/watcher re-scans must hit disk fresh.\n const fileContents = new Map<string, string>();\n const scanResults = new Map<string, ReturnType<typeof scanFile>>();\n if (tsPaths) {\n for (const targets of Object.values(tsPaths)) {\n for (const target of targets as string[]) {\n // Skip wildcard patterns — entry barrels are normally exact\n // file paths like \"libs/helm/select/src/index.ts\".\n if (target.includes('*')) continue;\n candidates.add(resolve(baseUrl, target));\n }\n }\n }\n const results = await Promise.all(\n Array.from(candidates).map(async (file) => {\n try {\n const code = await fsPromises.readFile(file, 'utf-8');\n fileContents.set(file, code);\n const entries = scanFile(code, file);\n scanResults.set(file, entries);\n return entries;\n } catch (e) {\n if (debugRegistry.enabled) {\n debugRegistry(\n 'initFastCompile: skipping unreadable %s: %s',\n file,\n (e as Error)?.message,\n );\n }\n return []; // Skip unreadable files\n }\n }),\n );\n\n for (const entries of results) {\n for (const entry of entries) {\n registry.set(entry.className, entry);\n }\n }\n\n // Walk the transitive import graph from the root files so the registry also\n // contains declarations that live in files not directly in tsconfig\n // `files`/`include` (transitively-imported app sources) and in workspace\n // libraries reached through wildcard `paths` (e.g. `@bitwarden/*`). Without\n // this, a non-standalone component's owning module can't classify its\n // declarations and `ɵɵsetComponentScope` is never emitted for it. Only\n // relative imports and `paths`-mapped (project/workspace) bare specifiers are\n // followed; true `node_modules` packages are left to the lazy `.d.ts` scanner.\n // Return *all* candidate base paths a bare specifier maps to. A `paths`\n // entry can list several fallback targets (e.g. a built `dist` path first\n // and the workspace `src` second); the caller probes them in order.\n const resolvePathSpecifier = (spec: string): string[] => {\n if (!tsPaths) return [];\n for (const [key, targets] of Object.entries(tsPaths)) {\n const list = targets as string[];\n if (key.endsWith('/*')) {\n const prefix = key.slice(0, -1);\n if (spec.startsWith(prefix)) {\n // `split('*').join(...)` substitutes the single tsconfig `*`\n // wildcard without `String.replace`'s first-match-only behavior or\n // `$`-pattern interpretation of the replacement.\n return list.map((t) =>\n resolve(baseUrl, t.split('*').join(spec.slice(prefix.length))),\n );\n }\n } else if (key === spec) {\n return list.map((t) => resolve(baseUrl, t));\n }\n }\n return [];\n };\n const probeToSource = async (base: string): Promise<string | null> => {\n const candidates = base.endsWith('.ts')\n ? [base]\n : [base + '.ts', resolve(base, 'index.ts')];\n for (const candidate of candidates) {\n try {\n await fsPromises.access(candidate);\n return candidate;\n } catch {\n // try next candidate\n }\n }\n return null;\n };\n // Memoize fs probes per absolute base path. The cache stores the\n // Promise (not the settled value) so concurrent walks racing on the\n // same base collapse into a single probe.\n const baseResolveCache = new Map<string, Promise<string | null>>();\n const resolveToSource = (base: string): Promise<string | null> => {\n let probe = baseResolveCache.get(base);\n if (!probe) {\n probe = probeToSource(base);\n baseResolveCache.set(base, probe);\n }\n return probe;\n };\n // Probe each `paths` target in order; first one that resolves to source wins.\n const resolveFirstSource = async (\n bases: string[],\n ): Promise<string | null> => {\n for (const base of bases) {\n const resolved = await resolveToSource(base);\n if (resolved) return resolved;\n }\n return null;\n };\n const importWalkVisited = new Set<string>();\n // Paths-mapped resolution doesn't depend on the importer, so bare\n // specifiers can be memoized by their raw text. Relative specifiers\n // must NOT be — the same './foo' resolves differently per directory.\n const bareSpecResolveCache = new Map<string, Promise<string | null>>();\n const walkImports = async (file: string): Promise<void> => {\n if (importWalkVisited.has(file)) return;\n importWalkVisited.add(file);\n let code: string;\n try {\n code =\n fileContents.get(file) ?? (await fsPromises.readFile(file, 'utf-8'));\n fileContents.set(file, code);\n } catch {\n return;\n }\n // Single parse shared by scanFile, collectImportedPackages, and\n // collectAllImports. On a parse error each consumer re-parses on\n // its own, preserving their individual failure semantics.\n let program: ReturnType<typeof parseSync>['program'] | undefined;\n try {\n program = parseSync(file, code).program;\n } catch {\n program = undefined;\n }\n let entries = scanResults.get(file);\n if (!entries) {\n entries = scanFile(code, file, program);\n scanResults.set(file, entries);\n }\n for (const entry of entries) {\n if (!registry.has(entry.className))\n registry.set(entry.className, entry);\n }\n // Pre-scan the `.d.ts` of every external package this file imports (and,\n // transitively, packages those packages' NgModules re-export — e.g.\n // BrowserModule → CommonModule → NgIf). Doing this at buildStart means the\n // registry is complete before any component transforms, so non-standalone\n // component scope resolves regardless of file transform order.\n for (const pkg of collectImportedPackages(code, file, program)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n try {\n for (const entry of scanPackageDts(\n pkg,\n projectRoot,\n scannedDtsPackages,\n )) {\n if (!registry.has(entry.className))\n registry.set(entry.className, entry);\n }\n } catch {\n // Package may not have .d.ts or not be Angular\n }\n }\n const dir = dirname(file);\n const targets = await Promise.all(\n collectAllImports(code, file, program).map((spec) => {\n if (spec.startsWith('.')) {\n return resolveToSource(\n resolve(dir, spec.replace(/\\.(?:js|mjs)$/u, '')),\n );\n }\n let resolved = bareSpecResolveCache.get(spec);\n if (!resolved) {\n resolved = resolveFirstSource(resolvePathSpecifier(spec));\n bareSpecResolveCache.set(spec, resolved);\n }\n return resolved;\n }),\n );\n await Promise.all(\n targets.filter((t): t is string => !!t).map((t) => walkImports(t)),\n );\n };\n await Promise.all(config.rootNames.map((file) => walkImports(file)));\n\n // Library barrels typically `export * from './lib/...'` rather than\n // declaring directives directly, so the entry file alone gives us\n // the tuple consts but not the directive classes they reference.\n // Walk the relative `export *` chain so the underlying classes also\n // land in the registry. Use a SHARED visited set across all\n // barrels so recursive walks don't double-scan a file that's\n // re-exported from multiple entry points.\n const buildStartVisited = new Set<string>();\n if (tsPaths) {\n const barrelCandidates: string[] = [];\n for (const targets of Object.values(tsPaths)) {\n for (const target of targets as string[]) {\n if (target.includes('*')) continue;\n barrelCandidates.push(resolve(baseUrl, target));\n }\n }\n await Promise.all(\n barrelCandidates.map((c) =>\n scanBarrelExports(\n c,\n buildStartVisited,\n false,\n fileContents,\n scanResults,\n ),\n ),\n );\n }\n debugRegistry(\n 'initFastCompile done: %d entries from %d candidate files',\n registry.size,\n candidates.size,\n );\n }\n\n function ensureDtsRegistryForSource(\n code: string,\n id: string,\n program?: ReturnType<typeof parseSync>['program'],\n ) {\n for (const pkg of collectImportedPackages(code, id, program)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n\n try {\n const dtsEntries = scanPackageDts(pkg, projectRoot, scannedDtsPackages);\n for (const entry of dtsEntries) {\n if (!registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n } catch {\n // Package may not have .d.ts files or may not be Angular\n }\n }\n }\n\n /**\n * Scan the source files `id` imports into the registry on demand and record\n * `id` as their importer, so a metadata change in any of them recompiles it.\n */\n async function resolveImportedDeclarations(\n code: string,\n id: string,\n program: ReturnType<typeof parseSync>['program'],\n resolveImport: ResolveImport,\n ) {\n await Promise.all(\n collectAllImports(code, id, program).map(async (spec) => {\n const file = await resolveImport(spec, id);\n if (!file) return;\n for (const scanned of await scanOnDemand(file, resolveImport)) {\n let importers = importersByFile.get(scanned);\n if (!importers) {\n importers = new Set();\n importersByFile.set(scanned, importers);\n }\n importers.add(id);\n }\n }),\n );\n }\n\n function scanOnDemand(\n file: string,\n resolveImport: ResolveImport,\n ): Promise<Set<string>> {\n let scan = lazyScans.get(file);\n if (!scan) {\n scan = scanWithReExports(file, resolveImport);\n lazyScans.set(file, scan);\n }\n return scan;\n }\n\n /**\n * Scan a file and everything it re-exports, resolving specifiers through\n * Vite so path aliases work. Tuple barrels and NgModules can list classes\n * their file imports without re-exporting, so their imports are followed\n * too. Returns every file scanned.\n */\n async function scanWithReExports(\n file: string,\n resolveImport: ResolveImport,\n ): Promise<Set<string>> {\n const visited = new Set<string>();\n const visit = async (current: string): Promise<void> => {\n if (visited.has(current)) return;\n visited.add(current);\n let code: string;\n let program: ReturnType<typeof parseSync>['program'];\n try {\n code = await fsPromises.readFile(current, 'utf-8');\n program = parseSync(current, code).program;\n } catch {\n return;\n }\n const entries = scanFile(code, current, program);\n for (const entry of entries) {\n if (!registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n ensureDtsRegistryForSource(code, current, program);\n const followsImports = entries.some(\n (e) => e.kind === 'tuple' || e.kind === 'ngmodule',\n );\n const specifiers = followsImports\n ? collectAllImports(code, current, program)\n : collectReExports(code, current, program);\n for (const spec of specifiers) {\n const dep = await resolveImport(spec, current);\n if (dep) await visit(dep);\n }\n };\n await visit(file);\n return visited;\n }\n\n function registryEntriesOf(file: string) {\n return [...registry.values()].filter((e) => e.fileName === file);\n }\n\n async function handleFastCompileTransform(\n code: string,\n id: string,\n resolveImport: ResolveImport,\n ): Promise<{ code: string; map: any } | undefined> {\n if (!ANGULAR_DECORATOR_CALL_RE.test(code)) {\n // Non-Angular file — strip TS-only syntax ourselves so barrels\n // like `export { Foo, type Bar } from './x'` and other TS-only\n // forms don't leak unstripped to Rolldown. In rolldown-vite the\n // built-in `vite:oxc` strip is registered as a Rust-side native\n // plugin (`viteTransformPlugin` from `rolldown/experimental`); if\n // its hook-filter treats files our `transform.filter.id.include`\n // claimed as already-handled, no JS-side fallback runs and raw\n // TS reaches the parser → `SyntaxError: Unexpected identifier`.\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(code, id, {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n })\n : await vite.transformWithEsbuild(code, id, {\n loader: 'ts',\n sourcemap: true,\n });\n return { code: stripped.code, map: stripped.map };\n }\n\n // JIT mode\n if (pluginOptions.jit) {\n const result = jitTransform(code, id);\n // Strip TypeScript-only syntax (e.g. `readonly`, parameter property\n // modifiers, type annotations on fields) so the output is valid JS\n // for Rolldown. `angularVitestSourcemapPlugin` normally runs this\n // strip downstream in tests, but it is intentionally skipped on\n // StackBlitz / WebContainer — and the production build pipeline\n // does not register it either — so the JIT path must self-strip\n // to stay safe across environments.\n //\n // Pass the jitTransform map as `inMap` so OXC/esbuild emit a map\n // composed with the original `.ts` source — without this, debug\n // stack traces and breakpoints land on the wrong lines once the\n // strip removes any TS-only token. `jitTransform` returns\n // `map: null` for files with no Angular class (no edits made);\n // passing that to OXC/esbuild as `inMap` throws, so coerce to\n // `undefined` in that case.\n const inMap = result.map ?? undefined;\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(\n result.code,\n id,\n {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n },\n inMap,\n )\n : await vite.transformWithEsbuild(\n result.code,\n id,\n { loader: 'ts', sourcemap: true },\n inMap,\n );\n return { code: stripped.code, map: stripped.map };\n }\n\n // Inline external templateUrl/styleUrl(s) into the source before compilation.\n // `styleExtensions` carries the source extension of each inlined external\n // style so it can be preprocessed by its own file type (e.g. an external\n // `.scss` styleUrl) regardless of the `inlineStylesExtension` option.\n const inlined = await inlineResourceUrls(code, id);\n code = inlined.code;\n const { styleExtensions } = inlined;\n\n // Track inlined resources for HMR. `compile()` only reports resources it\n // reads through its own fallback (a templateUrl/styleUrl the inliner did\n // NOT already inline), so files inlined here must be recorded here or a\n // later edit to them never invalidates the owning module.\n for (const dep of inlined.resourceDependencies) {\n resourceToSource.set(dep, id);\n }\n\n // Single OXC parse of the post-inline source, shared by every AST\n // consumer below. `inlineResourceUrls` parsed the PRE-inline string,\n // so its program can never be reused here.\n const { program: oxcProgram } = parseSync(id, code);\n\n // Pre-resolve inline styles that need preprocessing (SCSS/Sass/Less). Run\n // whenever a style needs a non-`css` preprocessor — either the configured\n // `inlineStylesExtension` for truly-inline styles, or an external styleUrl's\n // own extension.\n let resolvedInlineStyles: Map<number, string> | undefined;\n\n const inlineExt = pluginOptions.inlineStylesExtension;\n const styleNeedsPreprocess = (ext: string) => ext !== '' && ext !== 'css';\n\n if (styleNeedsPreprocess(inlineExt) || styleExtensions.size > 0) {\n const styleStrings = extractInlineStyles(code, id, oxcProgram);\n\n if (styleStrings.length > 0) {\n resolvedInlineStyles = new Map();\n for (let i = 0; i < styleStrings.length; i++) {\n // External styleUrls are preprocessed by their own extension; truly\n // inline `styles: [...]` fall back to `inlineStylesExtension`.\n const ext = styleExtensions.get(i) ?? inlineExt;\n if (!styleNeedsPreprocess(ext)) continue;\n try {\n const fakePath = id.replace(/\\.ts$/, `.inline-${i}.${ext}`);\n const processed = await preprocessCSS(\n styleStrings[i],\n fakePath,\n resolvedConfig,\n );\n resolvedInlineStyles.set(i, processed.code);\n } catch (e) {\n if (debugCompile.enabled) {\n debugCompile(\n 'inline style #%d preprocessing failed in %s: %s',\n i,\n id,\n (e as Error)?.message,\n );\n }\n // Skip styles that can't be preprocessed\n }\n }\n if (resolvedInlineStyles.size === 0) resolvedInlineStyles = undefined;\n }\n }\n\n ensureDtsRegistryForSource(code, id, oxcProgram);\n\n for (const entry of scanFile(code, id, oxcProgram)) {\n registry.set(entry.className, entry);\n }\n await resolveImportedDeclarations(code, id, oxcProgram, resolveImport);\n if (declaresNonStandaloneComponent(oxcProgram)) {\n projectScan ??= scanProject();\n await projectScan;\n }\n\n // Merge registries contributed through `analog.setup()` into this\n // compile's lookup view. Out-of-tree compilers register directive\n // metadata for classes fastCompile can't reach through its\n // tsconfig-driven scan (e.g. `.tsrx` files compiled by `@tsrx/analog`).\n // Without this merge, a TS `@Component({ imports: [X] })` that\n // references such a class hits `_unresolved-${className}` as its\n // selector and the tag never matches at runtime.\n let compileRegistry: ComponentRegistry = registry;\n if (componentRegistries.some((external) => external.size > 0)) {\n compileRegistry = new Map(registry);\n for (const external of componentRegistries) {\n for (const [k, v] of external) compileRegistry.set(k, v);\n }\n }\n\n const result = compile(code, id, {\n registry: compileRegistry,\n resolvedInlineStyles,\n useDefineForClassFields,\n compilationMode: pluginOptions.fastCompileMode,\n oxcProgram,\n });\n\n // Track resource dependencies for HMR\n for (const dep of result.resourceDependencies) {\n resourceToSource.set(dep, id);\n }\n\n // Strip TypeScript-only syntax and compose the compiler map with the\n // final generated code so downstream breakpoints map back to the source.\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(\n result.code,\n id,\n {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n },\n result.map,\n )\n : await vite.transformWithEsbuild(\n result.code,\n id,\n { loader: 'ts', sourcemap: true },\n result.map,\n );\n let outputCode = stripped.code;\n\n // Append HMR code in dev mode\n if (watchMode && pluginOptions.liveReload) {\n const fileDeclarations = registryEntriesOf(id);\n if (fileDeclarations.length > 0) {\n const localDepClassNames = fileDeclarations.map((e) => e.className);\n outputCode += generateHmrCode(fileDeclarations, localDepClassNames);\n }\n }\n\n return { code: outputCode, map: stripped.map };\n }\n\n function resolveTsConfigPath() {\n const { root, isProd, isLib } = tsConfigResolutionContext!;\n return getTsConfigPath(\n root,\n pluginOptions.tsconfigGetter(),\n isProd,\n pluginOptions.isTest,\n isLib,\n pluginOptions.workspaceRoot,\n );\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-fast-compile',\n api: { getTsConfigPath: resolveTsConfigPath },\n enforce: 'pre' as const,\n async config(config, { command }) {\n watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n const preliminaryTsConfigPath = resolveTsConfigPath();\n\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd,\n jit: pluginOptions.jit,\n watchMode,\n isTest: pluginOptions.isTest,\n isAstroIntegration: pluginOptions.isAstroIntegration,\n });\n\n // No `resolve.conditions` extension here: the `style` condition is\n // scoped to `.css`-extension requests by\n // `cssExtensionStyleResolverPlugin`, registered once at the\n // `angular()` factory level (which is the only public entry point\n // that wires this plugin in).\n return {\n ...(vite.rolldownVersion ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n const integrations = await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n componentRegistries = integrations.componentRegistries;\n },\n async buildStart() {\n await initFastCompile();\n },\n closeBundle() {\n if (!watchMode) {\n releaseCssPreprocessorWorkers();\n }\n },\n async handleHotUpdate(ctx) {\n // Resource file changes → invalidate parent .ts module\n if (resourceToSource.has(ctx.file)) {\n const parentSource = resourceToSource.get(ctx.file)!;\n const parentModule = ctx.server.moduleGraph.getModuleById(parentSource);\n if (parentModule) {\n return [parentModule];\n }\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n\n // Remove old entries from this file\n const oldEntries = registryEntriesOf(fileId);\n for (const entry of oldEntries) {\n registry.delete(entry.className);\n }\n\n // Rescan the changed file via the barrel-aware scanner so an\n // edited barrel re-export picks up newly-referenced files.\n // Pass overwrite=true so updated metadata replaces stale\n // entries from the previous scan.\n await scanBarrelExports(fileId, new Set(), true);\n\n // Importers compiled the old selector/inputs/outputs into their\n // templates, so recompile them when this file's metadata changed.\n // Cached scans that pulled in this file may now be incomplete.\n lazyScans.clear();\n const metadataChanged =\n JSON.stringify(oldEntries) !==\n JSON.stringify(registryEntriesOf(fileId));\n if (metadataChanged) {\n const importerModules = [\n ...(importersByFile.get(fileId) ?? []),\n ].flatMap((importer) => [\n ...(ctx.server.moduleGraph.getModulesByFile(importer) ?? []),\n ]);\n return [...ctx.modules, ...importerModules];\n }\n }\n\n // Let Vite handle the rest — the transform hook will recompile\n return ctx.modules;\n },\n resolveId(id, importer) {\n if (id.startsWith(VIRTUAL_RAW_PREFIX)) {\n return `\\0${id}`;\n }\n\n if (pluginOptions.jit && id.startsWith('angular:jit:')) {\n const filePath = normalizePath(\n resolve(dirname(importer as string), id.split(';')[1]),\n );\n if (id.includes(':style')) {\n markStylePathSafe(resolvedConfig, filePath);\n return filePath + '?inline';\n }\n return toVirtualRawId(filePath);\n }\n\n const rawRewrite = rewriteHtmlRawImport(id, importer);\n if (rawRewrite) return rawRewrite;\n\n // User `.scss?inline` / `.css?inline` imports: resolve and mark\n // safe so Vite's native CSS pipeline handles them.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id) && importer) {\n const filePath = id.split('?')[0];\n const resolved = isAbsolute(filePath)\n ? normalizePath(filePath)\n : normalizePath(resolve(dirname(importer), filePath));\n markStylePathSafe(resolvedConfig, resolved);\n return resolved + '?inline';\n }\n\n return undefined;\n },\n async load(id) {\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Vitest fallback: module-runner can skip resolveId, so the bare\n // ?inline query reaches load. Mark safe and let Vite handle it.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id)) {\n markStylePathSafe(resolvedConfig, id.split('?')[0]);\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n // `?raw` ids already carry Vite's native raw-loader output\n // (`export default \"<source>\"`). Recompiling them as Angular/TS\n // would strip that default export, so leave them to Vite (#2356).\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (transformFilter && !transformFilter(code, id)) {\n return;\n }\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n return handleFastCompileTransform(code, id, async (spec, importer) => {\n const resolved = await this.resolve(spec, importer, {\n skipSelf: true,\n });\n if (!resolved || resolved.external) return null;\n const file = normalizePath(resolved.id.split('?')[0]);\n // Package declarations come from the lazy `.d.ts` scanner instead.\n return TS_EXT_REGEX.test(file) &&\n !EXCLUDED_TS_EXT_REGEX.test(file) &&\n !file.includes('/node_modules/')\n ? file\n : null;\n });\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAgB,iBACd,SACA,UACQ;CACR,OAAO,SAAS,WAAW,SAAS,iBAAiB;AACvD;AAEA,SAAgB,kBACd,eACQ;CACR,IAAI;CACJ,IAAI;CACJ,IAAI,sBAAkD,CAAC;CACvD,IAAI,4BAA8D;CAClE,IAAI,YAAY;CAGhB,MAAM,2BAA8B,IAAI,IAAI;CAC5C,M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;IAC1C,OAAO,WAAW;GACpB;EAGF;EACA,MAAM,KAAK,IAAI;GACb,MAAM,YAAY,MAAM,qBAAqB,MAAM,EAAE;GACrD,IAAI,cAAc,KAAA,GAAW,OAAO;GAIpC,IAAI,kCAAkC,KAAK,EAAE,GAC3C,kBAAkB,gBAAgB,GAAG,MAAM,GAAG,CAAC,CAAC,EAAE;EAItD;EACA,WAAW;GACT,QAAQ,EACN,IAAI;IACF,SAAS,CAAC,YAAY;IAItB,SAAS;KACP;KACA;KACA;KACA;IACF;GACF,EACF;GACA,MAAM,QAAQ,MAAM,IAAI;IACtB,IAAI,mBAAmB,CAAC,gBAAgB,MAAM,EAAE,GAC9C;IAGF,IAAI,GAAG,SAAS,MAAM,GACpB,KAAK,GAAG,QAAQ,UAAU,EAAE;IAE9B,OAAO,2BAA2B,MAAM,IAAI,OAAO,MAAM,aAAa;KACpE,MAAM,WAAW,MAAM,KAAK,QAAQ,MAAM,UAAU,EAClD,UAAU,KACZ,CAAC;KACD,IAAI,CAAC,YAAY,SAAS,UAAU,OAAO;KAC3C,MAAM,OAAO,cAAc,SAAS,GAAG,MAAM,GAAG,CAAC,CAAC,EAAE;KAEpD,OAAO,aAAa,KAAK,IAAI,KAC3B,CAAC,sBAAsB,KAAK,IAAI,KAChC,CAAC,KAAK,SAAS,gBAAgB,IAC7B,OACA;IACN,CAAC;GACH;EACF;CACF;AACF"}
@@ -0,0 +1,3 @@
1
+ import * as vite from "vite";
2
+ import type { FastCompilePluginOptions } from "./fast-compile-plugin.js";
3
+ export declare function ngpCompilePlugin(options: FastCompilePluginOptions): vite.Plugin;
@@ -0,0 +1,271 @@
1
+ import { angularFullVersion } from "./utils/devkit.js";
2
+ import { TS_EXT_REGEX, createDepOptimizerConfig, getTsConfigPath, isProdMode } from "./utils/plugin-config.js";
3
+ import { discoverAnalogIntegrations } from "./analog-plugin-interop.js";
4
+ import { releaseCssPreprocessorWorkers } from "./utils/css-preprocessor-workers.js";
5
+ import { LspTypeChecker } from "./utils/lsp-type-checker.js";
6
+ import { resolve } from "node:path";
7
+ import { createRequire } from "node:module";
8
+ import * as vite from "vite";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ //#region packages/vite-plugin-angular/src/lib/ngp-compile-plugin.ts
11
+ var BUNDLED_NGP = new URL("../../ngp/", "" + import.meta.url);
12
+ async function loadNgp(tsconfig) {
13
+ const nativeBinding = process.env["ANALOG_NGP_NATIVE_BINDING"];
14
+ let modulePath = process.env["ANALOG_NGP_COMPILER"];
15
+ if (!modulePath) try {
16
+ modulePath = createRequire(tsconfig).resolve("@angular/ngp");
17
+ } catch {
18
+ if (angularFullVersion < 220200) throw new Error("[@analogjs/vite-plugin-angular]: compilation: 'ngp' requires Angular v22.2 or later.");
19
+ return {
20
+ api: await import(new URL("api.mjs", BUNDLED_NGP).href),
21
+ analyzerOptions: nativeBinding ? { nativeBinding } : {
22
+ backend: "wasm",
23
+ wasmBinding: fileURLToPath(new URL("ng_analyze.cjs", BUNDLED_NGP))
24
+ }
25
+ };
26
+ }
27
+ return {
28
+ api: await import(pathToFileURL(resolve(modulePath)).href),
29
+ analyzerOptions: nativeBinding ? { nativeBinding } : {}
30
+ };
31
+ }
32
+ function ngpCompilePlugin(options) {
33
+ if (options.jit || options.fastCompileMode === "partial") throw new Error("compilation: 'ngp' requires jit: false and fastCompileMode: 'full'.");
34
+ let configContext;
35
+ let resolvedConfig;
36
+ let transformFilter;
37
+ let watchMode = false;
38
+ let activeBuilds = 0;
39
+ let analyzer;
40
+ let compiler;
41
+ let typeChecker;
42
+ let api;
43
+ const filesByPath = /* @__PURE__ */ new Map();
44
+ const chunkContexts = /* @__PURE__ */ new Map();
45
+ const output = /* @__PURE__ */ new Map();
46
+ const watchedFiles = /* @__PURE__ */ new Set();
47
+ let pending = Promise.resolve();
48
+ const filter = vite.createFilter(TS_EXT_REGEX, [
49
+ /node_modules/,
50
+ /[?&]raw\b/,
51
+ /type=script/,
52
+ /@ng\/component/
53
+ ]);
54
+ function resolveTsConfigPath() {
55
+ return getTsConfigPath(configContext.root, options.tsconfigGetter(), configContext.isProd, options.isTest, configContext.isLib, options.workspaceRoot);
56
+ }
57
+ async function prepareResources(file, watch) {
58
+ watch(file.filePath);
59
+ return {
60
+ ...file,
61
+ classes: await Promise.all(file.classes.map(async (metadata, classIndex) => {
62
+ const component = metadata.component;
63
+ if (!component) return metadata;
64
+ if (component.templateUrl) watch(component.templateUrl.resolvedPath);
65
+ for (const style of component.styleUrls ?? []) watch(style.resolvedPath);
66
+ const preprocess = async (content, path) => {
67
+ const result = await vite.preprocessCSS(content, path, resolvedConfig);
68
+ result.deps?.forEach(watch);
69
+ return result.code;
70
+ };
71
+ return {
72
+ ...metadata,
73
+ component: {
74
+ ...component,
75
+ styles: component.styles && await Promise.all(component.styles.map((style, index) => preprocess(style, `${file.filePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`))),
76
+ stylesFromUrls: component.stylesFromUrls && await Promise.all(component.stylesFromUrls.map((style, index) => preprocess(style, component.styleUrls[index].resolvedPath)))
77
+ }
78
+ };
79
+ }))
80
+ };
81
+ }
82
+ async function indexChunks(update) {
83
+ if (update) {
84
+ const invalidated = await update();
85
+ for (const filePath of invalidated) output.delete(vite.normalizePath(filePath));
86
+ chunkContexts.clear();
87
+ } else {
88
+ filesByPath.clear();
89
+ chunkContexts.clear();
90
+ output.clear();
91
+ compiler = new api.HybridCompiler(analyzer, { optimize: true });
92
+ }
93
+ const chunks = update ? compiler.analyzeOptimizedDelta() : compiler.analyzeOptimized();
94
+ for await (const chunk of chunks) for (const file of chunk.files) {
95
+ const normPath = vite.normalizePath(file.filePath);
96
+ filesByPath.set(normPath, {
97
+ file,
98
+ chunk
99
+ });
100
+ output.delete(normPath);
101
+ }
102
+ }
103
+ function enqueueIndex(update) {
104
+ pending = pending.catch(() => {}).then(() => indexChunks(update));
105
+ return pending;
106
+ }
107
+ function getChunkContext(chunk) {
108
+ let context = chunkContexts.get(chunk);
109
+ if (!context) {
110
+ context = compiler.prepareChunk(chunk);
111
+ chunkContexts.set(chunk, context);
112
+ }
113
+ return context;
114
+ }
115
+ async function checkTypes(filePath, sourceCode, tcbCode) {
116
+ typeChecker ??= new LspTypeChecker(resolveTsConfigPath(), options.typeChecker);
117
+ typeChecker.queueFile(filePath, sourceCode, tcbCode);
118
+ if (!watchMode) return;
119
+ const typeErrors = await typeChecker.flushQueue(true);
120
+ if (typeErrors.length) throw new Error(typeErrors.join("\n"));
121
+ }
122
+ function compileFile(normPath, watch) {
123
+ const entry = filesByPath.get(normPath);
124
+ if (!entry) return void 0;
125
+ let task = output.get(normPath);
126
+ if (!task) {
127
+ task = (async () => {
128
+ const activeAnalyzer = analyzer;
129
+ const activeCompiler = compiler;
130
+ const trackWatch = (path) => {
131
+ watchedFiles.add(path);
132
+ watch(path);
133
+ };
134
+ const [file, context, content] = await Promise.all([
135
+ prepareResources(entry.file, trackWatch),
136
+ getChunkContext(entry.chunk),
137
+ activeAnalyzer.getFileContent(entry.file.filePath)
138
+ ]);
139
+ const result = activeCompiler.processFile.length >= 5 ? await activeCompiler.processFile(file.filePath, content, void 0, file, context) : await activeCompiler.processFile(file.filePath, content, file, context);
140
+ const errors = [...file.diagnostics ?? [], ...result.diagnostics ?? []].filter((diagnostic) => diagnostic.category === 1);
141
+ if (errors.length) throw new Error(`${file.filePath}: ${errors.map((error) => error.messageText).join("\n")}`);
142
+ if (options.disableTypeChecking !== true) await checkTypes(file.filePath, content, result.tcb?.code);
143
+ return result;
144
+ })();
145
+ output.set(normPath, task);
146
+ }
147
+ return task;
148
+ }
149
+ return {
150
+ name: "@analogjs/vite-plugin-angular-ngp",
151
+ enforce: "pre",
152
+ api: {
153
+ getTsConfigPath: resolveTsConfigPath,
154
+ output,
155
+ ready: () => pending
156
+ },
157
+ config(config, { command }) {
158
+ watchMode = command === "serve";
159
+ configContext = {
160
+ root: config.root || ".",
161
+ isProd: isProdMode(config.mode),
162
+ isLib: !!config.build?.lib
163
+ };
164
+ const depOptimizer = createDepOptimizerConfig({
165
+ tsconfig: resolveTsConfigPath(),
166
+ isProd: configContext.isProd,
167
+ jit: false,
168
+ watchMode,
169
+ isTest: options.isTest,
170
+ isAstroIntegration: options.isAstroIntegration
171
+ });
172
+ return {
173
+ ...vite.rolldownVersion ? { oxc: {} } : { esbuild: false },
174
+ ...depOptimizer
175
+ };
176
+ },
177
+ async configResolved(config) {
178
+ resolvedConfig = config;
179
+ transformFilter = (await discoverAnalogIntegrations(config)).transformFilter;
180
+ },
181
+ configureServer(server) {
182
+ const changeTypes = {
183
+ add: 1,
184
+ change: 2,
185
+ unlink: 3
186
+ };
187
+ server.watcher.on("all", (event, path) => {
188
+ const type = changeTypes[event];
189
+ if (type) typeChecker?.notifyFileChanged(path, type);
190
+ });
191
+ server.httpServer?.on("close", () => {
192
+ typeChecker?.close();
193
+ typeChecker = void 0;
194
+ analyzer?.close();
195
+ analyzer = void 0;
196
+ compiler = void 0;
197
+ });
198
+ },
199
+ async buildStart() {
200
+ activeBuilds++;
201
+ if (!analyzer) {
202
+ const tsconfig = resolveTsConfigPath();
203
+ const ngp = await loadNgp(tsconfig);
204
+ api = ngp.api;
205
+ analyzer = await api.createAnalyzer(tsconfig, ngp.analyzerOptions);
206
+ pending = indexChunks();
207
+ }
208
+ await pending;
209
+ for (const path of watchedFiles) this.addWatchFile(path);
210
+ },
211
+ async transform(code, id) {
212
+ if (!filter(id) || transformFilter?.(code, id) === false) return;
213
+ const filePath = vite.normalizePath(id.split("?")[0]);
214
+ await pending;
215
+ let result = await compileFile(filePath, (path) => this.addWatchFile(path));
216
+ if (result && result.magicString.original !== code) {
217
+ await enqueueIndex(() => analyzer.updateFileContent([{
218
+ filePath,
219
+ content: code
220
+ }]));
221
+ result = await compileFile(filePath, (path) => this.addWatchFile(path));
222
+ } else if (!result && options.disableTypeChecking !== true) await checkTypes(filePath, code);
223
+ const source = result?.magicString.toString() ?? code;
224
+ const map = result?.magicString.generateMap({
225
+ source: filePath,
226
+ includeContent: true,
227
+ hires: true
228
+ });
229
+ return vite.transformWithOxc ? vite.transformWithOxc(source, filePath, {
230
+ lang: "ts",
231
+ sourcemap: true
232
+ }, map) : vite.transformWithEsbuild(source, filePath, {
233
+ loader: "ts",
234
+ sourcemap: true
235
+ }, map);
236
+ },
237
+ async handleHotUpdate(ctx) {
238
+ await enqueueIndex(() => analyzer.invalidateFiles([{
239
+ filePath: ctx.file,
240
+ updateType: 2
241
+ }]));
242
+ ctx.server.moduleGraph.invalidateAll();
243
+ ctx.server.ws.send({ type: "full-reload" });
244
+ return [];
245
+ },
246
+ async buildEnd(error) {
247
+ if (error || watchMode || !typeChecker) return;
248
+ const typeErrors = await typeChecker.flushQueue();
249
+ if (typeErrors.length) throw new Error(typeErrors.join("\n"));
250
+ },
251
+ async closeBundle() {
252
+ activeBuilds = Math.max(0, activeBuilds - 1);
253
+ if (watchMode || activeBuilds > 0) return;
254
+ await pending.catch(() => {});
255
+ typeChecker?.close();
256
+ typeChecker = void 0;
257
+ analyzer?.close();
258
+ analyzer = void 0;
259
+ compiler = void 0;
260
+ filesByPath.clear();
261
+ chunkContexts.clear();
262
+ output.clear();
263
+ watchedFiles.clear();
264
+ releaseCssPreprocessorWorkers();
265
+ }
266
+ };
267
+ }
268
+ //#endregion
269
+ export { ngpCompilePlugin };
270
+
271
+ //# sourceMappingURL=ngp-compile-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ngp-compile-plugin.js","names":[],"sources":["../../../src/lib/ngp-compile-plugin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type MagicString from 'magic-string';\nimport * as vite from 'vite';\nimport {\n discoverAnalogIntegrations,\n type TransformFilter,\n} from './analog-plugin-interop.js';\nimport type { FastCompilePluginOptions } from './fast-compile-plugin.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 {\n LspTypeChecker,\n type FileChangeType,\n} from './utils/lsp-type-checker.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 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}\n\ninterface NgpResult {\n magicString: MagicString;\n diagnostics?: NgpDiagnostic[];\n tcb?: { code: 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 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 NgpAnalyzerOptions {\n nativeBinding?: string;\n backend?: 'wasm';\n wasmBinding?: string;\n}\n\ninterface NgpApi {\n createAnalyzer(\n tsconfig: string,\n options: NgpAnalyzerOptions,\n ): Promise<NgpAnalyzer>;\n HybridCompiler: new (\n analyzer: NgpAnalyzer,\n options: { optimize: boolean },\n ) => NgpCompiler;\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\nasync function loadNgp(\n tsconfig: string,\n): Promise<{ api: NgpApi; analyzerOptions: NgpAnalyzerOptions }> {\n const nativeBinding = process.env['ANALOG_NGP_NATIVE_BINDING'];\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 ? { nativeBinding } : {},\n };\n}\n\nexport function ngpCompilePlugin(\n options: FastCompilePluginOptions,\n): vite.Plugin {\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;\n let resolvedConfig: vite.ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let watchMode = 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 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 watchedFiles = new Set<string>();\n let pending = Promise.resolve();\n const filter = vite.createFilter(TS_EXT_REGEX, [\n /node_modules/,\n /[?&]raw\\b/,\n /type=script/,\n /@ng\\/component/,\n ]);\n\n function resolveTsConfigPath() {\n return getTsConfigPath(\n configContext.root,\n options.tsconfigGetter(),\n configContext.isProd,\n options.isTest,\n configContext.isLib,\n options.workspaceRoot,\n );\n }\n\n async function prepareResources(\n file: NgpFile,\n watch: (path: string) => void,\n ): Promise<NgpFile> {\n watch(file.filePath);\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) watch(component.templateUrl.resolvedPath);\n for (const style of component.styleUrls ?? [])\n watch(style.resolvedPath);\n const preprocess = async (content: string, path: string) => {\n const result = await vite.preprocessCSS(\n content,\n path,\n resolvedConfig,\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 `${file.filePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`,\n ),\n ),\n )),\n stylesFromUrls:\n component.stylesFromUrls &&\n (await Promise.all(\n component.stylesFromUrls.map((style, index) =>\n preprocess(style, component.styleUrls![index].resolvedPath),\n ),\n )),\n },\n };\n }),\n ),\n };\n }\n\n async function indexChunks(update?: () => Promise<string[]>) {\n if (update) {\n const invalidated = await update();\n for (const filePath of invalidated) {\n output.delete(vite.normalizePath(filePath));\n }\n chunkContexts.clear();\n } else {\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n compiler = new api.HybridCompiler(analyzer!, { optimize: true });\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 = vite.normalizePath(file.filePath);\n filesByPath.set(normPath, { file, chunk });\n output.delete(normPath);\n }\n }\n }\n\n function enqueueIndex(update: () => Promise<string[]>) {\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 ) {\n typeChecker ??= new LspTypeChecker(\n resolveTsConfigPath(),\n options.typeChecker,\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 function compileFile(\n normPath: string,\n watch: (path: string) => void,\n ): Promise<NgpResult> | undefined {\n const entry = filesByPath.get(normPath);\n if (!entry) return undefined;\n let task = output.get(normPath);\n if (!task) {\n task = (async () => {\n const activeAnalyzer = analyzer!;\n const activeCompiler = compiler!;\n const trackWatch = (path: string) => {\n watchedFiles.add(path);\n watch(path);\n };\n const [file, context, content] = await Promise.all([\n prepareResources(entry.file, trackWatch),\n getChunkContext(entry.chunk),\n activeAnalyzer.getFileContent(entry.file.filePath),\n ]);\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 const errors = [\n ...(file.diagnostics ?? []),\n ...(result.diagnostics ?? []),\n ].filter((diagnostic) => diagnostic.category === 1);\n if (errors.length) {\n throw new Error(\n `${file.filePath}: ${errors.map((error) => error.messageText).join('\\n')}`,\n );\n }\n if (options.disableTypeChecking !== true) {\n await checkTypes(file.filePath, content, result.tcb?.code);\n }\n return result;\n })();\n output.set(normPath, task);\n }\n return task;\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-ngp',\n enforce: 'pre',\n api: { getTsConfigPath: resolveTsConfigPath, output, ready: () => pending },\n config(config, { command }) {\n watchMode = command === 'serve';\n configContext = {\n root: config.root || '.',\n isProd: isProdMode(config.mode),\n isLib: !!config.build?.lib,\n };\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: resolveTsConfigPath(),\n isProd: configContext.isProd,\n jit: false,\n watchMode,\n isTest: options.isTest,\n isAstroIntegration: options.isAstroIntegration,\n });\n return {\n ...(vite.rolldownVersion ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n const integrations = await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n },\n configureServer(server) {\n const changeTypes: Record<string, FileChangeType> = {\n add: 1,\n change: 2,\n unlink: 3,\n };\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 async buildStart() {\n activeBuilds++;\n if (!analyzer) {\n const tsconfig = resolveTsConfigPath();\n const ngp = await loadNgp(tsconfig);\n api = ngp.api;\n analyzer = await api.createAnalyzer(tsconfig, ngp.analyzerOptions);\n pending = indexChunks();\n }\n await pending;\n for (const path of watchedFiles) {\n this.addWatchFile(path);\n }\n },\n async transform(code, id) {\n if (!filter(id) || transformFilter?.(code, id) === false) return;\n const filePath = vite.normalizePath(id.split('?')[0]);\n await pending;\n let result = await compileFile(filePath, (path) =>\n this.addWatchFile(path),\n );\n if (result && result.magicString.original !== code) {\n await enqueueIndex(() =>\n analyzer!.updateFileContent([{ filePath, content: code }]),\n );\n result = await compileFile(filePath, (path) => this.addWatchFile(path));\n } else if (!result && options.disableTypeChecking !== true) {\n await checkTypes(filePath, code);\n }\n const source = result?.magicString.toString() ?? code;\n const map = result?.magicString.generateMap({\n source: filePath,\n includeContent: true,\n hires: true,\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 async handleHotUpdate(ctx) {\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([{ filePath: ctx.file, updateType: 2 }]),\n );\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 watchedFiles.clear();\n releaseCssPreprocessorWorkers();\n },\n };\n}\n"],"mappings":";;;;;;;;;;AA6FA,IAAM,cAAc,IAAA,IAAA,cAAA,KAAA,YAAA,GAAA;AAEpB,eAAe,QACb,UAC+D;CAC/D,MAAM,gBAAgB,QAAQ,IAAI;CAClC,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,gBAAgB,EAAE,cAAc,IAAI,CAAC;CACxD;AACF;AAEA,SAAgB,iBACd,SACa;CACb,IAAI,QAAQ,OAAO,QAAQ,oBAAoB,WAC7C,MAAM,IAAI,MACR,qEACF;CAGF,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,YAAY;CAChB,IAAI,eAAe;CACnB,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM,8BAAc,IAAI,IAAgD;CACxE,MAAM,gCAAgB,IAAI,IAAgC;CAC1D,MAAM,yBAAS,IAAI,IAAgC;CACnD,MAAM,+BAAe,IAAI,IAAY;CACrC,IAAI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AAgB;IAChB,OAAO;GACT,CAAC;GACD,OAAO,KAAK,mBACR,KAAK,iBACH,QACA,UACA;IAAE,MAAM;IAAM,WAAW;GAAK,GAC9B,GACF,IACA,KAAK,qBACH,QACA,UACA;IAAE,QAAQ;IAAM,WAAW;GAAK,GAChC,GACF;EACN;EACA,MAAM,gBAAgB,KAAK;GACzB,MAAM,mBACJ,SAAU,gBAAgB,CAAC;IAAE,UAAU,IAAI;IAAM,YAAY;GAAE,CAAC,CAAC,CACnE;GACA,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,aAAa,MAAM;GACnB,8BAA8B;EAChC;CACF;AACF"}
@@ -0,0 +1,55 @@
1
+ export interface TcbTemplateSource {
2
+ templateFile?: string;
3
+ templateExpression?: {
4
+ start: number;
5
+ end: number;
6
+ };
7
+ }
8
+ type TemplateSources = Record<string, TcbTemplateSource>;
9
+ interface TcbLineRange {
10
+ startLine: number;
11
+ endLine: number;
12
+ filePath: string;
13
+ sourceCode: string;
14
+ templateSources: TemplateSources;
15
+ }
16
+ /** NGP's footer comment mapping TCB ids to the template they were generated from. */
17
+ export declare const TCB_TEMPLATE_SOURCES_PREFIX = "ngp-tcb-template-sources:";
18
+ export declare function readSpanComment(value: string): {
19
+ start: number;
20
+ end: number;
21
+ } | null;
22
+ export type TypeCheckerOption = "tsgo" | "tsrs" | {
23
+ command: string;
24
+ args?: string[];
25
+ };
26
+ interface TypeCheckerCommand {
27
+ command: string;
28
+ args: string[];
29
+ }
30
+ /** LSP `FileChangeType`: 1 created, 2 changed, 3 deleted. */
31
+ export type FileChangeType = 1 | 2 | 3;
32
+ export declare function resolveTypeChecker(tsconfig: string, option: TypeCheckerOption): TypeCheckerCommand;
33
+ export declare class LspTypeChecker {
34
+ private proc;
35
+ private seq;
36
+ private pending;
37
+ private versions;
38
+ private queued;
39
+ private buffer;
40
+ private exitError;
41
+ readonly ready: Promise<void>;
42
+ constructor(tsconfig: string, option?: TypeCheckerOption);
43
+ private onData;
44
+ private send;
45
+ private notify;
46
+ private request;
47
+ updateDocument(filePath: string, text: string);
48
+ checkFile(filePath: string, sourceLineCount?: number, lines?: string[], tcbRanges?: TcbLineRange[]): Promise<string[]>;
49
+ /** Reports a change on disk; an open copy is closed so the checker rereads the file. */
50
+ notifyFileChanged(filePath: string, type: FileChangeType);
51
+ queueFile(filePath: string, sourceCode: string, tcbCode?: string | null);
52
+ flushQueue(watchMode?: boolean): Promise<string[]>;
53
+ close();
54
+ }
55
+ export {};