@analogjs/vite-plugin-angular 3.0.0-beta.3 → 3.0.0-beta.30
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.
- package/ngp/LICENSE +21 -0
- package/ngp/api.mjs +46048 -0
- package/ngp/build.json +4 -0
- package/ngp/ng_analyze.cjs +504 -0
- package/ngp/ng_analyze_bg.wasm +0 -0
- package/package.json +1 -1
- package/src/lib/angular-build-optimizer-plugin.js +6 -3
- package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
- package/src/lib/angular-vite-plugin.d.ts +20 -5
- package/src/lib/angular-vite-plugin.js +28 -13
- package/src/lib/angular-vite-plugin.js.map +1 -1
- package/src/lib/compiler/compile.d.ts +1 -1
- package/src/lib/compiler/compile.js +137 -134
- package/src/lib/compiler/compile.js.map +1 -1
- package/src/lib/compiler/defer.d.ts +2 -3
- package/src/lib/compiler/defer.js +11 -13
- package/src/lib/compiler/defer.js.map +1 -1
- package/src/lib/compiler/dts-reader.d.ts +6 -1
- package/src/lib/compiler/dts-reader.js +15 -9
- package/src/lib/compiler/dts-reader.js.map +1 -1
- package/src/lib/compiler/hmr.d.ts +4 -0
- package/src/lib/compiler/hmr.js +7 -2
- package/src/lib/compiler/hmr.js.map +1 -1
- package/src/lib/compiler/index.d.ts +2 -2
- package/src/lib/compiler/index.js +3 -3
- package/src/lib/compiler/jit-metadata.d.ts +3 -1
- package/src/lib/compiler/jit-metadata.js +10 -8
- package/src/lib/compiler/jit-metadata.js.map +1 -1
- package/src/lib/compiler/jit-transform.js +2 -2
- package/src/lib/compiler/jit-transform.js.map +1 -1
- package/src/lib/compiler/js-emitter.d.ts +0 -3
- package/src/lib/compiler/js-emitter.js +3 -21
- package/src/lib/compiler/js-emitter.js.map +1 -1
- package/src/lib/compiler/registry.d.ts +7 -1
- package/src/lib/compiler/registry.js +23 -3
- package/src/lib/compiler/registry.js.map +1 -1
- package/src/lib/compiler/resource-inliner.d.ts +1 -1
- package/src/lib/compiler/resource-inliner.js +2 -2
- package/src/lib/compiler/resource-inliner.js.map +1 -1
- package/src/lib/compiler/style-ast.d.ts +1 -1
- package/src/lib/compiler/style-ast.js +2 -2
- package/src/lib/compiler/style-ast.js.map +1 -1
- package/src/lib/compiler/type-elision.d.ts +4 -3
- package/src/lib/compiler/type-elision.js +10 -11
- package/src/lib/compiler/type-elision.js.map +1 -1
- package/src/lib/compiler/utils.d.ts +14 -7
- package/src/lib/compiler/utils.js +38 -9
- package/src/lib/compiler/utils.js.map +1 -1
- package/src/lib/fast-compile-plugin.d.ts +3 -0
- package/src/lib/fast-compile-plugin.js +101 -19
- package/src/lib/fast-compile-plugin.js.map +1 -1
- package/src/lib/live-reload-plugin.d.ts +4 -3
- package/src/lib/live-reload-plugin.js +4 -3
- package/src/lib/live-reload-plugin.js.map +1 -1
- package/src/lib/ngp-compile-plugin.d.ts +3 -0
- package/src/lib/ngp-compile-plugin.js +344 -0
- package/src/lib/ngp-compile-plugin.js.map +1 -0
- package/src/lib/tools/src/builders/vite/vite-build.impl.js +2 -1
- package/src/lib/tools/src/builders/vite/vite-build.impl.js.map +1 -1
- package/src/lib/utils/hmr-component-updates.d.ts +7 -0
- package/src/lib/utils/hmr-component-updates.js +87 -0
- package/src/lib/utils/hmr-component-updates.js.map +1 -0
- package/src/lib/utils/lsp-type-checker.d.ts +55 -0
- package/src/lib/utils/lsp-type-checker.js +502 -0
- package/src/lib/utils/lsp-type-checker.js.map +1 -0
- package/src/lib/utils/plugin-config.d.ts +9 -0
- package/src/lib/utils/plugin-config.js +10 -1
- package/src/lib/utils/plugin-config.js.map +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { findAllClasses, parseOxc } from "./utils.js";
|
|
2
2
|
import "magic-string";
|
|
3
3
|
//#region packages/vite-plugin-angular/src/lib/compiler/type-elision.ts
|
|
4
4
|
/**
|
|
@@ -45,7 +45,7 @@ var TYPE_NODE_TYPES = /* @__PURE__ */ new Set([
|
|
|
45
45
|
* type-only imported names. Avoids double-parsing when both are needed.
|
|
46
46
|
*/
|
|
47
47
|
function analyzeTypeOnlyImports(code, program) {
|
|
48
|
-
const ast = program ??
|
|
48
|
+
const ast = program ?? parseOxc("file.ts", code).program;
|
|
49
49
|
const importedNames = /* @__PURE__ */ new Set();
|
|
50
50
|
for (const node of ast.body) {
|
|
51
51
|
if (node.type !== "ImportDeclaration") continue;
|
|
@@ -103,7 +103,7 @@ function analyzeTypeOnlyImports(code, program) {
|
|
|
103
103
|
};
|
|
104
104
|
}
|
|
105
105
|
/**
|
|
106
|
-
* Walk the program looking for decorated classes with constructors and add
|
|
106
|
+
* Walk the program (including nested scopes) looking for decorated classes with constructors and add
|
|
107
107
|
* the type names from constructor parameter annotations to `valueReferenced`.
|
|
108
108
|
*
|
|
109
109
|
* Constructor parameter types are TypeScript type positions, but for decorated
|
|
@@ -112,11 +112,10 @@ function analyzeTypeOnlyImports(code, program) {
|
|
|
112
112
|
* import of the type therefore must NOT be elided as type-only.
|
|
113
113
|
*/
|
|
114
114
|
function collectConstructorDiTokens(ast, importedNames, valueReferenced) {
|
|
115
|
-
for (const
|
|
116
|
-
const classNode = stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration" ? stmt.declaration : stmt;
|
|
117
|
-
if (!classNode || classNode.type !== "ClassDeclaration" && classNode.type !== "ClassExpression") continue;
|
|
115
|
+
for (const classNode of findAllClasses(ast)) {
|
|
118
116
|
if (!classNode.decorators?.length) continue;
|
|
119
|
-
const
|
|
117
|
+
const ctors = (classNode.body?.body || []).filter((m) => m.type === "MethodDefinition" && m.kind === "constructor");
|
|
118
|
+
const ctor = ctors.find((m) => m.value?.body != null) ?? ctors[0];
|
|
120
119
|
if (!ctor) continue;
|
|
121
120
|
const params = ctor.value?.params?.items || ctor.value?.params || [];
|
|
122
121
|
for (const param of params) {
|
|
@@ -198,12 +197,12 @@ function applyElisionEdits(ms, ast, src, typeOnlyNames) {
|
|
|
198
197
|
* Detects type-only names from `ms.toString()` (the fully-mutated code),
|
|
199
198
|
* but reads import positions from `ms.original` (the coordinate system
|
|
200
199
|
* MagicString expects). `originalProgram`, when provided, must be a parse
|
|
201
|
-
* of `ms.original` — never of the mutated text.
|
|
200
|
+
* of `ms.original` — never of the mutated text. `typeOnlyNames` may be passed
|
|
201
|
+
* when the caller already analysed the mutated code.
|
|
202
202
|
*/
|
|
203
|
-
function elideTypeOnlyImportsMagicString(ms, originalProgram) {
|
|
204
|
-
const typeOnlyNames = detectTypeOnlyImportNames(ms.toString());
|
|
203
|
+
function elideTypeOnlyImportsMagicString(ms, originalProgram, typeOnlyNames = detectTypeOnlyImportNames(ms.toString())) {
|
|
205
204
|
if (typeOnlyNames.size === 0) return;
|
|
206
|
-
applyElisionEdits(ms, originalProgram ??
|
|
205
|
+
applyElisionEdits(ms, originalProgram ?? parseOxc("file.ts", ms.original).program, ms.original, typeOnlyNames);
|
|
207
206
|
}
|
|
208
207
|
//#endregion
|
|
209
208
|
export { detectTypeOnlyImportNames, elideTypeOnlyImportsMagicString };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type-elision.js","names":[],"sources":["../../../../src/lib/compiler/type-elision.ts"],"sourcesContent":["import MagicString from 'magic-string';\nimport { parseSync } from 'oxc-parser';\n\n// ── Type-only import elision via OXC AST ────────────────────────────────\n\n/**\n * AST property keys that represent type-only positions in TypeScript.\n * Identifiers found only under these keys are never emitted as runtime values.\n */\nconst TYPE_POSITION_KEYS = new Set([\n 'typeAnnotation',\n 'typeParameters',\n 'superTypeParameters',\n 'implements',\n 'returnType',\n 'typeArguments',\n]);\n\n/**\n * AST node types that represent type-level constructs.\n * Any identifier nested inside one of these nodes is in a type position.\n */\nconst TYPE_NODE_TYPES = new Set([\n 'TSTypeAnnotation',\n 'TSTypeReference',\n 'TSTypeParameterInstantiation',\n 'TSTypeParameterDeclaration',\n 'TSInterfaceDeclaration',\n 'TSTypeAliasDeclaration',\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSUnionType',\n 'TSIntersectionType',\n 'TSArrayType',\n 'TSTupleType',\n 'TSFunctionType',\n 'TSConstructorType',\n 'TSMappedType',\n 'TSConditionalType',\n 'TSIndexedAccessType',\n 'TSTypeQuery',\n 'TSTypeLiteral',\n 'TSQualifiedName',\n 'TSInterfaceBody',\n]);\n\n/**\n * Internal helper: parse code and return both the AST and the set of\n * type-only imported names. Avoids double-parsing when both are needed.\n */\nfunction analyzeTypeOnlyImports(\n code: string,\n program?: ReturnType<typeof parseSync>['program'],\n): {\n ast: any;\n typeOnlyNames: Set<string>;\n} {\n const ast = program ?? parseSync('file.ts', code).program;\n\n // Step 1 – collect all value-imported names (skip `import type` / `{ type X }`)\n // Namespace imports (`import * as ns`) are intentionally skipped — they are\n // always value imports in TypeScript and cannot be type-only at the\n // declaration level.\n const importedNames = new Set<string>();\n for (const node of (ast as any).body) {\n if (node.type !== 'ImportDeclaration') continue;\n if (node.importKind === 'type') continue; // already type-only\n for (const spec of node.specifiers ?? []) {\n if (spec.importKind === 'type') continue; // already type-only\n importedNames.add(spec.local.name);\n }\n }\n if (importedNames.size === 0) return { ast, typeOnlyNames: new Set() };\n\n // Step 2 – walk AST and collect names referenced in value positions\n const valueReferenced = new Set<string>();\n\n // Pre-pass: constructor parameter types of decorated classes are DI tokens\n // and must be preserved as runtime values, even though they appear in\n // type-annotation positions. Without this, `constructor(svc: MyService)`\n // would erase the `MyService` import and `extractConstructorDeps` would\n // emit `ɵɵinvalidFactory()`.\n collectConstructorDiTokens(ast, importedNames, valueReferenced);\n\n function walk(node: any, inTypePosition: boolean): void {\n if (!node || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item, inTypePosition);\n return;\n }\n\n // Short-circuit: if we found every imported name in a value position, stop\n if (valueReferenced.size === importedNames.size) return;\n\n // If this node's type itself marks a type construct, everything below is type-only\n // Exception: TSAsExpression/TSSatisfiesExpression have a value `expression`\n // child that is NOT in a type position — only the type annotation is.\n if (!inTypePosition && TYPE_NODE_TYPES.has(node.type)) {\n if (\n node.type === 'TSAsExpression' ||\n node.type === 'TSSatisfiesExpression'\n ) {\n // Walk the expression child in value context, type annotation in type context\n walk(node.expression, false);\n walk(node.typeAnnotation, true);\n return;\n }\n inTypePosition = true;\n }\n\n // Type-only exports: `export type { Foo }` or `export { type Foo }`\n // Identifiers inside type-only export specifiers are not value references.\n if (\n !inTypePosition &&\n node.type === 'ExportNamedDeclaration' &&\n !node.source\n ) {\n // Walk the declaration (if any) in value context\n if (node.declaration) walk(node.declaration, false);\n // Walk each specifier, skipping type-only ones\n for (const spec of node.specifiers ?? []) {\n if (node.exportKind === 'type' || spec.exportKind === 'type') continue;\n walk(spec, false);\n }\n return;\n }\n\n if (\n !inTypePosition &&\n node.type === 'Identifier' &&\n importedNames.has(node.name)\n ) {\n valueReferenced.add(node.name);\n return;\n }\n\n for (const key of Object.keys(node)) {\n if (\n key === 'type' ||\n key === 'start' ||\n key === 'end' ||\n key === 'range' ||\n key === 'loc'\n )\n continue;\n const isTypePos = inTypePosition || TYPE_POSITION_KEYS.has(key);\n walk(node[key], isTypePos);\n }\n }\n\n for (const node of (ast as any).body) {\n // Skip import declarations themselves – we already processed them\n if (node.type !== 'ImportDeclaration') {\n walk(node, false);\n }\n }\n\n // Step 3 – names that were imported but never value-referenced are type-only\n const typeOnly = new Set<string>();\n for (const name of importedNames) {\n if (!valueReferenced.has(name)) typeOnly.add(name);\n }\n return { ast, typeOnlyNames: typeOnly };\n}\n\n/**\n * Walk the program looking for decorated classes with constructors and add\n * the type names from constructor parameter annotations to `valueReferenced`.\n *\n * Constructor parameter types are TypeScript type positions, but for decorated\n * classes they double as runtime DI tokens — Angular's compiler reads them\n * via `compileFactoryFunction` to wire `ɵɵdirectiveInject(...)` calls. The\n * import of the type therefore must NOT be elided as type-only.\n */\nfunction collectConstructorDiTokens(\n ast: any,\n importedNames: Set<string>,\n valueReferenced: Set<string>,\n): void {\n for (const stmt of (ast as any).body || []) {\n const classNode =\n stmt.type === 'ExportNamedDeclaration' ||\n stmt.type === 'ExportDefaultDeclaration'\n ? (stmt as any).declaration\n : stmt;\n if (\n !classNode ||\n (classNode.type !== 'ClassDeclaration' &&\n classNode.type !== 'ClassExpression')\n ) {\n continue;\n }\n if (!classNode.decorators?.length) continue;\n\n const ctor = (classNode.body?.body || []).find(\n (m: any) => m.type === 'MethodDefinition' && m.kind === 'constructor',\n );\n if (!ctor) continue;\n\n const params: any[] = ctor.value?.params?.items || ctor.value?.params || [];\n for (const param of params) {\n const actualParam =\n param.type === 'TSParameterProperty' ? param.parameter : param;\n const typeAnn =\n actualParam?.typeAnnotation?.typeAnnotation ??\n param?.typeAnnotation?.typeAnnotation;\n if (!typeAnn) continue;\n collectTypeReferenceNames(typeAnn, importedNames, valueReferenced);\n }\n }\n}\n\n/**\n * Recursively extract identifier names from a TS type expression and mark\n * any that match an imported name as value-referenced.\n */\nfunction collectTypeReferenceNames(\n typeNode: any,\n importedNames: Set<string>,\n valueReferenced: Set<string>,\n): void {\n if (!typeNode || typeof typeNode !== 'object') return;\n if (typeNode.type === 'TSTypeReference' && typeNode.typeName) {\n const name = typeNode.typeName.name;\n if (name && importedNames.has(name)) {\n valueReferenced.add(name);\n }\n // Walk type arguments too (e.g. Foo<Bar>)\n if (typeNode.typeArguments) {\n collectTypeReferenceNames(\n typeNode.typeArguments,\n importedNames,\n valueReferenced,\n );\n }\n } else if (\n typeNode.type === 'TSUnionType' ||\n typeNode.type === 'TSIntersectionType'\n ) {\n for (const t of typeNode.types || []) {\n collectTypeReferenceNames(t, importedNames, valueReferenced);\n }\n } else if (Array.isArray(typeNode)) {\n for (const t of typeNode) {\n collectTypeReferenceNames(t, importedNames, valueReferenced);\n }\n } else if (typeNode.params) {\n // TSTypeParameterInstantiation\n for (const t of typeNode.params) {\n collectTypeReferenceNames(t, importedNames, valueReferenced);\n }\n }\n}\n\n/**\n * Analyse compiled TypeScript source and return the set of imported names\n * that are only referenced in type positions (type annotations, implements\n * clauses, generics, etc.) and can safely be elided.\n *\n * Uses oxc-parser for fast, Rust-based AST analysis — no type-checker needed.\n */\nexport function detectTypeOnlyImportNames(\n code: string,\n program?: ReturnType<typeof parseSync>['program'],\n): Set<string> {\n return analyzeTypeOnlyImports(code, program).typeOnlyNames;\n}\n\n/**\n * Apply import elision edits to a MagicString instance using positions from\n * a parsed AST. Shared logic for both the string-based and MagicString APIs.\n */\nfunction applyElisionEdits(\n ms: MagicString,\n ast: any,\n src: string,\n typeOnlyNames: Set<string>,\n): boolean {\n let edited = false;\n\n for (const node of (ast as any).body) {\n if (node.type !== 'ImportDeclaration') continue;\n if (node.importKind === 'type') continue;\n\n const allSpecs = node.specifiers ?? [];\n\n // Separate default and named specifiers\n const defaultSpec = allSpecs.find(\n (s: any) => s.type === 'ImportDefaultSpecifier',\n );\n const namedSpecs = allSpecs.filter(\n (s: any) => s.type === 'ImportSpecifier' && s.importKind !== 'type',\n );\n\n const elideDefault =\n defaultSpec && typeOnlyNames.has(defaultSpec.local.name);\n const keptNamed = namedSpecs.filter(\n (s: any) => !typeOnlyNames.has(s.local.name),\n );\n const removingNamed = namedSpecs.length - keptNamed.length;\n\n // Nothing to elide from this declaration\n if (!elideDefault && removingNamed === 0) continue;\n\n // Find the end of the declaration including trailing newline\n let declEnd = node.end;\n while (\n declEnd < src.length &&\n (src[declEnd] === '\\n' || src[declEnd] === '\\r')\n )\n declEnd++;\n\n const keepDefault = defaultSpec && !elideDefault;\n const hasKeptNamed = keptNamed.length > 0;\n\n if (!keepDefault && !hasKeptNamed) {\n // Remove entire import declaration\n ms.remove(node.start, declEnd);\n edited = true;\n } else {\n // Rebuild with only the kept specifiers\n const parts: string[] = [];\n if (keepDefault) parts.push(defaultSpec.local.name);\n if (hasKeptNamed) {\n const namedList = keptNamed.map((s: any) => {\n const imported = s.imported?.name ?? s.local.name;\n return imported === s.local.name\n ? s.local.name\n : `${imported} as ${s.local.name}`;\n });\n parts.push(`{ ${namedList.join(', ')} }`);\n }\n const source = node.source.value;\n const quote = src[node.source.start]; // preserve original quote style\n ms.overwrite(\n node.start,\n node.end,\n `import ${parts.join(', ')} from ${quote}${source}${quote};`,\n );\n edited = true;\n }\n }\n\n return edited;\n}\n\n/**\n * Elide import specifiers (or entire import declarations) for names that are\n * only used in type positions. Operates on the compiler's TypeScript output\n * (before OXC strips remaining TS syntax).\n *\n * Returns the modified source code, or the original if nothing was elided.\n */\nexport function elideTypeOnlyImports(code: string): string {\n const { ast, typeOnlyNames } = analyzeTypeOnlyImports(code);\n if (typeOnlyNames.size === 0) return code;\n\n const ms = new MagicString(code);\n const edited = applyElisionEdits(ms, ast, code, typeOnlyNames);\n return edited ? ms.toString() : code;\n}\n\n/**\n * Elide type-only imports directly on a MagicString instance, so that\n * subsequent `ms.generateMap()` calls produce an accurate sourcemap.\n *\n * Detects type-only names from `ms.toString()` (the fully-mutated code),\n * but reads import positions from `ms.original` (the coordinate system\n * MagicString expects). `originalProgram`, when provided, must be a parse\n * of `ms.original` — never of the mutated text.\n */\nexport function elideTypeOnlyImportsMagicString(\n ms: MagicString,\n originalProgram?: ReturnType<typeof parseSync>['program'],\n): void {\n const typeOnlyNames = detectTypeOnlyImportNames(ms.toString());\n if (typeOnlyNames.size === 0) return;\n\n // Parse the original source to get positions in MagicString's coordinate system\n const ast = originalProgram ?? parseSync('file.ts', ms.original).program;\n applyElisionEdits(ms, ast, ms.original, typeOnlyNames);\n}\n"],"mappings":";;;;;;;AASA,IAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,IAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,SAAS,uBACP,MACA,SAIA;CACA,MAAM,MAAM,WAAW,UAAU,WAAW,IAAI,CAAC,CAAC;CAMlD,MAAM,gCAAgB,IA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SAAS;EACX,OAAO;GAEL,MAAM,QAAkB,CAAC;GACzB,IAAI,aAAa,MAAM,KAAK,YAAY,MAAM,IAAI;GAClD,IAAI,cAAc;IAChB,MAAM,YAAY,UAAU,KAAK,MAAW;KAC1C,MAAM,WAAW,EAAE,UAAU,QAAQ,EAAE,MAAM;KAC7C,OAAO,aAAa,EAAE,MAAM,OACxB,EAAE,MAAM,OACR,GAAG,SAAS,MAAM,EAAE,MAAM;IAChC,CAAC;IACD,MAAM,KAAK,KAAK,UAAU,KAAK,IAAI,EAAE,GAAG;GAC1C;GACA,MAAM,SAAS,KAAK,OAAO;GAC3B,MAAM,QAAQ,IAAI,KAAK,OAAO;GAC9B,GAAG,UACD,KAAK,OACL,KAAK,KACL,UAAU,MAAM,KAAK,IAAI,EAAE,QAAQ,QAAQ,SAAS,MAAM,EAC5D;GACA,SAAS;EACX;CACF;CAEA,OAAO;AACT;;;;;;;;;;AA2BA,SAAgB,gCACd,IACA,iBACM;CACN,MAAM,gBAAgB,0BAA0B,GAAG,SAAS,CAAC;CAC7D,IAAI,cAAc,SAAS,GAAG;CAI9B,kBAAkB,IADN,mBAAmB,UAAU,WAAW,GAAG,QAAQ,CAAC,CAAC,SACtC,GAAG,UAAU,aAAa;AACvD"}
|
|
1
|
+
{"version":3,"file":"type-elision.js","names":[],"sources":["../../../../src/lib/compiler/type-elision.ts"],"sourcesContent":["import MagicString from 'magic-string';\nimport type { parseSync } from 'oxc-parser';\nimport { findAllClasses, parseOxc } from './utils.js';\n\n// ── Type-only import elision via OXC AST ────────────────────────────────\n\n/**\n * AST property keys that represent type-only positions in TypeScript.\n * Identifiers found only under these keys are never emitted as runtime values.\n */\nconst TYPE_POSITION_KEYS = new Set([\n 'typeAnnotation',\n 'typeParameters',\n 'superTypeParameters',\n 'implements',\n 'returnType',\n 'typeArguments',\n]);\n\n/**\n * AST node types that represent type-level constructs.\n * Any identifier nested inside one of these nodes is in a type position.\n */\nconst TYPE_NODE_TYPES = new Set([\n 'TSTypeAnnotation',\n 'TSTypeReference',\n 'TSTypeParameterInstantiation',\n 'TSTypeParameterDeclaration',\n 'TSInterfaceDeclaration',\n 'TSTypeAliasDeclaration',\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSUnionType',\n 'TSIntersectionType',\n 'TSArrayType',\n 'TSTupleType',\n 'TSFunctionType',\n 'TSConstructorType',\n 'TSMappedType',\n 'TSConditionalType',\n 'TSIndexedAccessType',\n 'TSTypeQuery',\n 'TSTypeLiteral',\n 'TSQualifiedName',\n 'TSInterfaceBody',\n]);\n\n/**\n * Internal helper: parse code and return both the AST and the set of\n * type-only imported names. Avoids double-parsing when both are needed.\n */\nfunction analyzeTypeOnlyImports(\n code: string,\n program?: ReturnType<typeof parseSync>['program'],\n): {\n ast: any;\n typeOnlyNames: Set<string>;\n} {\n const ast = program ?? parseOxc('file.ts', code).program;\n\n // Step 1 – collect all value-imported names (skip `import type` / `{ type X }`)\n // Namespace imports (`import * as ns`) are intentionally skipped — they are\n // always value imports in TypeScript and cannot be type-only at the\n // declaration level.\n const importedNames = new Set<string>();\n for (const node of (ast as any).body) {\n if (node.type !== 'ImportDeclaration') continue;\n if (node.importKind === 'type') continue; // already type-only\n for (const spec of node.specifiers ?? []) {\n if (spec.importKind === 'type') continue; // already type-only\n importedNames.add(spec.local.name);\n }\n }\n if (importedNames.size === 0) return { ast, typeOnlyNames: new Set() };\n\n // Step 2 – walk AST and collect names referenced in value positions\n const valueReferenced = new Set<string>();\n\n // Pre-pass: constructor parameter types of decorated classes are DI tokens\n // and must be preserved as runtime values, even though they appear in\n // type-annotation positions. Without this, `constructor(svc: MyService)`\n // would erase the `MyService` import and `extractConstructorDeps` would\n // emit `ɵɵinvalidFactory()`.\n collectConstructorDiTokens(ast, importedNames, valueReferenced);\n\n function walk(node: any, inTypePosition: boolean): void {\n if (!node || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item, inTypePosition);\n return;\n }\n\n // Short-circuit: if we found every imported name in a value position, stop\n if (valueReferenced.size === importedNames.size) return;\n\n // If this node's type itself marks a type construct, everything below is type-only\n // Exception: TSAsExpression/TSSatisfiesExpression have a value `expression`\n // child that is NOT in a type position — only the type annotation is.\n if (!inTypePosition && TYPE_NODE_TYPES.has(node.type)) {\n if (\n node.type === 'TSAsExpression' ||\n node.type === 'TSSatisfiesExpression'\n ) {\n // Walk the expression child in value context, type annotation in type context\n walk(node.expression, false);\n walk(node.typeAnnotation, true);\n return;\n }\n inTypePosition = true;\n }\n\n // Type-only exports: `export type { Foo }` or `export { type Foo }`\n // Identifiers inside type-only export specifiers are not value references.\n if (\n !inTypePosition &&\n node.type === 'ExportNamedDeclaration' &&\n !node.source\n ) {\n // Walk the declaration (if any) in value context\n if (node.declaration) walk(node.declaration, false);\n // Walk each specifier, skipping type-only ones\n for (const spec of node.specifiers ?? []) {\n if (node.exportKind === 'type' || spec.exportKind === 'type') continue;\n walk(spec, false);\n }\n return;\n }\n\n if (\n !inTypePosition &&\n node.type === 'Identifier' &&\n importedNames.has(node.name)\n ) {\n valueReferenced.add(node.name);\n return;\n }\n\n for (const key of Object.keys(node)) {\n if (\n key === 'type' ||\n key === 'start' ||\n key === 'end' ||\n key === 'range' ||\n key === 'loc'\n )\n continue;\n const isTypePos = inTypePosition || TYPE_POSITION_KEYS.has(key);\n walk(node[key], isTypePos);\n }\n }\n\n for (const node of (ast as any).body) {\n // Skip import declarations themselves – we already processed them\n if (node.type !== 'ImportDeclaration') {\n walk(node, false);\n }\n }\n\n // Step 3 – names that were imported but never value-referenced are type-only\n const typeOnly = new Set<string>();\n for (const name of importedNames) {\n if (!valueReferenced.has(name)) typeOnly.add(name);\n }\n return { ast, typeOnlyNames: typeOnly };\n}\n\n/**\n * Walk the program (including nested scopes) looking for decorated classes with constructors and add\n * the type names from constructor parameter annotations to `valueReferenced`.\n *\n * Constructor parameter types are TypeScript type positions, but for decorated\n * classes they double as runtime DI tokens — Angular's compiler reads them\n * via `compileFactoryFunction` to wire `ɵɵdirectiveInject(...)` calls. The\n * import of the type therefore must NOT be elided as type-only.\n */\nfunction collectConstructorDiTokens(\n ast: any,\n importedNames: Set<string>,\n valueReferenced: Set<string>,\n): void {\n // Include classes nested in function scopes, which compile() also compiles.\n for (const classNode of findAllClasses(ast)) {\n if (!classNode.decorators?.length) continue;\n\n const ctors = (classNode.body?.body || []).filter(\n (m: any) => m.type === 'MethodDefinition' && m.kind === 'constructor',\n );\n // Match extractConstructorDeps: overload signatures have no body, so read\n // the implementation's parameters.\n const ctor = ctors.find((m: any) => m.value?.body != null) ?? ctors[0];\n if (!ctor) continue;\n\n const params: any[] = ctor.value?.params?.items || ctor.value?.params || [];\n for (const param of params) {\n const actualParam =\n param.type === 'TSParameterProperty' ? param.parameter : param;\n const typeAnn =\n actualParam?.typeAnnotation?.typeAnnotation ??\n param?.typeAnnotation?.typeAnnotation;\n if (!typeAnn) continue;\n collectTypeReferenceNames(typeAnn, importedNames, valueReferenced);\n }\n }\n}\n\n/**\n * Recursively extract identifier names from a TS type expression and mark\n * any that match an imported name as value-referenced.\n */\nfunction collectTypeReferenceNames(\n typeNode: any,\n importedNames: Set<string>,\n valueReferenced: Set<string>,\n): void {\n if (!typeNode || typeof typeNode !== 'object') return;\n if (typeNode.type === 'TSTypeReference' && typeNode.typeName) {\n const name = typeNode.typeName.name;\n if (name && importedNames.has(name)) {\n valueReferenced.add(name);\n }\n // Walk type arguments too (e.g. Foo<Bar>)\n if (typeNode.typeArguments) {\n collectTypeReferenceNames(\n typeNode.typeArguments,\n importedNames,\n valueReferenced,\n );\n }\n } else if (\n typeNode.type === 'TSUnionType' ||\n typeNode.type === 'TSIntersectionType'\n ) {\n for (const t of typeNode.types || []) {\n collectTypeReferenceNames(t, importedNames, valueReferenced);\n }\n } else if (Array.isArray(typeNode)) {\n for (const t of typeNode) {\n collectTypeReferenceNames(t, importedNames, valueReferenced);\n }\n } else if (typeNode.params) {\n // TSTypeParameterInstantiation\n for (const t of typeNode.params) {\n collectTypeReferenceNames(t, importedNames, valueReferenced);\n }\n }\n}\n\n/**\n * Analyse compiled TypeScript source and return the set of imported names\n * that are only referenced in type positions (type annotations, implements\n * clauses, generics, etc.) and can safely be elided.\n *\n * Uses oxc-parser for fast, Rust-based AST analysis — no type-checker needed.\n */\nexport function detectTypeOnlyImportNames(\n code: string,\n program?: ReturnType<typeof parseSync>['program'],\n): Set<string> {\n return analyzeTypeOnlyImports(code, program).typeOnlyNames;\n}\n\n/**\n * Apply import elision edits to a MagicString instance using positions from\n * a parsed AST. Shared logic for both the string-based and MagicString APIs.\n */\nfunction applyElisionEdits(\n ms: MagicString,\n ast: any,\n src: string,\n typeOnlyNames: Set<string>,\n): boolean {\n let edited = false;\n\n for (const node of (ast as any).body) {\n if (node.type !== 'ImportDeclaration') continue;\n if (node.importKind === 'type') continue;\n\n const allSpecs = node.specifiers ?? [];\n\n // Separate default and named specifiers\n const defaultSpec = allSpecs.find(\n (s: any) => s.type === 'ImportDefaultSpecifier',\n );\n const namedSpecs = allSpecs.filter(\n (s: any) => s.type === 'ImportSpecifier' && s.importKind !== 'type',\n );\n\n const elideDefault =\n defaultSpec && typeOnlyNames.has(defaultSpec.local.name);\n const keptNamed = namedSpecs.filter(\n (s: any) => !typeOnlyNames.has(s.local.name),\n );\n const removingNamed = namedSpecs.length - keptNamed.length;\n\n // Nothing to elide from this declaration\n if (!elideDefault && removingNamed === 0) continue;\n\n // Find the end of the declaration including trailing newline\n let declEnd = node.end;\n while (\n declEnd < src.length &&\n (src[declEnd] === '\\n' || src[declEnd] === '\\r')\n )\n declEnd++;\n\n const keepDefault = defaultSpec && !elideDefault;\n const hasKeptNamed = keptNamed.length > 0;\n\n if (!keepDefault && !hasKeptNamed) {\n // Remove entire import declaration\n ms.remove(node.start, declEnd);\n edited = true;\n } else {\n // Rebuild with only the kept specifiers\n const parts: string[] = [];\n if (keepDefault) parts.push(defaultSpec.local.name);\n if (hasKeptNamed) {\n const namedList = keptNamed.map((s: any) => {\n const imported = s.imported?.name ?? s.local.name;\n return imported === s.local.name\n ? s.local.name\n : `${imported} as ${s.local.name}`;\n });\n parts.push(`{ ${namedList.join(', ')} }`);\n }\n const source = node.source.value;\n const quote = src[node.source.start]; // preserve original quote style\n ms.overwrite(\n node.start,\n node.end,\n `import ${parts.join(', ')} from ${quote}${source}${quote};`,\n );\n edited = true;\n }\n }\n\n return edited;\n}\n\n/**\n * Elide import specifiers (or entire import declarations) for names that are\n * only used in type positions. Operates on the compiler's TypeScript output\n * (before OXC strips remaining TS syntax).\n *\n * Returns the modified source code, or the original if nothing was elided.\n */\nexport function elideTypeOnlyImports(code: string): string {\n const { ast, typeOnlyNames } = analyzeTypeOnlyImports(code);\n if (typeOnlyNames.size === 0) return code;\n\n const ms = new MagicString(code);\n const edited = applyElisionEdits(ms, ast, code, typeOnlyNames);\n return edited ? ms.toString() : code;\n}\n\n/**\n * Elide type-only imports directly on a MagicString instance, so that\n * subsequent `ms.generateMap()` calls produce an accurate sourcemap.\n *\n * Detects type-only names from `ms.toString()` (the fully-mutated code),\n * but reads import positions from `ms.original` (the coordinate system\n * MagicString expects). `originalProgram`, when provided, must be a parse\n * of `ms.original` — never of the mutated text. `typeOnlyNames` may be passed\n * when the caller already analysed the mutated code.\n */\nexport function elideTypeOnlyImportsMagicString(\n ms: MagicString,\n originalProgram?: ReturnType<typeof parseSync>['program'],\n typeOnlyNames = detectTypeOnlyImportNames(ms.toString()),\n): void {\n if (typeOnlyNames.size === 0) return;\n\n // Parse the original source to get positions in MagicString's coordinate system\n const ast = originalProgram ?? parseOxc('file.ts', ms.original).program;\n applyElisionEdits(ms, ast, ms.original, typeOnlyNames);\n}\n"],"mappings":";;;;;;;AAUA,IAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,IAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAC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AI,CAAC,eAAe,CAAC,cAAc;GAEjC,GAAG,OAAO,KAAK,OAAO,OAAO;GAC7B,SAAS;EACX,OAAO;GAEL,MAAM,QAAkB,CAAC;GACzB,IAAI,aAAa,MAAM,KAAK,YAAY,MAAM,IAAI;GAClD,IAAI,cAAc;IAChB,MAAM,YAAY,UAAU,KAAK,MAAW;KAC1C,MAAM,WAAW,EAAE,UAAU,QAAQ,EAAE,MAAM;KAC7C,OAAO,aAAa,EAAE,MAAM,OACxB,EAAE,MAAM,OACR,GAAG,SAAS,MAAM,EAAE,MAAM;IAChC,CAAC;IACD,MAAM,KAAK,KAAK,UAAU,KAAK,IAAI,EAAE,GAAG;GAC1C;GACA,MAAM,SAAS,KAAK,OAAO;GAC3B,MAAM,QAAQ,IAAI,KAAK,OAAO;GAC9B,GAAG,UACD,KAAK,OACL,KAAK,KACL,UAAU,MAAM,KAAK,IAAI,EAAE,QAAQ,QAAQ,SAAS,MAAM,EAC5D;GACA,SAAS;EACX;CACF;CAEA,OAAO;AACT;;;;;;;;;;;AA4BA,SAAgB,gCACd,IACA,iBACA,gBAAgB,0BAA0B,GAAG,SAAS,CAAC,GACjD;CACN,IAAI,cAAc,SAAS,GAAG;CAI9B,kBAAkB,IADN,mBAAmB,SAAS,WAAW,GAAG,QAAQ,CAAC,CAAC,SACrC,GAAG,UAAU,aAAa;AACvD"}
|
|
@@ -1,10 +1,17 @@
|
|
|
1
|
-
import
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
export declare function
|
|
1
|
+
import { type ParseResult } from "oxc-parser";
|
|
2
|
+
/**
|
|
3
|
+
* Parse with oxc-parser, using raw transfer when the platform supports it.
|
|
4
|
+
* Falls back to the default transfer for this and later calls if raw
|
|
5
|
+
* transfer throws (e.g. its large buffer cannot be allocated).
|
|
6
|
+
*/
|
|
7
|
+
export declare function parseOxc(fileName: string, code: string): ParseResult;
|
|
8
|
+
/** Recursively find all class declarations in an OXC AST, including nested scopes. */
|
|
9
|
+
export declare function findAllClasses(program: any): any[];
|
|
10
|
+
/**
|
|
11
|
+
* Depth-first walk over OXC AST nodes. `visit` returns `false` to skip a
|
|
12
|
+
* node's children.
|
|
13
|
+
*/
|
|
14
|
+
export declare function walkOxc(node: any, visit: (node: any) => boolean): void;
|
|
8
15
|
/** Unwrap forwardRef(() => X) to X for OXC AST nodes. Returns the original node if not a forwardRef call. */
|
|
9
16
|
export declare function unwrapForwardRefOxc(node: any): any;
|
|
10
17
|
/**
|
|
@@ -1,17 +1,46 @@
|
|
|
1
1
|
import "./constants.js";
|
|
2
2
|
import * as path$1 from "node:path";
|
|
3
|
-
import
|
|
3
|
+
import { parseSync, rawTransferSupported } from "oxc-parser";
|
|
4
4
|
//#region packages/vite-plugin-angular/src/lib/compiler/utils.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
5
|
+
var rawTransferOptions = { experimentalRawTransfer: true };
|
|
6
|
+
var useRawTransfer = rawTransferSupported();
|
|
7
|
+
/**
|
|
8
|
+
* Parse with oxc-parser, using raw transfer when the platform supports it.
|
|
9
|
+
* Falls back to the default transfer for this and later calls if raw
|
|
10
|
+
* transfer throws (e.g. its large buffer cannot be allocated).
|
|
11
|
+
*/
|
|
12
|
+
function parseOxc(fileName, code) {
|
|
13
|
+
if (useRawTransfer) try {
|
|
14
|
+
return parseSync(fileName, code, rawTransferOptions);
|
|
15
|
+
} catch {
|
|
16
|
+
useRawTransfer = false;
|
|
11
17
|
}
|
|
12
|
-
|
|
18
|
+
return parseSync(fileName, code);
|
|
19
|
+
}
|
|
20
|
+
/** Recursively find all class declarations in an OXC AST, including nested scopes. */
|
|
21
|
+
function findAllClasses(program) {
|
|
22
|
+
const result = [];
|
|
23
|
+
walkOxc(program, (node) => {
|
|
24
|
+
if (node.type === "ClassDeclaration") result.push(node);
|
|
25
|
+
return true;
|
|
26
|
+
});
|
|
13
27
|
return result;
|
|
14
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Depth-first walk over OXC AST nodes. `visit` returns `false` to skip a
|
|
31
|
+
* node's children.
|
|
32
|
+
*/
|
|
33
|
+
function walkOxc(node, visit) {
|
|
34
|
+
if (Array.isArray(node)) {
|
|
35
|
+
for (const child of node) walkOxc(child, visit);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (!node || typeof node.type !== "string" || !visit(node)) return;
|
|
39
|
+
for (const key in node) {
|
|
40
|
+
const value = node[key];
|
|
41
|
+
if (value && typeof value === "object") walkOxc(value, visit);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
15
44
|
/** Unwrap forwardRef(() => X) to X for OXC AST nodes. Returns the original node if not a forwardRef call. */
|
|
16
45
|
function unwrapForwardRefOxc(node) {
|
|
17
46
|
if (node?.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "forwardRef") {
|
|
@@ -73,6 +102,6 @@ function deriveRelativeImportPath(fromFile, toFile) {
|
|
|
73
102
|
return rel;
|
|
74
103
|
}
|
|
75
104
|
//#endregion
|
|
76
|
-
export { deriveRelativeImportPath, findAllClasses, resolveSyntheticImportSpecifier, unwrapForwardRefOxc };
|
|
105
|
+
export { deriveRelativeImportPath, findAllClasses, parseOxc, resolveSyntheticImportSpecifier, unwrapForwardRefOxc, walkOxc };
|
|
77
106
|
|
|
78
107
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/lib/compiler/utils.ts"],"sourcesContent":["import * as
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/lib/compiler/utils.ts"],"sourcesContent":["import * as path from 'node:path';\nimport {\n parseSync,\n rawTransferSupported,\n type ParseResult,\n type ParserOptions,\n} from 'oxc-parser';\n\n// Raw transfer reads the AST straight from Rust memory instead of going\n// through JSON (~3x faster). Not yet in oxc-parser's published types.\nconst rawTransferOptions = { experimentalRawTransfer: true } as ParserOptions;\nlet useRawTransfer = rawTransferSupported();\n\n/**\n * Parse with oxc-parser, using raw transfer when the platform supports it.\n * Falls back to the default transfer for this and later calls if raw\n * transfer throws (e.g. its large buffer cannot be allocated).\n */\nexport function parseOxc(fileName: string, code: string): ParseResult {\n if (useRawTransfer) {\n try {\n return parseSync(fileName, code, rawTransferOptions);\n } catch {\n useRawTransfer = false;\n }\n }\n return parseSync(fileName, code);\n}\n\n/** Recursively find all class declarations in an OXC AST, including nested scopes. */\nexport function findAllClasses(program: any): any[] {\n const result: any[] = [];\n walkOxc(program, (node) => {\n if (node.type === 'ClassDeclaration') result.push(node);\n return true;\n });\n return result;\n}\n\n/**\n * Depth-first walk over OXC AST nodes. `visit` returns `false` to skip a\n * node's children.\n */\nexport function walkOxc(node: any, visit: (node: any) => boolean): void {\n if (Array.isArray(node)) {\n for (const child of node) walkOxc(child, visit);\n return;\n }\n if (!node || typeof node.type !== 'string' || !visit(node)) return;\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === 'object') walkOxc(value, visit);\n }\n}\n\n/** Unwrap forwardRef(() => X) to X for OXC AST nodes. Returns the original node if not a forwardRef call. */\nexport function unwrapForwardRefOxc(node: any): any {\n if (\n node?.type === 'CallExpression' &&\n node.callee?.type === 'Identifier' &&\n node.callee.name === 'forwardRef'\n ) {\n const arg = node.arguments?.[0];\n if (arg?.type === 'ArrowFunctionExpression') {\n if (\n arg.body?.type === 'FunctionBody' ||\n arg.body?.type === 'BlockStatement'\n ) {\n const stmts = arg.body.statements || arg.body.body || [];\n const stmt = stmts[0];\n if (stmt?.type === 'ReturnStatement' && stmt.argument)\n return stmt.argument;\n } else {\n // Expression body: forwardRef(() => X)\n return arg.body;\n }\n }\n if (arg?.type === 'FunctionExpression') {\n const stmts = arg.body?.statements || arg.body?.body || [];\n if (stmts.length === 1) {\n const stmt = stmts[0];\n if (stmt?.type === 'ReturnStatement' && stmt.argument)\n return stmt.argument;\n }\n }\n }\n return node;\n}\n\n/**\n * Resolve the module specifier to use for a synthetic import of a registry\n * declaration referenced from `currentFileName`.\n *\n * Order of preference:\n * 1. `entry.sourcePackage` — external packages scanned from `.d.ts` resolve\n * via their package name (proper barrel exports).\n * 2. A relative path derived from `currentFileName` to `entry.fileName` — for\n * local workspace classes scanned from real source files. This is what\n * NgModule/tuple export expansion must use: the class lives in its own\n * file, not the module/barrel file that re-exports it, so importing from\n * the module specifier fails with\n * `\"X\" is not exported by \".../the.module.ts\"`.\n * 3. `fallbackSpecifier` — the import path of the module/tuple itself, used\n * for `.d.ts` entries (whose file path is not a usable import target) and\n * when the registry has no file location for the class.\n *\n * Returns `undefined` when the class is declared in `currentFileName` itself\n * (already in scope — no synthetic import needed).\n */\nexport function resolveSyntheticImportSpecifier(\n currentFileName: string,\n entry: { sourcePackage?: string; fileName?: string },\n fallbackSpecifier: string | undefined,\n): string | undefined {\n if (entry.sourcePackage) return entry.sourcePackage;\n // `.d.ts` entries come from scanning external package type declarations;\n // their file path is not a usable relative import target, so defer to the\n // module/tuple specifier the consumer already imports from.\n if (entry.fileName && !entry.fileName.endsWith('.d.ts')) {\n if (entry.fileName === currentFileName) return undefined;\n return deriveRelativeImportPath(currentFileName, entry.fileName);\n }\n return fallbackSpecifier;\n}\n\n/**\n * Derive a relative module specifier from `fromFile` to `toFile`, suitable for\n * a synthetic `import { … } from '…'` statement: strips the file extension,\n * normalizes to POSIX separators, and ensures an explicit `./` prefix.\n */\nexport function deriveRelativeImportPath(\n fromFile: string,\n toFile: string,\n): string {\n let rel = path.relative(path.dirname(fromFile), toFile);\n rel = rel.replace(/\\.[cm]?[jt]sx?$/, '');\n rel = rel.split(path.sep).join('/');\n if (!rel.startsWith('.')) rel = './' + rel;\n return rel;\n}\n\nexport { ANGULAR_DECORATORS } from './constants.js';\n"],"mappings":";;;;AAUA,IAAM,qBAAqB,EAAE,yBAAyB,KAAK;AAC3D,IAAI,iBAAiB,qBAAqB;;;;;;AAO1C,SAAgB,SAAS,UAAkB,MAA2B;CAC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ChB;EACF;CACF;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,gCACd,iBACA,OACA,mBACoB;CACpB,IAAI,MAAM,eAAe,OAAO,MAAM;CAItC,IAAI,MAAM,YAAY,CAAC,MAAM,SAAS,SAAS,OAAO,GAAG;EACvD,IAAI,MAAM,aAAa,iBAAiB,OAAO,KAAA;EAC/C,OAAO,yBAAyB,iBAAiB,MAAM,QAAQ;CACjE;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,yBACd,UACA,QACQ;CACR,IAAI,MAAM,OAAK,SAAS,OAAK,QAAQ,QAAQ,GAAG,MAAM;CACtD,MAAM,IAAI,QAAQ,mBAAmB,EAAE;CACvC,MAAM,IAAI,MAAM,OAAK,GAAG,CAAC,CAAC,KAAK,GAAG;CAClC,IAAI,CAAC,IAAI,WAAW,GAAG,GAAG,MAAM,OAAO;CACvC,OAAO;AACT"}
|
|
@@ -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,13 +1,14 @@
|
|
|
1
|
-
import { TS_EXT_REGEX, createDepOptimizerConfig, getTsConfigPath, isProdMode } from "./utils/plugin-config.js";
|
|
1
|
+
import { EXCLUDED_TS_EXT_REGEX, TS_EXT_REGEX, createDepOptimizerConfig, getTsConfigPath, isProdMode } from "./utils/plugin-config.js";
|
|
2
2
|
import { discoverAnalogIntegrations } from "./analog-plugin-interop.js";
|
|
3
3
|
import { releaseCssPreprocessorWorkers } from "./utils/css-preprocessor-workers.js";
|
|
4
4
|
import { toVirtualRawId } from "./utils/virtual-ids.js";
|
|
5
5
|
import { loadVirtualRawModule, rewriteHtmlRawImport } from "./utils/virtual-resources.js";
|
|
6
6
|
import { ANGULAR_DECORATOR_CALL_RE } from "./compiler/constants.js";
|
|
7
|
+
import { parseOxc } from "./compiler/utils.js";
|
|
7
8
|
import { debugCompile, debugRegistry } from "./compiler/debug.js";
|
|
8
9
|
import { compile } from "./compiler/compile.js";
|
|
9
|
-
import { scanFile } from "./compiler/registry.js";
|
|
10
|
-
import { collectAllImports, collectImportedPackages, collectRelativeReExports, scanPackageDts } from "./compiler/dts-reader.js";
|
|
10
|
+
import { declaresNonStandaloneComponent, scanFile } from "./compiler/registry.js";
|
|
11
|
+
import { collectAllImports, collectImportedPackages, collectReExports, collectRelativeReExports, scanPackageDts } from "./compiler/dts-reader.js";
|
|
11
12
|
import { jitTransform } from "./compiler/jit-transform.js";
|
|
12
13
|
import { generateHmrCode } from "./compiler/hmr.js";
|
|
13
14
|
import { extractInlineStyles, inlineResourceUrls } from "./compiler/resource-inliner.js";
|
|
@@ -18,7 +19,6 @@ import { dirname, isAbsolute, resolve } from "node:path";
|
|
|
18
19
|
import * as vite from "vite";
|
|
19
20
|
import { normalizePath, preprocessCSS } from "vite";
|
|
20
21
|
import * as compilerCli from "@angular/compiler-cli";
|
|
21
|
-
import { parseSync } from "oxc-parser";
|
|
22
22
|
//#region packages/vite-plugin-angular/src/lib/fast-compile-plugin.ts
|
|
23
23
|
/**
|
|
24
24
|
* Directory that `compilerOptions.paths` targets resolve against. Mirrors
|
|
@@ -40,6 +40,10 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
40
40
|
const scannedDtsPackages = /* @__PURE__ */ new Set();
|
|
41
41
|
let projectRoot = "";
|
|
42
42
|
let useDefineForClassFields = true;
|
|
43
|
+
let tsConfig;
|
|
44
|
+
const lazyScans = /* @__PURE__ */ new Map();
|
|
45
|
+
const importersByFile = /* @__PURE__ */ new Map();
|
|
46
|
+
let projectScan;
|
|
43
47
|
/**
|
|
44
48
|
* Scan a file into the registry, then recursively walk its relative
|
|
45
49
|
* `export *` / `export { … } from './x'` chain so any underlying
|
|
@@ -69,7 +73,7 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
69
73
|
}
|
|
70
74
|
let program;
|
|
71
75
|
try {
|
|
72
|
-
program =
|
|
76
|
+
program = parseOxc(file, code).program;
|
|
73
77
|
} catch {
|
|
74
78
|
program = void 0;
|
|
75
79
|
}
|
|
@@ -97,10 +101,17 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
97
101
|
if (pluginOptions.jit) return;
|
|
98
102
|
registry.clear();
|
|
99
103
|
scannedDtsPackages.clear();
|
|
104
|
+
lazyScans.clear();
|
|
105
|
+
importersByFile.clear();
|
|
106
|
+
projectScan = void 0;
|
|
100
107
|
const resolvedTsConfigPath = resolveTsConfigPath();
|
|
101
108
|
projectRoot = dirname(resolvedTsConfigPath);
|
|
102
|
-
|
|
103
|
-
useDefineForClassFields =
|
|
109
|
+
tsConfig = compilerCli.readConfiguration(resolvedTsConfigPath);
|
|
110
|
+
useDefineForClassFields = tsConfig.options?.useDefineForClassFields ?? true;
|
|
111
|
+
}
|
|
112
|
+
/** Scan all source files reachable from the tsconfig into the registry. */
|
|
113
|
+
async function scanProject() {
|
|
114
|
+
const config = tsConfig;
|
|
104
115
|
const candidates = new Set(config.rootNames);
|
|
105
116
|
const tsPaths = config.options?.paths;
|
|
106
117
|
const baseUrl = getPathsBasePath(config.options, projectRoot);
|
|
@@ -172,7 +183,7 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
172
183
|
}
|
|
173
184
|
let program;
|
|
174
185
|
try {
|
|
175
|
-
program =
|
|
186
|
+
program = parseOxc(file, code).program;
|
|
176
187
|
} catch {
|
|
177
188
|
program = void 0;
|
|
178
189
|
}
|
|
@@ -223,7 +234,67 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
223
234
|
} catch {}
|
|
224
235
|
}
|
|
225
236
|
}
|
|
226
|
-
|
|
237
|
+
/**
|
|
238
|
+
* Scan the source files `id` imports into the registry on demand and record
|
|
239
|
+
* `id` as their importer, so a metadata change in any of them recompiles it.
|
|
240
|
+
*/
|
|
241
|
+
async function resolveImportedDeclarations(code, id, program, resolveImport) {
|
|
242
|
+
await Promise.all(collectAllImports(code, id, program).map(async (spec) => {
|
|
243
|
+
const file = await resolveImport(spec, id);
|
|
244
|
+
if (!file) return;
|
|
245
|
+
for (const scanned of await scanOnDemand(file, resolveImport)) {
|
|
246
|
+
let importers = importersByFile.get(scanned);
|
|
247
|
+
if (!importers) {
|
|
248
|
+
importers = /* @__PURE__ */ new Set();
|
|
249
|
+
importersByFile.set(scanned, importers);
|
|
250
|
+
}
|
|
251
|
+
importers.add(id);
|
|
252
|
+
}
|
|
253
|
+
}));
|
|
254
|
+
}
|
|
255
|
+
function scanOnDemand(file, resolveImport) {
|
|
256
|
+
let scan = lazyScans.get(file);
|
|
257
|
+
if (!scan) {
|
|
258
|
+
scan = scanWithReExports(file, resolveImport);
|
|
259
|
+
lazyScans.set(file, scan);
|
|
260
|
+
}
|
|
261
|
+
return scan;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Scan a file and everything it re-exports, resolving specifiers through
|
|
265
|
+
* Vite so path aliases work. Tuple barrels and NgModules can list classes
|
|
266
|
+
* their file imports without re-exporting, so their imports are followed
|
|
267
|
+
* too. Returns every file scanned.
|
|
268
|
+
*/
|
|
269
|
+
async function scanWithReExports(file, resolveImport) {
|
|
270
|
+
const visited = /* @__PURE__ */ new Set();
|
|
271
|
+
const visit = async (current) => {
|
|
272
|
+
if (visited.has(current)) return;
|
|
273
|
+
visited.add(current);
|
|
274
|
+
let code;
|
|
275
|
+
let program;
|
|
276
|
+
try {
|
|
277
|
+
code = await promises.readFile(current, "utf-8");
|
|
278
|
+
program = parseOxc(current, code).program;
|
|
279
|
+
} catch {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const entries = scanFile(code, current, program);
|
|
283
|
+
for (const entry of entries) if (!registry.has(entry.className)) registry.set(entry.className, entry);
|
|
284
|
+
ensureDtsRegistryForSource(code, current, program);
|
|
285
|
+
const specifiers = entries.some((e) => e.kind === "tuple" || e.kind === "ngmodule") ? collectAllImports(code, current, program) : collectReExports(code, current, program);
|
|
286
|
+
for (const spec of specifiers) {
|
|
287
|
+
const dep = await resolveImport(spec, current);
|
|
288
|
+
if (dep) await visit(dep);
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
await visit(file);
|
|
292
|
+
return visited;
|
|
293
|
+
}
|
|
294
|
+
function registryEntriesOf(file) {
|
|
295
|
+
return [...registry.values()].filter((e) => e.fileName === file);
|
|
296
|
+
}
|
|
297
|
+
async function handleFastCompileTransform(code, id, resolveImport) {
|
|
227
298
|
if (!ANGULAR_DECORATOR_CALL_RE.test(code)) {
|
|
228
299
|
const stripped = vite.transformWithOxc ? await vite.transformWithOxc(code, id, {
|
|
229
300
|
lang: "ts",
|
|
@@ -264,7 +335,7 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
264
335
|
code = inlined.code;
|
|
265
336
|
const { styleExtensions } = inlined;
|
|
266
337
|
for (const dep of inlined.resourceDependencies) resourceToSource.set(dep, id);
|
|
267
|
-
const { program: oxcProgram } =
|
|
338
|
+
const { program: oxcProgram } = parseOxc(id, code);
|
|
268
339
|
let resolvedInlineStyles;
|
|
269
340
|
const inlineExt = pluginOptions.inlineStylesExtension;
|
|
270
341
|
const styleNeedsPreprocess = (ext) => ext !== "" && ext !== "css";
|
|
@@ -287,6 +358,12 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
287
358
|
}
|
|
288
359
|
}
|
|
289
360
|
ensureDtsRegistryForSource(code, id, oxcProgram);
|
|
361
|
+
for (const entry of scanFile(code, id, oxcProgram)) registry.set(entry.className, entry);
|
|
362
|
+
await resolveImportedDeclarations(code, id, oxcProgram, resolveImport);
|
|
363
|
+
if (declaresNonStandaloneComponent(oxcProgram)) {
|
|
364
|
+
projectScan ??= scanProject();
|
|
365
|
+
await projectScan;
|
|
366
|
+
}
|
|
290
367
|
let compileRegistry = registry;
|
|
291
368
|
if (componentRegistries.some((external) => external.size > 0)) {
|
|
292
369
|
compileRegistry = new Map(registry);
|
|
@@ -313,7 +390,7 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
313
390
|
}, result.map);
|
|
314
391
|
let outputCode = stripped.code;
|
|
315
392
|
if (watchMode && pluginOptions.liveReload) {
|
|
316
|
-
const fileDeclarations =
|
|
393
|
+
const fileDeclarations = registryEntriesOf(id);
|
|
317
394
|
if (fileDeclarations.length > 0) {
|
|
318
395
|
const localDepClassNames = fileDeclarations.map((e) => e.className);
|
|
319
396
|
outputCode += generateHmrCode(fileDeclarations, localDepClassNames);
|
|
@@ -360,11 +437,6 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
360
437
|
transformFilter = integrations.transformFilter;
|
|
361
438
|
componentRegistries = integrations.componentRegistries;
|
|
362
439
|
},
|
|
363
|
-
configureServer(server) {
|
|
364
|
-
server.watcher.on("add", async (filePath) => {
|
|
365
|
-
if (filePath.endsWith(".ts") && !filePath.endsWith(".spec.ts") && !filePath.endsWith(".d.ts")) await scanBarrelExports(filePath, /* @__PURE__ */ new Set(), true);
|
|
366
|
-
});
|
|
367
|
-
},
|
|
368
440
|
async buildStart() {
|
|
369
441
|
await initFastCompile();
|
|
370
442
|
},
|
|
@@ -379,9 +451,14 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
379
451
|
}
|
|
380
452
|
if (TS_EXT_REGEX.test(ctx.file)) {
|
|
381
453
|
const [fileId] = ctx.file.split("?");
|
|
382
|
-
const oldEntries =
|
|
383
|
-
for (const
|
|
454
|
+
const oldEntries = registryEntriesOf(fileId);
|
|
455
|
+
for (const entry of oldEntries) registry.delete(entry.className);
|
|
384
456
|
await scanBarrelExports(fileId, /* @__PURE__ */ new Set(), true);
|
|
457
|
+
lazyScans.clear();
|
|
458
|
+
if (JSON.stringify(oldEntries) !== JSON.stringify(registryEntriesOf(fileId))) {
|
|
459
|
+
const importerModules = [...importersByFile.get(fileId) ?? []].flatMap((importer) => [...ctx.server.moduleGraph.getModulesByFile(importer) ?? []]);
|
|
460
|
+
return [...ctx.modules, ...importerModules];
|
|
461
|
+
}
|
|
385
462
|
}
|
|
386
463
|
return ctx.modules;
|
|
387
464
|
},
|
|
@@ -422,7 +499,12 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
422
499
|
async handler(code, id) {
|
|
423
500
|
if (transformFilter && !transformFilter(code, id)) return;
|
|
424
501
|
if (id.includes(".ts?")) id = id.replace(/\?(.*)/, "");
|
|
425
|
-
return handleFastCompileTransform(code, id)
|
|
502
|
+
return handleFastCompileTransform(code, id, async (spec, importer) => {
|
|
503
|
+
const resolved = await this.resolve(spec, importer, { skipSelf: true });
|
|
504
|
+
if (!resolved || resolved.external) return null;
|
|
505
|
+
const file = normalizePath(resolved.id.split("?")[0]);
|
|
506
|
+
return TS_EXT_REGEX.test(file) && !EXCLUDED_TS_EXT_REGEX.test(file) && !file.includes("/node_modules/") ? file : null;
|
|
507
|
+
});
|
|
426
508
|
}
|
|
427
509
|
}
|
|
428
510
|
};
|