@analogjs/vite-plugin-angular 3.0.0-beta.9 → 3.0.1-beta.1
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/migrations/migrate-setup-vitest/migrate-setup-vitest.js +3 -3
- package/migrations/migrate-setup-vitest/migrate-setup-vitest.js.map +1 -1
- package/ngp/LICENSE +21 -0
- package/ngp/api.mjs +46806 -0
- package/ngp/build.json +4 -0
- package/ngp/ng_analyze.cjs +601 -0
- package/ngp/ng_analyze_bg.wasm +0 -0
- package/package.json +5 -2
- package/src/index.d.ts +2 -0
- package/src/index.js +4 -3
- package/src/index.js.map +1 -1
- package/src/lib/analog-plugin-interop.js +2 -3
- package/src/lib/angular-build-context.d.ts +217 -0
- package/src/lib/angular-build-context.js +374 -0
- package/src/lib/angular-build-context.js.map +1 -0
- package/src/lib/angular-build-optimizer-plugin.d.ts +6 -4
- package/src/lib/angular-build-optimizer-plugin.js +25 -11
- package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
- package/src/lib/angular-jit-plugin.d.ts +5 -3
- package/src/lib/angular-jit-plugin.js +16 -9
- package/src/lib/angular-jit-plugin.js.map +1 -1
- package/src/lib/angular-vite-plugin.d.ts +6 -109
- package/src/lib/angular-vite-plugin.js +9 -1251
- package/src/lib/angular-vite-plugin.js.map +1 -1
- package/src/lib/angular-vitest-plugin.d.ts +3 -2
- package/src/lib/angular-vitest-plugin.js +7 -5
- package/src/lib/angular-vitest-plugin.js.map +1 -1
- package/src/lib/companion-plugins.d.ts +7 -0
- package/src/lib/companion-plugins.js +37 -0
- package/src/lib/companion-plugins.js.map +1 -0
- package/src/lib/compilation-api/compilation-api-plugin.d.ts +11 -2
- package/src/lib/compilation-api/compilation-api-plugin.js +164 -289
- package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
- package/src/lib/compilation-api/index.js +1 -2
- package/src/lib/compiler/angular-version.js +0 -1
- package/src/lib/compiler/class-field-lowering.js +1 -2
- package/src/lib/compiler/compile.d.ts +1 -1
- package/src/lib/compiler/compile.js +224 -151
- package/src/lib/compiler/compile.js.map +1 -1
- package/src/lib/compiler/constants.js +1 -2
- package/src/lib/compiler/debug.js +1 -2
- package/src/lib/compiler/defer.d.ts +2 -3
- package/src/lib/compiler/defer.js +13 -16
- 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 +20 -12
- 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 +8 -4
- package/src/lib/compiler/hmr.js.map +1 -1
- package/src/lib/compiler/index.d.ts +2 -2
- package/src/lib/compiler/index.js +6 -6
- package/src/lib/compiler/jit-metadata.js +1 -2
- package/src/lib/compiler/jit-transform.js +37 -15
- 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 +4 -23
- package/src/lib/compiler/js-emitter.js.map +1 -1
- package/src/lib/compiler/metadata.js +2 -3
- package/src/lib/compiler/registry.d.ts +9 -1
- package/src/lib/compiler/registry.js +36 -8
- package/src/lib/compiler/registry.js.map +1 -1
- package/src/lib/compiler/resource-inliner.d.ts +8 -9
- package/src/lib/compiler/resource-inliner.js +11 -20
- package/src/lib/compiler/resource-inliner.js.map +1 -1
- package/src/lib/compiler/style-ast.d.ts +22 -1
- package/src/lib/compiler/style-ast.js +37 -20
- 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 +11 -13
- package/src/lib/compiler/type-elision.js.map +1 -1
- package/src/lib/compiler/utils.d.ts +9 -7
- package/src/lib/compiler/utils.js +50 -11
- package/src/lib/compiler/utils.js.map +1 -1
- package/src/lib/compiler-plugin.js +1 -2
- package/src/lib/component-resolvers.js +1 -2
- package/src/lib/component-scanner.d.ts +101 -0
- package/src/lib/component-scanner.js +331 -0
- package/src/lib/component-scanner.js.map +1 -0
- package/src/lib/component-styles-plugin.d.ts +52 -0
- package/src/lib/component-styles-plugin.js +352 -0
- package/src/lib/component-styles-plugin.js.map +1 -0
- package/src/lib/compose-angular-plugins.d.ts +12 -0
- package/src/lib/compose-angular-plugins.js +30 -0
- package/src/lib/compose-angular-plugins.js.map +1 -0
- package/src/lib/dev-server-mode-plugin.d.ts +7 -0
- package/src/lib/dev-server-mode-plugin.js +22 -0
- package/src/lib/dev-server-mode-plugin.js.map +1 -0
- package/src/lib/encapsulation-plugin.js +1 -2
- package/src/lib/fast-compile-api.d.ts +62 -0
- package/src/lib/fast-compile-api.js +11 -0
- package/src/lib/fast-compile-api.js.map +1 -0
- package/src/lib/fast-compile-plugin.d.ts +6 -1
- package/src/lib/fast-compile-plugin.js +222 -117
- package/src/lib/fast-compile-plugin.js.map +1 -1
- package/src/lib/host.d.ts +3 -0
- package/src/lib/host.js +5 -4
- package/src/lib/host.js.map +1 -1
- package/src/lib/hot-update-batch.js +1 -2
- package/src/lib/live-reload-plugin.d.ts +8 -5
- package/src/lib/live-reload-plugin.js +45 -10
- package/src/lib/live-reload-plugin.js.map +1 -1
- package/src/lib/models.d.ts +4 -1
- package/src/lib/ngp-compile-api.d.ts +55 -0
- package/src/lib/ngp-compile-api.js +11 -0
- package/src/lib/ngp-compile-api.js.map +1 -0
- package/src/lib/ngp-compile-plugin.d.ts +4 -0
- package/src/lib/ngp-compile-plugin.js +680 -0
- package/src/lib/ngp-compile-plugin.js.map +1 -0
- package/src/lib/ngtsc-compile-plugin.d.ts +23 -0
- package/src/lib/ngtsc-compile-plugin.js +780 -0
- package/src/lib/ngtsc-compile-plugin.js.map +1 -0
- package/src/lib/nx-folder-plugin.d.ts +6 -5
- package/src/lib/nx-folder-plugin.js +13 -9
- package/src/lib/nx-folder-plugin.js.map +1 -1
- package/src/lib/plugins/file-replacements.plugin.d.ts +6 -0
- package/src/lib/plugins/file-replacements.plugin.js +2 -2
- package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
- package/src/lib/router-plugin.d.ts +5 -1
- package/src/lib/router-plugin.js +14 -6
- package/src/lib/router-plugin.js.map +1 -1
- package/src/lib/style-preprocessor.js +1 -2
- package/src/lib/stylesheet-registry.js +1 -2
- package/src/lib/stylesheet-registry.js.map +1 -1
- package/src/lib/tools/src/builders/vite/vite-build.impl.js +2 -3
- package/src/lib/tools/src/builders/vite/vite-build.impl.js.map +1 -1
- package/src/lib/tools/src/builders/vite-dev-server/dev-server.impl.js +1 -2
- package/src/lib/tools/src/builders/vite-dev-server/dev-server.impl.js.map +1 -1
- package/src/lib/utils/compilation-shared.d.ts +1 -4
- package/src/lib/utils/compilation-shared.js +9 -8
- package/src/lib/utils/compilation-shared.js.map +1 -1
- package/src/lib/utils/css-extension-resolver.js +1 -2
- package/src/lib/utils/css-preprocessor-workers.js +1 -2
- package/src/lib/utils/debug-harness.js +1 -2
- package/src/lib/utils/debug-log-file.js +1 -2
- package/src/lib/utils/debug.js +1 -2
- package/src/lib/utils/devkit.js +2 -3
- package/src/lib/utils/hmr-component-updates.d.ts +7 -0
- package/src/lib/utils/hmr-component-updates.js +86 -0
- package/src/lib/utils/hmr-component-updates.js.map +1 -0
- package/src/lib/utils/jit-inline-styles.js +1 -2
- package/src/lib/utils/lsp-type-checker.d.ts +75 -0
- package/src/lib/utils/lsp-type-checker.js +532 -0
- package/src/lib/utils/lsp-type-checker.js.map +1 -0
- package/src/lib/utils/ngp-host-fs.d.ts +43 -0
- package/src/lib/utils/ngp-host-fs.js +128 -0
- package/src/lib/utils/ngp-host-fs.js.map +1 -0
- package/src/lib/utils/plugin-config.d.ts +15 -8
- package/src/lib/utils/plugin-config.js +19 -7
- package/src/lib/utils/plugin-config.js.map +1 -1
- package/src/lib/utils/rolldown.js +1 -2
- package/src/lib/utils/safe-module-paths.js +1 -2
- package/src/lib/utils/stylesheet-warning.d.ts +2 -0
- package/src/lib/utils/stylesheet-warning.js +10 -0
- package/src/lib/utils/stylesheet-warning.js.map +1 -0
- package/src/lib/utils/transform-cache.js +1 -2
- package/src/lib/utils/transform-cache.js.map +1 -1
- package/src/lib/utils/tsconfig-resolver.js +2 -3
- package/src/lib/utils/virtual-ids.js +1 -2
- package/src/lib/utils/virtual-resources.js +1 -2
- package/src/lib/utils/virtual-resources.js.map +1 -1
- package/src/lib/virtual-modules-plugin.d.ts +11 -3
- package/src/lib/virtual-modules-plugin.js +70 -15
- package/src/lib/virtual-modules-plugin.js.map +1 -1
|
@@ -1,16 +1,15 @@
|
|
|
1
|
-
import { parseSync } from "oxc-parser";
|
|
1
|
+
import type { parseSync } from "oxc-parser";
|
|
2
2
|
export interface InlineResourceResult {
|
|
3
3
|
/** The modified source code, or the original if no changes were needed. */
|
|
4
4
|
code: string;
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* truly-inline `styles: [...]` template strings).
|
|
6
|
+
* Absolute path of each inlined external style, keyed by its position in
|
|
7
|
+
* the flat per-file style list produced by {@link extractInlineStyles}. Lets
|
|
8
|
+
* the caller preprocess each external `styleUrl` as its own file (extension
|
|
9
|
+
* and relative imports), independent of the `inlineStylesExtension` option
|
|
10
|
+
* (which governs truly-inline `styles: [...]` template strings).
|
|
12
11
|
*/
|
|
13
|
-
|
|
12
|
+
stylePaths: Map<number, string>;
|
|
14
13
|
/**
|
|
15
14
|
* Absolute paths of every external resource file successfully read and
|
|
16
15
|
* inlined. Callers record these so a later edit to the resource file can
|
|
@@ -32,7 +31,7 @@ export interface InlineResourceResult {
|
|
|
32
31
|
* merged into that existing array instead of emitting a second `styles`
|
|
33
32
|
* property (which would be a duplicate object literal key).
|
|
34
33
|
*
|
|
35
|
-
* Returns the modified source code plus the per-style-index
|
|
34
|
+
* Returns the modified source code plus the per-style-index path map
|
|
36
35
|
* (see {@link InlineResourceResult}).
|
|
37
36
|
*/
|
|
38
37
|
export declare function inlineResourceUrls(code: string, fileName: string): Promise<InlineResourceResult>;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { parseOxc } from "./utils.js";
|
|
1
2
|
import { extractInlineStyles as extractInlineStyles$1 } from "./style-ast.js";
|
|
2
3
|
import * as fs from "node:fs";
|
|
3
4
|
import * as path$1 from "node:path";
|
|
4
|
-
import { parseSync } from "oxc-parser";
|
|
5
5
|
import MagicString from "magic-string";
|
|
6
|
-
|
|
6
|
+
// packages/vite-plugin-angular/src/lib/compiler/resource-inliner.ts
|
|
7
7
|
/** Whether a node is an inline style value (string literal or single-quasi template). */
|
|
8
8
|
function isInlineStyleValue(node) {
|
|
9
9
|
return node?.type === "Literal" && typeof node.value === "string" || node?.type === "TemplateLiteral" && node.quasis?.length === 1;
|
|
@@ -28,17 +28,17 @@ function countInlineStyleLiterals(arrayExpr) {
|
|
|
28
28
|
* merged into that existing array instead of emitting a second `styles`
|
|
29
29
|
* property (which would be a duplicate object literal key).
|
|
30
30
|
*
|
|
31
|
-
* Returns the modified source code plus the per-style-index
|
|
31
|
+
* Returns the modified source code plus the per-style-index path map
|
|
32
32
|
* (see {@link InlineResourceResult}).
|
|
33
33
|
*/
|
|
34
34
|
async function inlineResourceUrls(code, fileName) {
|
|
35
|
-
const
|
|
35
|
+
const stylePaths = /* @__PURE__ */ new Map();
|
|
36
36
|
if (!code.includes("templateUrl") && !code.includes("styleUrl")) return {
|
|
37
37
|
code,
|
|
38
|
-
|
|
38
|
+
stylePaths,
|
|
39
39
|
resourceDependencies: []
|
|
40
40
|
};
|
|
41
|
-
const { program } =
|
|
41
|
+
const { program } = parseOxc(fileName, code);
|
|
42
42
|
const ms = new MagicString(code);
|
|
43
43
|
let changed = false;
|
|
44
44
|
const dir = path$1.dirname(fileName);
|
|
@@ -125,11 +125,10 @@ async function inlineResourceUrls(code, fileName) {
|
|
|
125
125
|
if (content !== void 0) cssProps.push({
|
|
126
126
|
prop: rp.prop,
|
|
127
127
|
contents: [content],
|
|
128
|
-
|
|
128
|
+
paths: [rp.resolvedPath]
|
|
129
129
|
});
|
|
130
130
|
} else {
|
|
131
131
|
const contents = [];
|
|
132
|
-
const extensions = [];
|
|
133
132
|
let allRead = true;
|
|
134
133
|
for (const p of rp.resolvedPaths) {
|
|
135
134
|
const content = fileContents.get(p);
|
|
@@ -138,12 +137,11 @@ async function inlineResourceUrls(code, fileName) {
|
|
|
138
137
|
break;
|
|
139
138
|
}
|
|
140
139
|
contents.push(content);
|
|
141
|
-
extensions.push(extensionOf(p));
|
|
142
140
|
}
|
|
143
141
|
if (allRead && contents.length > 0) cssProps.push({
|
|
144
142
|
prop: rp.prop,
|
|
145
143
|
contents,
|
|
146
|
-
|
|
144
|
+
paths: rp.resolvedPaths
|
|
147
145
|
});
|
|
148
146
|
}
|
|
149
147
|
for (const { prop, content } of templateUrlRewrites) {
|
|
@@ -152,7 +150,7 @@ async function inlineResourceUrls(code, fileName) {
|
|
|
152
150
|
}
|
|
153
151
|
if (cssProps.length > 0) {
|
|
154
152
|
const allContents = cssProps.flatMap((c) => c.contents);
|
|
155
|
-
const
|
|
153
|
+
const allPaths = cssProps.flatMap((c) => c.paths);
|
|
156
154
|
if (existingStylesArray) {
|
|
157
155
|
const realElements = existingStylesArray.elements.filter((e) => e != null);
|
|
158
156
|
if (realElements.length > 0) {
|
|
@@ -176,22 +174,16 @@ async function inlineResourceUrls(code, fileName) {
|
|
|
176
174
|
}
|
|
177
175
|
changed = true;
|
|
178
176
|
const externalBase = flatStyleBase + existingInlineCount;
|
|
179
|
-
|
|
180
|
-
if (ext) styleExtensions.set(externalBase + k, ext);
|
|
181
|
-
});
|
|
177
|
+
allPaths.forEach((p, k) => stylePaths.set(externalBase + k, p));
|
|
182
178
|
flatStyleBase = externalBase + allContents.length;
|
|
183
179
|
} else flatStyleBase += existingInlineCount;
|
|
184
180
|
}
|
|
185
181
|
return {
|
|
186
182
|
code: changed ? ms.toString() : code,
|
|
187
|
-
|
|
183
|
+
stylePaths,
|
|
188
184
|
resourceDependencies: [...pathsToRead].filter((p) => fileContents.get(p) !== void 0)
|
|
189
185
|
};
|
|
190
186
|
}
|
|
191
|
-
/** Lower-cased file extension without the leading dot (e.g. `scss`), or `''`. */
|
|
192
|
-
function extensionOf(filePath) {
|
|
193
|
-
return path$1.extname(filePath).slice(1).toLowerCase();
|
|
194
|
-
}
|
|
195
187
|
/**
|
|
196
188
|
* Remove a property from an object literal while also eating one surrounding
|
|
197
189
|
* comma so the resulting object stays syntactically valid. Prefers the
|
|
@@ -224,7 +216,6 @@ function extractInlineStyles(code, fileName, program) {
|
|
|
224
216
|
if (!code.includes("styles")) return [];
|
|
225
217
|
return extractInlineStyles$1(code, fileName, program);
|
|
226
218
|
}
|
|
227
|
-
//#endregion
|
|
228
219
|
export { extractInlineStyles, inlineResourceUrls };
|
|
229
220
|
|
|
230
221
|
//# sourceMappingURL=resource-inliner.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-inliner.js","names":[],"sources":["../../../../src/lib/compiler/resource-inliner.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { parseSync } from 'oxc-parser';\nimport MagicString from 'magic-string';\nimport { extractInlineStyles as extractStylesFromAst } from './style-ast.js';\n\nexport interface InlineResourceResult {\n /** The modified source code, or the original if no changes were needed. */\n code: string;\n /**\n * Source extension (without the leading dot, lower-cased — e.g. `scss`) of\n * each inlined external style, keyed by its position in the flat per-file\n * style list produced by {@link extractInlineStyles}. Lets the caller run\n * each external `styleUrl` through the right preprocessor by its own file\n * extension, independent of the `inlineStylesExtension` option (which governs\n * truly-inline `styles: [...]` template strings).\n */\n styleExtensions: Map<number, string>;\n /**\n * Absolute paths of every external resource file successfully read and\n * inlined. Callers record these so a later edit to the resource file can\n * invalidate the owning source module — the inlined copy is otherwise\n * invisible to the module graph.\n */\n resourceDependencies: string[];\n}\n\n/** Whether a node is an inline style value (string literal or single-quasi template). */\nfunction isInlineStyleValue(node: any): boolean {\n return (\n (node?.type === 'Literal' && typeof node.value === 'string') ||\n (node?.type === 'TemplateLiteral' && node.quasis?.length === 1)\n );\n}\n\n/** Count the elements of a `styles: [...]` array that {@link extractInlineStyles} would emit. */\nfunction countInlineStyleLiterals(arrayExpr: any): number {\n let count = 0;\n for (const el of arrayExpr.elements ?? []) {\n if (el?.type === 'Literal' && typeof el.value === 'string') count++;\n else if (el?.type === 'TemplateLiteral' && el.quasis?.length === 1) count++;\n }\n return count;\n}\n\n/**\n * Inline external templateUrl and styleUrl/styleUrls into the source code\n * using OXC parser for precise AST-based rewriting.\n *\n * Replaces:\n * templateUrl: './file.html' → template: \"...file contents...\"\n * styleUrl: './file.scss' → styles: [\"...file contents...\"]\n * styleUrls: ['./a.scss'] → styles: [\"...contents...\"]\n *\n * When the decorator already has a `styles: [...]` array, inlined CSS is\n * merged into that existing array instead of emitting a second `styles`\n * property (which would be a duplicate object literal key).\n *\n * Returns the modified source code plus the per-style-index extension map\n * (see {@link InlineResourceResult}).\n */\nexport async function inlineResourceUrls(\n code: string,\n fileName: string,\n): Promise<InlineResourceResult> {\n const styleExtensions = new Map<number, string>();\n\n if (!code.includes('templateUrl') && !code.includes('styleUrl')) {\n return { code, styleExtensions, resourceDependencies: [] };\n }\n\n const { program } = parseSync(fileName, code);\n const ms = new MagicString(code);\n let changed = false;\n const dir = path.dirname(fileName);\n\n // Phase 1: walk the AST and collect resource descriptors per decorator,\n // in source order — no I/O during the walk. A plan is recorded for every\n // `@Component` decorator (even without url props) because the flat style\n // index bookkeeping below advances per decorator.\n type ResourceProp =\n | { kind: 'templateUrl'; prop: any; resolvedPath: string }\n | { kind: 'styleUrl'; prop: any; resolvedPath: string }\n | { kind: 'styleUrls'; prop: any; resolvedPaths: string[] };\n interface DecoratorPlan {\n existingStylesProp: any;\n existingStylesArray: any;\n existingInlineCount: number;\n resourceProps: ResourceProp[];\n }\n const plans: DecoratorPlan[] = [];\n\n for (const node of program.body) {\n const decl =\n node.type === 'ExportNamedDeclaration' ||\n node.type === 'ExportDefaultDeclaration'\n ? (node as any).declaration\n : node;\n if (!decl || decl.type !== 'ClassDeclaration') continue;\n\n for (const dec of decl.decorators || []) {\n const expr = dec.expression;\n if (!expr || expr.type !== 'CallExpression') continue;\n if (expr.callee?.name !== 'Component') continue;\n\n const arg = expr.arguments?.[0];\n if (!arg || arg.type !== 'ObjectExpression') continue;\n\n // First pass: locate an existing `styles` property in the same decorator.\n // Inlined CSS is merged into it — converting a singular string/template\n // value to an array when needed — to avoid emitting a duplicate `styles`\n // key.\n let existingStylesProp: any = null;\n let existingStylesArray: any = null;\n for (const prop of arg.properties) {\n if (prop.type !== 'Property') continue;\n const key: string = prop.key?.name ?? prop.key?.value;\n if (key === 'styles') {\n existingStylesProp = prop;\n if (prop.value?.type === 'ArrayExpression') {\n existingStylesArray = prop.value;\n }\n break;\n }\n }\n\n // Inline `styles` entries already present come first in the flat list;\n // appended external styles follow them.\n const existingInlineCount = existingStylesArray\n ? countInlineStyleLiterals(existingStylesArray)\n : isInlineStyleValue(existingStylesProp?.value)\n ? 1\n : 0;\n\n const resourceProps: ResourceProp[] = [];\n\n for (const prop of arg.properties) {\n if (prop.type !== 'Property') continue;\n const key: string = prop.key?.name ?? prop.key?.value;\n const val = prop.value;\n\n if (\n key === 'templateUrl' &&\n val?.type === 'Literal' &&\n typeof val.value === 'string'\n ) {\n resourceProps.push({\n kind: 'templateUrl',\n prop,\n resolvedPath: path.resolve(dir, val.value),\n });\n continue;\n }\n\n if (\n key === 'styleUrl' &&\n val?.type === 'Literal' &&\n typeof val.value === 'string'\n ) {\n resourceProps.push({\n kind: 'styleUrl',\n prop,\n resolvedPath: path.resolve(dir, val.value),\n });\n continue;\n }\n\n if (key === 'styleUrls' && val?.type === 'ArrayExpression') {\n const resolvedPaths: string[] = [];\n for (const el of val.elements) {\n if (el?.type === 'Literal' && typeof el.value === 'string') {\n resolvedPaths.push(path.resolve(dir, el.value));\n }\n }\n resourceProps.push({ kind: 'styleUrls', prop, resolvedPaths });\n }\n }\n\n plans.push({\n existingStylesProp,\n existingStylesArray,\n existingInlineCount,\n resourceProps,\n });\n }\n }\n\n // Phase 2: read every referenced resource without blocking the event\n // loop. Each read catches its own failure to `undefined` — one missing\n // file must not abort sibling reads that succeed.\n const pathsToRead = new Set<string>();\n for (const plan of plans) {\n for (const rp of plan.resourceProps) {\n if (rp.kind === 'styleUrls') {\n for (const p of rp.resolvedPaths) pathsToRead.add(p);\n } else {\n pathsToRead.add(rp.resolvedPath);\n }\n }\n }\n const fileContents = new Map<string, string | undefined>();\n await Promise.all(\n [...pathsToRead].map(async (p) => {\n fileContents.set(\n p,\n await fs.promises.readFile(p, 'utf-8').catch(() => undefined),\n );\n }),\n );\n\n // Phase 3: apply MagicString rewrites in the original AST order so the\n // flat style index bookkeeping matches `extractInlineStyles`.\n\n // Running base index into the flat per-file style list (matching the order\n // `extractInlineStyles` walks classes/decorators/properties) so external\n // styles can be mapped to the index `resolvedInlineStyles` later keys on.\n let flatStyleBase = 0;\n\n for (const plan of plans) {\n const { existingStylesProp, existingStylesArray, existingInlineCount } =\n plan;\n\n // Collect the props we want to rewrite. Contents from styleUrl /\n // styleUrls are accumulated so that multiple url-based props in one\n // decorator collapse into a single `styles` array write. `extensions`\n // tracks each content's source extension in the same order.\n const templateUrlRewrites: Array<{ prop: any; content: string }> = [];\n const cssProps: Array<{\n prop: any;\n contents: string[];\n extensions: string[];\n }> = [];\n\n for (const rp of plan.resourceProps) {\n if (rp.kind === 'templateUrl') {\n // Keep original if file can't be read\n const content = fileContents.get(rp.resolvedPath);\n if (content !== undefined) {\n templateUrlRewrites.push({ prop: rp.prop, content });\n }\n } else if (rp.kind === 'styleUrl') {\n // Keep original if file can't be read\n const content = fileContents.get(rp.resolvedPath);\n if (content !== undefined) {\n cssProps.push({\n prop: rp.prop,\n contents: [content],\n extensions: [extensionOf(rp.resolvedPath)],\n });\n }\n } else {\n // styleUrls is all-or-nothing: keep the original property if any\n // entry failed to read.\n const contents: string[] = [];\n const extensions: string[] = [];\n let allRead = true;\n for (const p of rp.resolvedPaths) {\n const content = fileContents.get(p);\n if (content === undefined) {\n allRead = false;\n break;\n }\n contents.push(content);\n extensions.push(extensionOf(p));\n }\n if (allRead && contents.length > 0) {\n cssProps.push({ prop: rp.prop, contents, extensions });\n }\n }\n }\n\n for (const { prop, content } of templateUrlRewrites) {\n ms.overwrite(\n prop.start,\n prop.end,\n `template: ${JSON.stringify(content)}`,\n );\n changed = true;\n }\n\n if (cssProps.length > 0) {\n const allContents = cssProps.flatMap((c) => c.contents);\n const allExtensions = cssProps.flatMap((c) => c.extensions);\n\n if (existingStylesArray) {\n // Filter out null holes in case the source already has a sparse array.\n const realElements = (existingStylesArray.elements as any[]).filter(\n (e) => e != null,\n );\n\n if (realElements.length > 0) {\n // Insert right after the last real element. This preserves any\n // trailing comma the source may have (e.g. Prettier output) and\n // avoids producing a sparse `[existing, , \"new\"]` element, which\n // would crash downstream decorator metadata extraction.\n const lastElement = realElements[realElements.length - 1];\n const insertion = allContents\n .map((c) => `, ${JSON.stringify(c)}`)\n .join('');\n ms.appendRight(lastElement.end, insertion);\n } else {\n // Empty array — drop the leading comma.\n const insertion = allContents\n .map((c) => JSON.stringify(c))\n .join(', ');\n ms.appendLeft(existingStylesArray.end - 1, insertion);\n }\n\n for (const { prop } of cssProps) {\n removePropertyWithSeparator(ms, code, prop.start, prop.end);\n }\n } else if (isInlineStyleValue(existingStylesProp?.value)) {\n // Singular `styles: '...'` / `styles: \\`...\\`` — wrap the original\n // value into an array merged with the inlined styles, then drop the\n // styleUrl props so only one `styles` key remains.\n const original = code.slice(\n existingStylesProp.value.start,\n existingStylesProp.value.end,\n );\n const merged = allContents\n .map((c) => `, ${JSON.stringify(c)}`)\n .join('');\n ms.overwrite(\n existingStylesProp.value.start,\n existingStylesProp.value.end,\n `[${original}${merged}]`,\n );\n for (const { prop } of cssProps) {\n removePropertyWithSeparator(ms, code, prop.start, prop.end);\n }\n } else {\n // No existing `styles` array — rewrite the first styleUrl/styleUrls\n // prop with the merged contents and drop any additional ones so we\n // don't emit multiple `styles` properties.\n const [first, ...rest] = cssProps;\n ms.overwrite(\n first.prop.start,\n first.prop.end,\n `styles: [${allContents.map((c) => JSON.stringify(c)).join(', ')}]`,\n );\n for (const { prop } of rest) {\n removePropertyWithSeparator(ms, code, prop.start, prop.end);\n }\n }\n changed = true;\n\n // The appended external styles occupy the flat indices after any\n // pre-existing inline styles for this component.\n const externalBase = flatStyleBase + existingInlineCount;\n allExtensions.forEach((ext, k) => {\n if (ext) styleExtensions.set(externalBase + k, ext);\n });\n flatStyleBase = externalBase + allContents.length;\n } else {\n flatStyleBase += existingInlineCount;\n }\n }\n\n return {\n code: changed ? ms.toString() : code,\n styleExtensions,\n resourceDependencies: [...pathsToRead].filter(\n (p) => fileContents.get(p) !== undefined,\n ),\n };\n}\n\n/** Lower-cased file extension without the leading dot (e.g. `scss`), or `''`. */\nfunction extensionOf(filePath: string): string {\n return path.extname(filePath).slice(1).toLowerCase();\n}\n\n/**\n * Remove a property from an object literal while also eating one surrounding\n * comma so the resulting object stays syntactically valid. Prefers the\n * trailing comma; falls back to the leading comma when the property is the\n * last entry in the object.\n */\nfunction removePropertyWithSeparator(\n ms: MagicString,\n code: string,\n propStart: number,\n propEnd: number,\n): void {\n let i = propEnd;\n while (i < code.length && isWhitespace(code[i])) i++;\n if (code[i] === ',') {\n ms.remove(propStart, i + 1);\n return;\n }\n let j = propStart - 1;\n while (j >= 0 && isWhitespace(code[j])) j--;\n if (code[j] === ',') {\n ms.remove(j, propEnd);\n return;\n }\n ms.remove(propStart, propEnd);\n}\n\nfunction isWhitespace(ch: string): boolean {\n return (\n ch === ' ' ||\n ch === '\\t' ||\n ch === '\\n' ||\n ch === '\\r' ||\n ch === '\\f' ||\n ch === '\\v'\n );\n}\n\n/**\n * Extract inline style strings from Angular @Component decorator using OXC parser.\n * Returns an array of style string values for preprocessing.\n */\nexport function extractInlineStyles(\n code: string,\n fileName: string,\n program?: ReturnType<typeof parseSync>['program'],\n):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"resource-inliner.js","names":["path","extractStylesFromAst"],"sources":["../../../../src/lib/compiler/resource-inliner.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { parseSync } from 'oxc-parser';\nimport { parseOxc } from './utils.js';\nimport MagicString from 'magic-string';\nimport { extractInlineStyles as extractStylesFromAst } from './style-ast.js';\n\nexport interface InlineResourceResult {\n /** The modified source code, or the original if no changes were needed. */\n code: string;\n /**\n * Absolute path of each inlined external style, keyed by its position in\n * the flat per-file style list produced by {@link extractInlineStyles}. Lets\n * the caller preprocess each external `styleUrl` as its own file (extension\n * and relative imports), independent of the `inlineStylesExtension` option\n * (which governs truly-inline `styles: [...]` template strings).\n */\n stylePaths: Map<number, string>;\n /**\n * Absolute paths of every external resource file successfully read and\n * inlined. Callers record these so a later edit to the resource file can\n * invalidate the owning source module — the inlined copy is otherwise\n * invisible to the module graph.\n */\n resourceDependencies: string[];\n}\n\n/** Whether a node is an inline style value (string literal or single-quasi template). */\nfunction isInlineStyleValue(node: any): boolean {\n return (\n (node?.type === 'Literal' && typeof node.value === 'string') ||\n (node?.type === 'TemplateLiteral' && node.quasis?.length === 1)\n );\n}\n\n/** Count the elements of a `styles: [...]` array that {@link extractInlineStyles} would emit. */\nfunction countInlineStyleLiterals(arrayExpr: any): number {\n let count = 0;\n for (const el of arrayExpr.elements ?? []) {\n if (el?.type === 'Literal' && typeof el.value === 'string') count++;\n else if (el?.type === 'TemplateLiteral' && el.quasis?.length === 1) count++;\n }\n return count;\n}\n\n/**\n * Inline external templateUrl and styleUrl/styleUrls into the source code\n * using OXC parser for precise AST-based rewriting.\n *\n * Replaces:\n * templateUrl: './file.html' → template: \"...file contents...\"\n * styleUrl: './file.scss' → styles: [\"...file contents...\"]\n * styleUrls: ['./a.scss'] → styles: [\"...contents...\"]\n *\n * When the decorator already has a `styles: [...]` array, inlined CSS is\n * merged into that existing array instead of emitting a second `styles`\n * property (which would be a duplicate object literal key).\n *\n * Returns the modified source code plus the per-style-index path map\n * (see {@link InlineResourceResult}).\n */\nexport async function inlineResourceUrls(\n code: string,\n fileName: string,\n): Promise<InlineResourceResult> {\n const stylePaths = new Map<number, string>();\n\n if (!code.includes('templateUrl') && !code.includes('styleUrl')) {\n return { code, stylePaths, resourceDependencies: [] };\n }\n\n const { program } = parseOxc(fileName, code);\n const ms = new MagicString(code);\n let changed = false;\n const dir = path.dirname(fileName);\n\n // Phase 1: walk the AST and collect resource descriptors per decorator,\n // in source order — no I/O during the walk. A plan is recorded for every\n // `@Component` decorator (even without url props) because the flat style\n // index bookkeeping below advances per decorator.\n type ResourceProp =\n | { kind: 'templateUrl'; prop: any; resolvedPath: string }\n | { kind: 'styleUrl'; prop: any; resolvedPath: string }\n | { kind: 'styleUrls'; prop: any; resolvedPaths: string[] };\n interface DecoratorPlan {\n existingStylesProp: any;\n existingStylesArray: any;\n existingInlineCount: number;\n resourceProps: ResourceProp[];\n }\n const plans: DecoratorPlan[] = [];\n\n for (const node of program.body) {\n const decl =\n node.type === 'ExportNamedDeclaration' ||\n node.type === 'ExportDefaultDeclaration'\n ? (node as any).declaration\n : node;\n if (!decl || decl.type !== 'ClassDeclaration') continue;\n\n for (const dec of decl.decorators || []) {\n const expr = dec.expression;\n if (!expr || expr.type !== 'CallExpression') continue;\n if (expr.callee?.name !== 'Component') continue;\n\n const arg = expr.arguments?.[0];\n if (!arg || arg.type !== 'ObjectExpression') continue;\n\n // First pass: locate an existing `styles` property in the same decorator.\n // Inlined CSS is merged into it — converting a singular string/template\n // value to an array when needed — to avoid emitting a duplicate `styles`\n // key.\n let existingStylesProp: any = null;\n let existingStylesArray: any = null;\n for (const prop of arg.properties) {\n if (prop.type !== 'Property') continue;\n const key: string = prop.key?.name ?? prop.key?.value;\n if (key === 'styles') {\n existingStylesProp = prop;\n if (prop.value?.type === 'ArrayExpression') {\n existingStylesArray = prop.value;\n }\n break;\n }\n }\n\n // Inline `styles` entries already present come first in the flat list;\n // appended external styles follow them.\n const existingInlineCount = existingStylesArray\n ? countInlineStyleLiterals(existingStylesArray)\n : isInlineStyleValue(existingStylesProp?.value)\n ? 1\n : 0;\n\n const resourceProps: ResourceProp[] = [];\n\n for (const prop of arg.properties) {\n if (prop.type !== 'Property') continue;\n const key: string = prop.key?.name ?? prop.key?.value;\n const val = prop.value;\n\n if (\n key === 'templateUrl' &&\n val?.type === 'Literal' &&\n typeof val.value === 'string'\n ) {\n resourceProps.push({\n kind: 'templateUrl',\n prop,\n resolvedPath: path.resolve(dir, val.value),\n });\n continue;\n }\n\n if (\n key === 'styleUrl' &&\n val?.type === 'Literal' &&\n typeof val.value === 'string'\n ) {\n resourceProps.push({\n kind: 'styleUrl',\n prop,\n resolvedPath: path.resolve(dir, val.value),\n });\n continue;\n }\n\n if (key === 'styleUrls' && val?.type === 'ArrayExpression') {\n const resolvedPaths: string[] = [];\n for (const el of val.elements) {\n if (el?.type === 'Literal' && typeof el.value === 'string') {\n resolvedPaths.push(path.resolve(dir, el.value));\n }\n }\n resourceProps.push({ kind: 'styleUrls', prop, resolvedPaths });\n }\n }\n\n plans.push({\n existingStylesProp,\n existingStylesArray,\n existingInlineCount,\n resourceProps,\n });\n }\n }\n\n // Phase 2: read every referenced resource without blocking the event\n // loop. Each read catches its own failure to `undefined` — one missing\n // file must not abort sibling reads that succeed.\n const pathsToRead = new Set<string>();\n for (const plan of plans) {\n for (const rp of plan.resourceProps) {\n if (rp.kind === 'styleUrls') {\n for (const p of rp.resolvedPaths) pathsToRead.add(p);\n } else {\n pathsToRead.add(rp.resolvedPath);\n }\n }\n }\n const fileContents = new Map<string, string | undefined>();\n await Promise.all(\n [...pathsToRead].map(async (p) => {\n fileContents.set(\n p,\n await fs.promises.readFile(p, 'utf-8').catch(() => undefined),\n );\n }),\n );\n\n // Phase 3: apply MagicString rewrites in the original AST order so the\n // flat style index bookkeeping matches `extractInlineStyles`.\n\n // Running base index into the flat per-file style list (matching the order\n // `extractInlineStyles` walks classes/decorators/properties) so external\n // styles can be mapped to the index `resolvedInlineStyles` later keys on.\n let flatStyleBase = 0;\n\n for (const plan of plans) {\n const { existingStylesProp, existingStylesArray, existingInlineCount } =\n plan;\n\n // Collect the props we want to rewrite. Contents from styleUrl /\n // styleUrls are accumulated so that multiple url-based props in one\n // decorator collapse into a single `styles` array write. `paths`\n // tracks each content's source path in the same order.\n const templateUrlRewrites: Array<{ prop: any; content: string }> = [];\n const cssProps: Array<{\n prop: any;\n contents: string[];\n paths: string[];\n }> = [];\n\n for (const rp of plan.resourceProps) {\n if (rp.kind === 'templateUrl') {\n // Keep original if file can't be read\n const content = fileContents.get(rp.resolvedPath);\n if (content !== undefined) {\n templateUrlRewrites.push({ prop: rp.prop, content });\n }\n } else if (rp.kind === 'styleUrl') {\n // Keep original if file can't be read\n const content = fileContents.get(rp.resolvedPath);\n if (content !== undefined) {\n cssProps.push({\n prop: rp.prop,\n contents: [content],\n paths: [rp.resolvedPath],\n });\n }\n } else {\n // styleUrls is all-or-nothing: keep the original property if any\n // entry failed to read.\n const contents: string[] = [];\n let allRead = true;\n for (const p of rp.resolvedPaths) {\n const content = fileContents.get(p);\n if (content === undefined) {\n allRead = false;\n break;\n }\n contents.push(content);\n }\n if (allRead && contents.length > 0) {\n cssProps.push({ prop: rp.prop, contents, paths: rp.resolvedPaths });\n }\n }\n }\n\n for (const { prop, content } of templateUrlRewrites) {\n ms.overwrite(\n prop.start,\n prop.end,\n `template: ${JSON.stringify(content)}`,\n );\n changed = true;\n }\n\n if (cssProps.length > 0) {\n const allContents = cssProps.flatMap((c) => c.contents);\n const allPaths = cssProps.flatMap((c) => c.paths);\n\n if (existingStylesArray) {\n // Filter out null holes in case the source already has a sparse array.\n const realElements = (existingStylesArray.elements as any[]).filter(\n (e) => e != null,\n );\n\n if (realElements.length > 0) {\n // Insert right after the last real element. This preserves any\n // trailing comma the source may have (e.g. Prettier output) and\n // avoids producing a sparse `[existing, , \"new\"]` element, which\n // would crash downstream decorator metadata extraction.\n const lastElement = realElements[realElements.length - 1];\n const insertion = allContents\n .map((c) => `, ${JSON.stringify(c)}`)\n .join('');\n ms.appendRight(lastElement.end, insertion);\n } else {\n // Empty array — drop the leading comma.\n const insertion = allContents\n .map((c) => JSON.stringify(c))\n .join(', ');\n ms.appendLeft(existingStylesArray.end - 1, insertion);\n }\n\n for (const { prop } of cssProps) {\n removePropertyWithSeparator(ms, code, prop.start, prop.end);\n }\n } else if (isInlineStyleValue(existingStylesProp?.value)) {\n // Singular `styles: '...'` / `styles: \\`...\\`` — wrap the original\n // value into an array merged with the inlined styles, then drop the\n // styleUrl props so only one `styles` key remains.\n const original = code.slice(\n existingStylesProp.value.start,\n existingStylesProp.value.end,\n );\n const merged = allContents\n .map((c) => `, ${JSON.stringify(c)}`)\n .join('');\n ms.overwrite(\n existingStylesProp.value.start,\n existingStylesProp.value.end,\n `[${original}${merged}]`,\n );\n for (const { prop } of cssProps) {\n removePropertyWithSeparator(ms, code, prop.start, prop.end);\n }\n } else {\n // No existing `styles` array — rewrite the first styleUrl/styleUrls\n // prop with the merged contents and drop any additional ones so we\n // don't emit multiple `styles` properties.\n const [first, ...rest] = cssProps;\n ms.overwrite(\n first.prop.start,\n first.prop.end,\n `styles: [${allContents.map((c) => JSON.stringify(c)).join(', ')}]`,\n );\n for (const { prop } of rest) {\n removePropertyWithSeparator(ms, code, prop.start, prop.end);\n }\n }\n changed = true;\n\n // The appended external styles occupy the flat indices after any\n // pre-existing inline styles for this component.\n const externalBase = flatStyleBase + existingInlineCount;\n allPaths.forEach((p, k) => stylePaths.set(externalBase + k, p));\n flatStyleBase = externalBase + allContents.length;\n } else {\n flatStyleBase += existingInlineCount;\n }\n }\n\n return {\n code: changed ? ms.toString() : code,\n stylePaths,\n resourceDependencies: [...pathsToRead].filter(\n (p) => fileContents.get(p) !== undefined,\n ),\n };\n}\n\n/**\n * Remove a property from an object literal while also eating one surrounding\n * comma so the resulting object stays syntactically valid. Prefers the\n * trailing comma; falls back to the leading comma when the property is the\n * last entry in the object.\n */\nfunction removePropertyWithSeparator(\n ms: MagicString,\n code: string,\n propStart: number,\n propEnd: number,\n): void {\n let i = propEnd;\n while (i < code.length && isWhitespace(code[i])) i++;\n if (code[i] === ',') {\n ms.remove(propStart, i + 1);\n return;\n }\n let j = propStart - 1;\n while (j >= 0 && isWhitespace(code[j])) j--;\n if (code[j] === ',') {\n ms.remove(j, propEnd);\n return;\n }\n ms.remove(propStart, propEnd);\n}\n\nfunction isWhitespace(ch: string): boolean {\n return (\n ch === ' ' ||\n ch === '\\t' ||\n ch === '\\n' ||\n ch === '\\r' ||\n ch === '\\f' ||\n ch === '\\v'\n );\n}\n\n/**\n * Extract inline style strings from Angular @Component decorator using OXC parser.\n * Returns an array of style string values for preprocessing.\n */\nexport function extractInlineStyles(\n code: string,\n fileName: string,\n program?: ReturnType<typeof parseSync>['program'],\n): string[] {\n if (!code.includes('styles')) return [];\n return extractStylesFromAst(code, fileName, program);\n}\n"],"mappings":";;;;;;;AA4BA,SAAS,mBAAmB,MAAoB;CAC9C,OACG,MAAM,SAAS,aAAa,OAAO,KAAK,UAAU,YAClD,MAAM,SAAS,qBAAqB,KAAK,QAAQ,WAAW;AAEjE;;AAGA,SAAS,yBAAyB,WAAwB;CACxD,IAAI,QAAQ;CACZ,KAAK,MAAM,MAAM,UAAU,YAAY,CAAC,GACtC,IAAI,IAAI,SAAS,aAAa,OAAO,GAAG,UAAU,UAAU;MACvD,IAAI,IAAI,SAAS,qBAAqB,GAAG,QAAQ,WAAW,GAAG;CAEtE,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,eAAsB,mBACpB,MACA,UAC+B;CAC/B,MAAM,6BAAa,IAAI,IAAoB;CAE3C,IAAI,CAAC,KAAK,SAAS,aAAa,KAAK,CAAC,KAAK,SAAS,UAAU,GAC5D,OAAO;EAAE;EAAM;EAAY,sBAAsB,CAAC;CAAE;CAGtD,MAAM,EAAE,YAAY,SAAS,UAAU,IAAI;CAC3C,MAAM,KAAK,IAAI,YAAY,IAAI;CAC/B,IAAI,UAAU;CACd,MA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ACA,GAAG,OAAO,WAAW,OAAO;AAC9B;AAEA,SAAS,aAAa,IAAqB;CACzC,OACE,OAAO,OACP,OAAO,OACP,OAAO,QACP,OAAO,QACP,OAAO,QACP,OAAO;AAEX;;;;;AAMA,SAAgB,oBACd,MACA,UACA,SACU;CACV,IAAI,CAAC,KAAK,SAAS,QAAQ,GAAG,OAAO,CAAC;CACtC,OAAOC,sBAAqB,MAAM,UAAU,OAAO;AACrD"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { parseSync } from "oxc-parser";
|
|
1
|
+
import type { parseSync } from "oxc-parser";
|
|
2
|
+
/** An object property's key, quoted (`'styles'`) or not (`styles`). */
|
|
3
|
+
export declare function getPropertyKey(prop: any): string | undefined;
|
|
2
4
|
/**
|
|
3
5
|
* Extract styleUrl/styleUrls values from Angular @Component decorators.
|
|
4
6
|
*/
|
|
@@ -7,3 +9,22 @@ export declare function extractStyleUrls(code: string, fileName: string): string
|
|
|
7
9
|
* Extract inline style strings from Angular @Component decorators.
|
|
8
10
|
*/
|
|
9
11
|
export declare function extractInlineStyles(code: string, fileName: string, program?: ReturnType<typeof parseSync>["program"]): string[];
|
|
12
|
+
/**
|
|
13
|
+
* An inline style string, the AST node it was read from, and its position in
|
|
14
|
+
* the `styles` array (0 for a single `styles` value).
|
|
15
|
+
*/
|
|
16
|
+
export interface InlineStyle {
|
|
17
|
+
text: string;
|
|
18
|
+
node: any;
|
|
19
|
+
index: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A component's inline styles and the index of the first one in the flat
|
|
23
|
+
* per-file list returned by {@link extractInlineStyles}.
|
|
24
|
+
*/
|
|
25
|
+
export interface InlineStyleRange {
|
|
26
|
+
start: number;
|
|
27
|
+
styles: InlineStyle[];
|
|
28
|
+
}
|
|
29
|
+
/** Map each @Component decorator node to its {@link InlineStyleRange}. */
|
|
30
|
+
export declare function inlineStyleRanges(program: ReturnType<typeof parseSync>["program"]): Map<any, InlineStyleRange>;
|
|
@@ -1,11 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { parseOxc } from "./utils.js";
|
|
2
|
+
// packages/vite-plugin-angular/src/lib/compiler/style-ast.ts
|
|
3
3
|
function getClassDeclaration(node) {
|
|
4
4
|
return node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration" ? node.declaration : node;
|
|
5
5
|
}
|
|
6
|
+
/** An object property's key, quoted (`'styles'`) or not (`styles`). */
|
|
6
7
|
function getPropertyKey(prop) {
|
|
7
8
|
return prop.key?.name || prop.key?.value;
|
|
8
9
|
}
|
|
10
|
+
function styleText(node) {
|
|
11
|
+
if (node?.type === "Literal" && typeof node.value === "string") return node.value;
|
|
12
|
+
return getTemplateLiteralText(node);
|
|
13
|
+
}
|
|
9
14
|
function getTemplateLiteralText(node) {
|
|
10
15
|
if (node?.type !== "TemplateLiteral" || node.quasis?.length !== 1) return;
|
|
11
16
|
return node.quasis[0].value.cooked || node.quasis[0].value.raw;
|
|
@@ -14,8 +19,24 @@ function getTemplateLiteralText(node) {
|
|
|
14
19
|
* Extract inline style strings from Angular @Component decorators.
|
|
15
20
|
*/
|
|
16
21
|
function extractInlineStyles(code, fileName, program) {
|
|
17
|
-
|
|
18
|
-
program
|
|
22
|
+
program ??= parseOxc(fileName, code).program;
|
|
23
|
+
return [...componentInlineStyles(program).values()].flat().map((style) => style.text);
|
|
24
|
+
}
|
|
25
|
+
/** Map each @Component decorator node to its {@link InlineStyleRange}. */
|
|
26
|
+
function inlineStyleRanges(program) {
|
|
27
|
+
const ranges = /* @__PURE__ */ new Map();
|
|
28
|
+
let start = 0;
|
|
29
|
+
for (const [decorator, styles] of componentInlineStyles(program)) {
|
|
30
|
+
ranges.set(decorator, {
|
|
31
|
+
start,
|
|
32
|
+
styles
|
|
33
|
+
});
|
|
34
|
+
start += styles.length;
|
|
35
|
+
}
|
|
36
|
+
return ranges;
|
|
37
|
+
}
|
|
38
|
+
function componentInlineStyles(program) {
|
|
39
|
+
const result = /* @__PURE__ */ new Map();
|
|
19
40
|
for (const node of program.body) {
|
|
20
41
|
const decl = getClassDeclaration(node);
|
|
21
42
|
if (!decl || decl.type !== "ClassDeclaration") continue;
|
|
@@ -25,30 +46,26 @@ function extractInlineStyles(code, fileName, program) {
|
|
|
25
46
|
if (expr.callee?.name !== "Component") continue;
|
|
26
47
|
const arg = expr.arguments?.[0];
|
|
27
48
|
if (!arg || arg.type !== "ObjectExpression") continue;
|
|
49
|
+
const styles = [];
|
|
50
|
+
result.set(dec, styles);
|
|
28
51
|
for (const prop of arg.properties) {
|
|
29
52
|
if (prop.type !== "Property") continue;
|
|
30
53
|
const key = getPropertyKey(prop);
|
|
31
54
|
const val = prop.value;
|
|
32
55
|
if (key !== "styles") continue;
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
}
|
|
41
|
-
else if (val?.type === "Literal" && typeof val.value === "string") styles.push(val.value);
|
|
42
|
-
else {
|
|
43
|
-
const templateText = getTemplateLiteralText(val);
|
|
44
|
-
if (templateText !== void 0) styles.push(templateText);
|
|
45
|
-
}
|
|
56
|
+
(val?.type === "ArrayExpression" ? val.elements : [val]).forEach((node, index) => {
|
|
57
|
+
const text = styleText(node);
|
|
58
|
+
if (text !== void 0) styles.push({
|
|
59
|
+
text,
|
|
60
|
+
node,
|
|
61
|
+
index
|
|
62
|
+
});
|
|
63
|
+
});
|
|
46
64
|
}
|
|
47
65
|
}
|
|
48
66
|
}
|
|
49
|
-
return
|
|
67
|
+
return result;
|
|
50
68
|
}
|
|
51
|
-
|
|
52
|
-
export { extractInlineStyles };
|
|
69
|
+
export { extractInlineStyles, getPropertyKey, inlineStyleRanges };
|
|
53
70
|
|
|
54
71
|
//# sourceMappingURL=style-ast.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"style-ast.js","names":[],"sources":["../../../../src/lib/compiler/style-ast.ts"],"sourcesContent":["import { parseSync } from 'oxc-parser';\n\ntype ProgramNode = ReturnType<typeof parseSync>['program']['body'][number];\n\nfunction getClassDeclaration(node: ProgramNode): any {\n return node.type === 'ExportNamedDeclaration' ||\n node.type === 'ExportDefaultDeclaration'\n ? (node as any).declaration\n : node;\n}\n\
|
|
1
|
+
{"version":3,"file":"style-ast.js","names":[],"sources":["../../../../src/lib/compiler/style-ast.ts"],"sourcesContent":["import type { parseSync } from 'oxc-parser';\nimport { parseOxc } from './utils.js';\n\ntype ProgramNode = ReturnType<typeof parseSync>['program']['body'][number];\n\nfunction getClassDeclaration(node: ProgramNode): any {\n return node.type === 'ExportNamedDeclaration' ||\n node.type === 'ExportDefaultDeclaration'\n ? (node as any).declaration\n : node;\n}\n\n/** An object property's key, quoted (`'styles'`) or not (`styles`). */\nexport function getPropertyKey(prop: any): string | undefined {\n return prop.key?.name || prop.key?.value;\n}\n\nfunction styleText(node: any): string | undefined {\n if (node?.type === 'Literal' && typeof node.value === 'string') {\n return node.value;\n }\n return getTemplateLiteralText(node);\n}\n\nfunction getTemplateLiteralText(node: any): string | undefined {\n if (node?.type !== 'TemplateLiteral' || node.quasis?.length !== 1) {\n return undefined;\n }\n\n return node.quasis[0].value.cooked || node.quasis[0].value.raw;\n}\n\n/**\n * Extract styleUrl/styleUrls values from Angular @Component decorators.\n */\nexport function extractStyleUrls(code: string, fileName: string): string[] {\n const urls: string[] = [];\n const { program } = parseOxc(fileName, code);\n\n for (const node of program.body) {\n const decl = getClassDeclaration(node);\n if (!decl || decl.type !== 'ClassDeclaration') continue;\n\n for (const dec of decl.decorators || []) {\n const expr = dec.expression;\n if (!expr || expr.type !== 'CallExpression') continue;\n if (expr.callee?.name !== 'Component') continue;\n\n const arg = expr.arguments?.[0];\n if (!arg || arg.type !== 'ObjectExpression') continue;\n\n for (const prop of arg.properties) {\n if (prop.type !== 'Property') continue;\n const key = getPropertyKey(prop);\n const val = prop.value;\n\n if (\n key === 'styleUrl' &&\n val?.type === 'Literal' &&\n typeof val.value === 'string'\n ) {\n urls.push(val.value);\n }\n\n if (key === 'styleUrls' && val?.type === 'ArrayExpression') {\n for (const el of val.elements) {\n if (el?.type === 'Literal' && typeof el.value === 'string') {\n urls.push(el.value);\n }\n }\n }\n }\n }\n }\n\n return urls;\n}\n\n/**\n * Extract inline style strings from Angular @Component decorators.\n */\nexport function extractInlineStyles(\n code: string,\n fileName: string,\n program?: ReturnType<typeof parseSync>['program'],\n): string[] {\n program ??= parseOxc(fileName, code).program;\n return [...componentInlineStyles(program).values()]\n .flat()\n .map((style) => style.text);\n}\n\n/**\n * An inline style string, the AST node it was read from, and its position in\n * the `styles` array (0 for a single `styles` value).\n */\nexport interface InlineStyle {\n text: string;\n node: any;\n index: number;\n}\n\n/**\n * A component's inline styles and the index of the first one in the flat\n * per-file list returned by {@link extractInlineStyles}.\n */\nexport interface InlineStyleRange {\n start: number;\n styles: InlineStyle[];\n}\n\n/** Map each @Component decorator node to its {@link InlineStyleRange}. */\nexport function inlineStyleRanges(\n program: ReturnType<typeof parseSync>['program'],\n): Map<any, InlineStyleRange> {\n const ranges = new Map<any, InlineStyleRange>();\n let start = 0;\n for (const [decorator, styles] of componentInlineStyles(program)) {\n ranges.set(decorator, { start, styles });\n start += styles.length;\n }\n return ranges;\n}\n\nfunction componentInlineStyles(\n program: ReturnType<typeof parseSync>['program'],\n): Map<any, InlineStyle[]> {\n const result = new Map<any, InlineStyle[]>();\n\n for (const node of program.body) {\n const decl = getClassDeclaration(node);\n if (!decl || decl.type !== 'ClassDeclaration') continue;\n\n for (const dec of decl.decorators || []) {\n const expr = dec.expression;\n if (!expr || expr.type !== 'CallExpression') continue;\n if (expr.callee?.name !== 'Component') continue;\n\n const arg = expr.arguments?.[0];\n if (!arg || arg.type !== 'ObjectExpression') continue;\n\n const styles: InlineStyle[] = [];\n result.set(dec, styles);\n\n for (const prop of arg.properties) {\n if (prop.type !== 'Property') continue;\n const key = getPropertyKey(prop);\n const val = prop.value;\n\n if (key !== 'styles') continue;\n\n const nodes = val?.type === 'ArrayExpression' ? val.elements : [val];\n nodes.forEach((node: any, index: number) => {\n const text = styleText(node);\n if (text !== undefined) styles.push({ text, node, index });\n });\n }\n }\n }\n\n return result;\n}\n"],"mappings":";;AAKA,SAAS,oBAAoB,MAAwB;CACnD,OAAO,KAAK,SAAS,4BACnB,KAAK,SAAS,6BACX,KAAa,cACd;AACN;;AAGA,SAAgB,eAAe,MAA+B;CAC5D,OAAO,KAAK,KAAK,QAAQ,KAAK,KAAK;AACrC;AAEA,SAAS,UAAU,MAA+B;CAChD,IAAI,MAAM,SAAS,aAAa,OAAO,KAAK,UAAU,UACpD,OAAO,KAAK;CAEd,OAAO,uBAAuB,IAAI;AACpC;AAEA,SAAS,uBAAuB,MAA+B;CAC7D,IAAI,MAAM,SAAS,qBAAqB,KAAK,QAAQ,WAAW,GAC9D;CAGF,OAAO,KAAK,OAAO,EAAE,CAAC,MAAM,UAAU,KAAK,OAAO,EAAE,CAAC,MAAM;AAC7D;;;;AAmDA,SAAgB,oBACd,MACA,UACA,SACU;CACV,YAAY,SAAS,UAAU,IAAI,CAAC,CAAC;CACrC,OAAO,CAAC,GAAG,sBAAsB,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,CAChD,KAAK,CAAC,CACN,KAAK,UAAU,MAAM,IAAI;AAC9B;;AAsBA,SAAgB,kBACd,SAC4B;CAC5B,MAAM,yBAAS,IAAI,IAA2B;CAC9C,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,WAAW,WAAW,sBAAsB,OAAO,GAAG;EAChE,OAAO,IAAI,WAAW;GAAE;GAAO;EAAO,CAAC;EACvC,SAAS,OAAO;CAClB;CACA,OAAO;AACT;AAEA,SAAS,sBACP,SACyB;CACzB,MAAM,yBAAS,IAAI,IAAwB;CAE3C,KAAK,MAAM,QAAQ,QAAQ,MAAM;EAC/B,MAAM,OAAO,oBAAoB,IAAI;EACrC,IAAI,CAAC,QAAQ,KAAK,SAAS,oBAAoB;EAE/C,KAAK,MAAM,OAAO,KAAK,cAAc,CAAC,GAAG;GACvC,MAAM,OAAO,IAAI;GACjB,IAAI,CAAC,QAAQ,KAAK,SAAS,kBAAkB;GAC7C,IAAI,KAAK,QAAQ,SAAS,aAAa;GAEvC,MAAM,MAAM,KAAK,YAAY;GAC7B,IAAI,CAAC,OAAO,IAAI,SAAS,oBAAoB;GAE7C,MAAM,SAAwB,CAAC;GAC/B,OAAO,IAAI,KAAK,MAAM;GAEtB,KAAK,MAAM,QAAQ,IAAI,YAAY;IACjC,IAAI,KAAK,SAAS,YAAY;IAC9B,MAAM,MAAM,eAAe,IAAI;IAC/B,MAAM,MAAM,KAAK;IAEjB,IAAI,QAAQ,UAAU;IAGtB,CADc,KAAK,SAAS,oBAAoB,IAAI,WAAW,CAAC,GAAG,EAAA,CAC7D,SAAS,MAAW,UAAkB;KAC1C,MAAM,OAAO,UAAU,IAAI;KAC3B,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK;MAAE;MAAM;MAAM;KAAM,CAAC;IAC3D,CAAC;GACH;EACF;CACF;CAEA,OAAO;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import MagicString from "magic-string";
|
|
2
|
-
import { parseSync } from "oxc-parser";
|
|
2
|
+
import type { parseSync } from "oxc-parser";
|
|
3
3
|
/**
|
|
4
4
|
* Analyse compiled TypeScript source and return the set of imported names
|
|
5
5
|
* that are only referenced in type positions (type annotations, implements
|
|
@@ -23,6 +23,7 @@ export declare function elideTypeOnlyImports(code: string): string;
|
|
|
23
23
|
* Detects type-only names from `ms.toString()` (the fully-mutated code),
|
|
24
24
|
* but reads import positions from `ms.original` (the coordinate system
|
|
25
25
|
* MagicString expects). `originalProgram`, when provided, must be a parse
|
|
26
|
-
* of `ms.original` — never of the mutated text.
|
|
26
|
+
* of `ms.original` — never of the mutated text. `typeOnlyNames` may be passed
|
|
27
|
+
* when the caller already analysed the mutated code.
|
|
27
28
|
*/
|
|
28
|
-
export declare function elideTypeOnlyImportsMagicString(ms: MagicString, originalProgram?: ReturnType<typeof parseSync>["program"]): void;
|
|
29
|
+
export declare function elideTypeOnlyImportsMagicString(ms: MagicString, originalProgram?: ReturnType<typeof parseSync>["program"], typeOnlyNames?): void;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { findAllClasses, parseOxc } from "./utils.js";
|
|
2
2
|
import "magic-string";
|
|
3
|
-
|
|
3
|
+
// packages/vite-plugin-angular/src/lib/compiler/type-elision.ts
|
|
4
4
|
/**
|
|
5
5
|
* AST property keys that represent type-only positions in TypeScript.
|
|
6
6
|
* Identifiers found only under these keys are never emitted as runtime values.
|
|
@@ -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,14 +197,13 @@ 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
|
-
//#endregion
|
|
209
207
|
export { detectTypeOnlyImportNames, elideTypeOnlyImportsMagicString };
|
|
210
208
|
|
|
211
209
|
//# sourceMappingURL=type-elision.js.map
|
|
@@ -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,IAAI,IAAY;CACtC,KAAK,MAAM,QAAS,IAAY,MAAM;EACpC,IAAI,KAAK,SAAS,qBAAqB;EACvC,IAAI,KAAK,eAAe,QAAQ;EAChC,KAAK,MAAM,QAAQ,KAAK,cAAc,CAAC,GAAG;GACxC,IAAI,KAAK,eAAe,QAAQ;GAChC,cAAc,IAAI,KAAK,MAAM,IAAI;EACnC;CACF;CACA,IAAI,cAAc,SAAS,GAAG,OAAO;EAAE;EAAK,+BAAe,IAAI,IAAI;CAAE;CAGrE,MAAM,kCAAkB,IAAI,IAAY;CAOxC,2BAA2B,KAAK,eAAe,eAAe;CAE9D,SAAS,KAAK,MAAW,gBAA+B;EACtD,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU;EACvC,IAAI,MAAM,QAAQ,IAAI,GAAG;GACvB,KAAK,MAAM,QAAQ,MAAM,KAAK,MAAM,cAAc;GAClD;EACF;EAGA,IAAI,gBAAgB,SAAS,cAAc,MAAM;EAKjD,IAAI,CAAC,kBAAkB,gBAAgB,IAAI,KAAK,IAAI,GAAG;GACrD,IACE,KAAK,SAAS,oBACd,KAAK,SAAS,yBACd;IAEA,KAAK,KAAK,YAAY,K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AG,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;CACA;CACA;AACF,CAAC;;;;;AAMD,SAAS,uBACP,MACA,SAIA;CACA,MAAM,MAAM,WAAW,SAAS,WAAW,IAAI,CAAC,CAAC;CAMjD,MAAM,gCAAgB,IAAI,IAAY;CACtC,KAAK,MAAM,QAAS,IAAY,MAAM;EACpC,IAAI,KAAK,SAAS,qBAAqB;EACvC,IAAI,KAAK,eAAe,QAAQ;EAChC,KAAK,MAAM,QAAQ,KAAK,cAAc,CAAC,GAAG;GACxC,IAAI,KAAK,eAAe,QAAQ;GAChC,cAAc,IAAI,KAAK,MAAM,IAAI;EACnC;CACF;CACA,IAAI,cAAc,SAAS,GAAG,OAAO;EAAE;EAAK,+BAAe,IAAI,IAAI;CAAE;CAGrE,MAAM,kCAAkB,IAAI,IAAY;CAOxC,2BAA2B,KAAK,eAAe,eAAe;CAE9D,SAAS,KAAK,MAAW,gBAA+B;EACtD,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU;EACvC,IAAI,MAAM,QAAQ,IAAI,GAAG;GACvB,KAAK,MAAM,QAAQ,MAAM,KAAK,MAAM,cAAc;GAClD;EACF;EAGA,IAAI,gBAAgB,SAAS,cAAc,MAAM;EAK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AAI,cAAc,SAAS,GAAG;CAI9B,kBAAkB,IADN,mBAAmB,SAAS,WAAW,GAAG,QAAQ,CAAC,CAAC,SACrC,GAAG,UAAU,aAAa;AACvD"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import { type ParseResult } from "oxc-parser";
|
|
2
|
+
export declare function parseOxc(fileName: string, code: string): ParseResult;
|
|
3
|
+
/** Recursively find all class declarations in an OXC AST, including nested scopes. */
|
|
4
|
+
export declare function findAllClasses(program: any): any[];
|
|
5
|
+
/**
|
|
6
|
+
* Depth-first walk over OXC AST nodes. `visit` returns `false` to skip a
|
|
7
|
+
* node's children.
|
|
8
|
+
*/
|
|
9
|
+
export declare function walkOxc(node: any, visit: (node: any) => boolean): void;
|
|
8
10
|
/** Unwrap forwardRef(() => X) to X for OXC AST nodes. Returns the original node if not a forwardRef call. */
|
|
9
11
|
export declare function unwrapForwardRefOxc(node: any): any;
|
|
10
12
|
/**
|