@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.
Files changed (68) hide show
  1. package/ngp/LICENSE +21 -0
  2. package/ngp/api.mjs +46048 -0
  3. package/ngp/build.json +4 -0
  4. package/ngp/ng_analyze.cjs +504 -0
  5. package/ngp/ng_analyze_bg.wasm +0 -0
  6. package/package.json +1 -1
  7. package/src/lib/angular-build-optimizer-plugin.js +6 -3
  8. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  9. package/src/lib/angular-vite-plugin.d.ts +20 -5
  10. package/src/lib/angular-vite-plugin.js +28 -13
  11. package/src/lib/angular-vite-plugin.js.map +1 -1
  12. package/src/lib/compiler/compile.d.ts +1 -1
  13. package/src/lib/compiler/compile.js +137 -134
  14. package/src/lib/compiler/compile.js.map +1 -1
  15. package/src/lib/compiler/defer.d.ts +2 -3
  16. package/src/lib/compiler/defer.js +11 -13
  17. package/src/lib/compiler/defer.js.map +1 -1
  18. package/src/lib/compiler/dts-reader.d.ts +6 -1
  19. package/src/lib/compiler/dts-reader.js +15 -9
  20. package/src/lib/compiler/dts-reader.js.map +1 -1
  21. package/src/lib/compiler/hmr.d.ts +4 -0
  22. package/src/lib/compiler/hmr.js +7 -2
  23. package/src/lib/compiler/hmr.js.map +1 -1
  24. package/src/lib/compiler/index.d.ts +2 -2
  25. package/src/lib/compiler/index.js +3 -3
  26. package/src/lib/compiler/jit-metadata.d.ts +3 -1
  27. package/src/lib/compiler/jit-metadata.js +10 -8
  28. package/src/lib/compiler/jit-metadata.js.map +1 -1
  29. package/src/lib/compiler/jit-transform.js +2 -2
  30. package/src/lib/compiler/jit-transform.js.map +1 -1
  31. package/src/lib/compiler/js-emitter.d.ts +0 -3
  32. package/src/lib/compiler/js-emitter.js +3 -21
  33. package/src/lib/compiler/js-emitter.js.map +1 -1
  34. package/src/lib/compiler/registry.d.ts +7 -1
  35. package/src/lib/compiler/registry.js +23 -3
  36. package/src/lib/compiler/registry.js.map +1 -1
  37. package/src/lib/compiler/resource-inliner.d.ts +1 -1
  38. package/src/lib/compiler/resource-inliner.js +2 -2
  39. package/src/lib/compiler/resource-inliner.js.map +1 -1
  40. package/src/lib/compiler/style-ast.d.ts +1 -1
  41. package/src/lib/compiler/style-ast.js +2 -2
  42. package/src/lib/compiler/style-ast.js.map +1 -1
  43. package/src/lib/compiler/type-elision.d.ts +4 -3
  44. package/src/lib/compiler/type-elision.js +10 -11
  45. package/src/lib/compiler/type-elision.js.map +1 -1
  46. package/src/lib/compiler/utils.d.ts +14 -7
  47. package/src/lib/compiler/utils.js +38 -9
  48. package/src/lib/compiler/utils.js.map +1 -1
  49. package/src/lib/fast-compile-plugin.d.ts +3 -0
  50. package/src/lib/fast-compile-plugin.js +101 -19
  51. package/src/lib/fast-compile-plugin.js.map +1 -1
  52. package/src/lib/live-reload-plugin.d.ts +4 -3
  53. package/src/lib/live-reload-plugin.js +4 -3
  54. package/src/lib/live-reload-plugin.js.map +1 -1
  55. package/src/lib/ngp-compile-plugin.d.ts +3 -0
  56. package/src/lib/ngp-compile-plugin.js +344 -0
  57. package/src/lib/ngp-compile-plugin.js.map +1 -0
  58. package/src/lib/tools/src/builders/vite/vite-build.impl.js +2 -1
  59. package/src/lib/tools/src/builders/vite/vite-build.impl.js.map +1 -1
  60. package/src/lib/utils/hmr-component-updates.d.ts +7 -0
  61. package/src/lib/utils/hmr-component-updates.js +87 -0
  62. package/src/lib/utils/hmr-component-updates.js.map +1 -0
  63. package/src/lib/utils/lsp-type-checker.d.ts +55 -0
  64. package/src/lib/utils/lsp-type-checker.js +502 -0
  65. package/src/lib/utils/lsp-type-checker.js.map +1 -0
  66. package/src/lib/utils/plugin-config.d.ts +9 -0
  67. package/src/lib/utils/plugin-config.js +10 -1
  68. package/src/lib/utils/plugin-config.js.map +1 -1
@@ -1,22 +1,34 @@
1
1
  import { ANGULAR_DECORATORS, FIELD_DECORATORS } from "./constants.js";
2
- import { findAllClasses, resolveSyntheticImportSpecifier } from "./utils.js";
2
+ import { findAllClasses, parseOxc, resolveSyntheticImportSpecifier, walkOxc } from "./utils.js";
3
3
  import { angularVersionAtLeast } from "./angular-version.js";
4
4
  import { detectTypeOnlyImportNames, elideTypeOnlyImportsMagicString } from "./type-elision.js";
5
- import { emitAngularExpr, emitAngularStmt, setEmitterSourceCode, setEmitterSourceFile } from "./js-emitter.js";
5
+ import { emitAngularExpr, emitAngularStmt, setEmitterSourceCode } from "./js-emitter.js";
6
6
  import { lowerClassFields } from "./class-field-lowering.js";
7
7
  import { collectStringConstants, detectFieldDecorators, detectSignals, extractConstructorDeps, extractMetadata } from "./metadata.js";
8
8
  import { buildDeferDependencyMap } from "./defer.js";
9
+ import { buildCtorParameters, buildPropDecorators } from "./jit-metadata.js";
9
10
  import { debugCompile } from "./debug.js";
10
11
  import * as fs from "node:fs";
11
12
  import * as path$1 from "node:path";
12
13
  import * as o from "@angular/compiler";
13
14
  import { ConstantPool, FactoryTarget, ParseLocation, ParseSourceFile, ParseSourceSpan, R3NgModuleMetadataKind, R3SelectorScopeMode, compileClassMetadata, compileComponentFromMetadata, compileDeclareClassMetadata, compileDeclareComponentFromMetadata, compileDeclareDirectiveFromMetadata, compileDeclareFactoryFunction, compileDeclareInjectableFromMetadata, compileDeclareInjectorFromMetadata, compileDeclareNgModuleFromMetadata, compileDeclarePipeFromMetadata, compileDirectiveFromMetadata, compileFactoryFunction, compileInjector, compileNgModule, compilePipeFromMetadata, makeBindingParser, parseHostBindings, parseTemplate } from "@angular/compiler";
14
- import { parseSync } from "oxc-parser";
15
- import * as ts from "typescript";
16
15
  import MagicString from "magic-string";
17
16
  //#region packages/vite-plugin-angular/src/lib/compiler/compile.ts
18
- function hasExportModifier(node) {
19
- return ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) === true;
17
+ function toTopLevelStatement(stmt) {
18
+ const isExport = (stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration") && stmt.declaration;
19
+ const decl = isExport ? stmt.declaration : stmt;
20
+ return {
21
+ decl,
22
+ exported: !!isExport,
23
+ start: Math.min(stmt.start, decl.decorators?.[0]?.start ?? stmt.start),
24
+ end: stmt.end
25
+ };
26
+ }
27
+ /** Get the callee name of a decorator call, e.g. `Component` for `@Component(...)`. */
28
+ function decoratorCallName(dec, sourceCode) {
29
+ const callee = dec.expression;
30
+ if (callee?.type !== "CallExpression") return void 0;
31
+ return sourceCode.slice(callee.callee.start, callee.callee.end);
20
32
  }
21
33
  /**
22
34
  * Normalize a `providers` / `viewProviders` metadata value into the single
@@ -34,37 +46,59 @@ function providersToExpr(value) {
34
46
  if (Array.isArray(value)) return value.length ? new o.LiteralArrayExpr(value) : null;
35
47
  return value;
36
48
  }
49
+ var LAZY_SCOPE_TYPES = /* @__PURE__ */ new Set([
50
+ "FunctionDeclaration",
51
+ "FunctionExpression",
52
+ "ArrowFunctionExpression",
53
+ "ClassDeclaration",
54
+ "ClassExpression",
55
+ "TSFunctionType",
56
+ "TSConstructorType",
57
+ "TSMethodSignature",
58
+ "TSCallSignatureDeclaration",
59
+ "TSConstructSignatureDeclaration"
60
+ ]);
37
61
  /**
38
62
  * Collect identifier names referenced in eagerly-evaluated code only.
39
63
  * Skips function/arrow/class bodies so that lazy references
40
64
  * (e.g. `const TOKEN = () => LaterClass`) are not treated as dependencies.
65
+ * The root node's own children are always walked.
41
66
  */
42
- function collectIdentifiers(node) {
67
+ function collectIdentifiers(root) {
43
68
  const ids = /* @__PURE__ */ new Set();
44
- function walk(n) {
45
- if (ts.isIdentifier(n)) ids.add(n.text);
46
- if (ts.isFunctionLike(n) || ts.isClassLike(n)) return;
47
- ts.forEachChild(n, walk);
48
- }
49
- ts.forEachChild(node, walk);
69
+ walkOxc(root, (n) => {
70
+ if (n.type === "Identifier") ids.add(n.name);
71
+ return n === root || !LAZY_SCOPE_TYPES.has(n.type);
72
+ });
50
73
  return ids;
51
74
  }
52
- /** Extract the names defined by a top-level statement. */
53
- function getDefinedNames(stmt) {
54
- if (ts.isVariableStatement(stmt)) {
75
+ /** Extract the names defined by a top-level declaration. */
76
+ function getDefinedNames(decl) {
77
+ if (decl.type === "VariableDeclaration") {
55
78
  const names = [];
56
- for (const decl of stmt.declarationList.declarations) collectBindingNames(decl.name, names);
79
+ for (const d of decl.declarations) collectBindingNames(d.id, names);
57
80
  return names;
58
81
  }
59
- if (ts.isFunctionDeclaration(stmt) && stmt.name) return [stmt.name.text];
60
- if (ts.isClassDeclaration(stmt) && stmt.name) return [stmt.name.text];
82
+ if ((decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") && decl.id) return [decl.id.name];
61
83
  return [];
62
84
  }
63
- /** Recursively collect all bound identifiers from a binding name/pattern. */
64
- function collectBindingNames(name, out) {
65
- if (ts.isIdentifier(name)) out.push(name.text);
66
- else if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) {
67
- for (const el of name.elements) if (!ts.isOmittedExpression(el)) collectBindingNames(el.name, out);
85
+ /** Recursively collect all bound identifiers from a binding pattern. */
86
+ function collectBindingNames(pattern, out) {
87
+ if (!pattern) return;
88
+ switch (pattern.type) {
89
+ case "Identifier":
90
+ out.push(pattern.name);
91
+ break;
92
+ case "ObjectPattern":
93
+ for (const prop of pattern.properties) collectBindingNames(prop.type === "RestElement" ? prop.argument : prop.value, out);
94
+ break;
95
+ case "ArrayPattern":
96
+ for (const el of pattern.elements) collectBindingNames(el, out);
97
+ break;
98
+ case "RestElement":
99
+ collectBindingNames(pattern.argument, out);
100
+ break;
101
+ case "AssignmentPattern": collectBindingNames(pattern.left, out);
68
102
  }
69
103
  }
70
104
  function compile(sourceCode, fileName, optionsOrRegistry) {
@@ -76,8 +110,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
76
110
  const isPartial = opts.compilationMode === "partial";
77
111
  const startTimeMs = debugCompile.enabled ? performance.now() : 0;
78
112
  debugCompile("compile %s (mode=%s, registry=%d entries)", fileName, isPartial ? "partial" : "full", registry?.size ?? 0);
79
- const origSourceFile = ts.createSourceFile(fileName, sourceCode, ts.ScriptTarget.Latest, false);
80
- const oxcProgram = opts.oxcProgram ?? parseSync(fileName, sourceCode).program;
113
+ const oxcProgram = opts.oxcProgram ?? parseOxc(fileName, sourceCode).program;
81
114
  const oxcClassMap = /* @__PURE__ */ new Map();
82
115
  for (const stmt of oxcProgram.body) {
83
116
  const decl = stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration" ? stmt.declaration : stmt;
@@ -92,18 +125,18 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
92
125
  const typeOnlyImports = detectTypeOnlyImportNames(sourceCode, oxcProgram);
93
126
  const importSpecifierByName = /* @__PURE__ */ new Map();
94
127
  const importedNames = /* @__PURE__ */ new Set();
95
- for (const stmt of origSourceFile.statements) {
96
- if (!ts.isImportDeclaration(stmt) || !stmt.importClause?.namedBindings || !ts.isNamedImports(stmt.importClause.namedBindings)) continue;
97
- const moduleSpecifier = stmt.moduleSpecifier.text;
98
- const isDeclarationTypeOnly = stmt.importClause.isTypeOnly;
99
- for (const element of stmt.importClause.namedBindings.elements) {
100
- const localName = element.name.text;
128
+ for (const stmt of oxcProgram.body) {
129
+ if (stmt.type !== "ImportDeclaration") continue;
130
+ const moduleSpecifier = stmt.source.value;
131
+ const isDeclarationTypeOnly = stmt.importKind === "type";
132
+ for (const element of stmt.specifiers) {
133
+ if (element.type !== "ImportSpecifier") continue;
134
+ const localName = element.local.name;
101
135
  importedNames.add(localName);
102
136
  importSpecifierByName.set(localName, moduleSpecifier);
103
- if (isDeclarationTypeOnly || element.isTypeOnly) typeOnlyImports.add(localName);
137
+ if (isDeclarationTypeOnly || element.importKind === "type") typeOnlyImports.add(localName);
104
138
  }
105
139
  }
106
- const sourceFile = injectAngularImport(origSourceFile);
107
140
  const localSelectors = /* @__PURE__ */ new Map();
108
141
  if (!registry) for (const [clsName, oxcNode] of oxcClassMap) {
109
142
  const decs = oxcNode.decorators || [];
@@ -113,20 +146,16 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
113
146
  }
114
147
  }
115
148
  const bindingParser = isPartial ? void 0 : makeBindingParser();
116
- setEmitterSourceFile(origSourceFile);
117
149
  setEmitterSourceCode(sourceCode);
118
150
  const classResults = [];
151
+ const topLevelClasses = new Set(oxcProgram.body.map((stmt) => toTopLevelStatement(stmt).decl));
119
152
  const syntheticImports = /* @__PURE__ */ new Map();
120
- for (const node of findAllClasses(origSourceFile)) {
121
- const decorators = ts.getDecorators(node);
153
+ for (const node of findAllClasses(oxcProgram)) {
154
+ const decorators = node.decorators;
122
155
  if (!decorators || decorators.length === 0) continue;
123
- const className = node.name?.text;
156
+ const className = node.id?.name;
124
157
  if (!className) continue;
125
- const angularDecorators = decorators.filter((dec) => {
126
- if (!ts.isCallExpression(dec.expression)) return false;
127
- const name = dec.expression.expression.getText(origSourceFile);
128
- return ANGULAR_DECORATORS.has(name);
129
- });
158
+ const angularDecorators = decorators.filter((dec) => ANGULAR_DECORATORS.has(decoratorCallName(dec, sourceCode) ?? ""));
130
159
  if (angularDecorators.length === 0) continue;
131
160
  const ivyCode = [];
132
161
  let targetType = FactoryTarget.Injectable;
@@ -135,31 +164,13 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
135
164
  value: new o.WrappedNodeExpr(className),
136
165
  type: new o.WrappedNodeExpr(className)
137
166
  };
138
- const extendsClause = node.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
139
- const usesInheritance = !!extendsClause && extendsClause.types.length > 0;
140
- const oxcNode = oxcClassMap.get(className);
167
+ const usesInheritance = !!node.superClass;
141
168
  let classCompileError = null;
142
169
  angularDecorators.forEach((dec) => {
143
- const decoratorName = dec.expression.expression.getText(origSourceFile);
144
- const oxcDec = oxcNode?.decorators?.find((d) => {
145
- const expr = d.expression;
146
- return expr?.type === "CallExpression" && expr.callee?.name === decoratorName;
147
- });
148
- const meta = extractMetadata(oxcDec, sourceCode, stringConsts);
149
- const sigs = oxcNode ? detectSignals(oxcNode, sourceCode) : {
150
- inputs: {},
151
- outputs: {},
152
- viewQueries: [],
153
- contentQueries: []
154
- };
155
- const fields = oxcNode ? detectFieldDecorators(oxcNode, sourceCode) : {
156
- inputs: {},
157
- outputs: {},
158
- viewQueries: [],
159
- contentQueries: [],
160
- hostProperties: {},
161
- hostListeners: {}
162
- };
170
+ const decoratorName = decoratorCallName(dec, sourceCode);
171
+ const meta = extractMetadata(dec, sourceCode, stringConsts);
172
+ const sigs = detectSignals(node, sourceCode);
173
+ const fields = detectFieldDecorators(node, sourceCode);
163
174
  const hostBindings = parseHostBindings(meta.hostRaw || {});
164
175
  const hostMetadata = {
165
176
  attributes: hostBindings.attributes,
@@ -423,7 +434,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
423
434
  usesInheritance,
424
435
  defer: {
425
436
  mode: 0,
426
- blocks: buildDeferDependencyMap(parsedTemplate, sourceFile, registry, localSelectors).blocks
437
+ blocks: buildDeferDependencyMap(parsedTemplate, oxcProgram, registry, localSelectors).blocks
427
438
  },
428
439
  declarationListEmitMode: 1,
429
440
  i18nUseExternalIds: opts.i18nUseExternalIds ?? false,
@@ -619,7 +630,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
619
630
  }
620
631
  });
621
632
  if (classCompileError) throw classCompileError;
622
- const deps = oxcNode ? extractConstructorDeps(oxcNode, sourceCode, typeOnlyImports) : [];
633
+ const deps = extractConstructorDeps(node, sourceCode, typeOnlyImports);
623
634
  if (deps === null) {
624
635
  const baseVar = `ɵ${className}_BaseFactory`;
625
636
  ivyCode.unshift(`static ɵfac = /*@__PURE__*/ (() => { let ${baseVar}; return function ${className}_Factory(__ngFactoryType__) { return (${baseVar} || (${baseVar} = i0.ɵɵgetInheritedFactory(${className})))(__ngFactoryType__ || ${className}); }; })()`);
@@ -640,36 +651,39 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
640
651
  ivyCode.unshift(`static ɵfac = /*@__PURE__*/ ${emitAngularExpr(fac.expression)}`);
641
652
  }
642
653
  }
654
+ const ctorParameters = buildCtorParameters(node, sourceCode, typeOnlyImports);
655
+ const propDecorators = buildPropDecorators(node, sourceCode, "i0.");
656
+ const scopedMetadata = [];
643
657
  angularDecorators.forEach((dec) => {
644
- const call = dec.expression;
645
- const decName = call.expression.getText(origSourceFile);
646
- const decArgsNode = call.arguments[0];
658
+ const decName = decoratorCallName(dec, sourceCode);
659
+ const decArgsNode = dec.expression.arguments[0];
660
+ const textOf = (n) => sourceCode.slice(n.start, n.end);
647
661
  const resources = resolvedResources.get(dec);
648
662
  let metadataArgsExpr = null;
649
663
  if (decArgsNode) {
650
- if (resources && ts.isObjectLiteralExpression(decArgsNode)) {
664
+ if (resources && decArgsNode.type === "ObjectExpression") {
651
665
  const rewrittenProps = [];
652
666
  let needsTransform = false;
653
667
  for (const prop of decArgsNode.properties) {
654
- if (!ts.isPropertyAssignment(prop)) {
655
- rewrittenProps.push(prop.getText(origSourceFile));
668
+ if (prop.type !== "Property" || prop.shorthand || prop.method || prop.kind !== "init") {
669
+ rewrittenProps.push(textOf(prop));
656
670
  continue;
657
671
  }
658
- const propName = prop.name?.getText(origSourceFile);
672
+ const propName = textOf(prop.key);
659
673
  if (propName === "templateUrl" && resources.template) {
660
674
  rewrittenProps.push(`template: ${JSON.stringify(resources.template)}`);
661
675
  needsTransform = true;
662
676
  } else if ((propName === "styleUrl" || propName === "styleUrls") && resources.styles?.length) {
663
677
  rewrittenProps.push(`styles: [${resources.styles.map((s) => JSON.stringify(s)).join(", ")}]`);
664
678
  needsTransform = true;
665
- } else rewrittenProps.push(prop.getText(origSourceFile));
679
+ } else rewrittenProps.push(textOf(prop));
666
680
  }
667
- metadataArgsExpr = needsTransform ? `{${rewrittenProps.join(", ")}}` : decArgsNode.getText(origSourceFile);
668
- } else metadataArgsExpr = decArgsNode.getText(origSourceFile);
681
+ metadataArgsExpr = needsTransform ? `{${rewrittenProps.join(", ")}}` : textOf(decArgsNode);
682
+ } else metadataArgsExpr = textOf(decArgsNode);
669
683
  }
670
684
  try {
671
685
  const classMetaInput = {
672
- type: new o.WrappedNodeExpr(ts.factory.createIdentifier(className)),
686
+ type: new o.WrappedNodeExpr(className),
673
687
  decorators: new o.LiteralArrayExpr([new o.LiteralMapExpr([{
674
688
  key: "type",
675
689
  value: new o.WrappedNodeExpr(decName),
@@ -679,29 +693,24 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
679
693
  value: new o.LiteralArrayExpr([new o.WrappedNodeExpr(metadataArgsExpr)]),
680
694
  quoted: false
681
695
  }] : []])]),
682
- ctorParameters: null,
683
- propDecorators: null
696
+ ctorParameters: ctorParameters ? new o.WrappedNodeExpr(`() => [${ctorParameters}]`) : null,
697
+ propDecorators: propDecorators ? new o.WrappedNodeExpr(propDecorators) : null
684
698
  };
685
699
  const classMetadataExpr = isPartial ? compileDeclareClassMetadata(classMetaInput) : compileClassMetadata(classMetaInput);
686
- constantPool.statements.push(new o.ExpressionStatement(classMetadataExpr));
700
+ const metadataStmt = new o.ExpressionStatement(classMetadataExpr);
701
+ if (topLevelClasses.has(node)) constantPool.statements.push(metadataStmt);
702
+ else scopedMetadata.push(metadataStmt);
687
703
  } catch (e) {
688
704
  if (debugCompile.enabled) debugCompile("compileClassMetadata failed for %s in %s: %s", className, fileName, e?.message);
689
705
  }
690
706
  });
691
707
  const memberDecorators = [];
692
- for (const member of node.members) {
693
- const mDecorators = ts.getDecorators(member);
694
- if (!mDecorators) continue;
695
- for (const dec of mDecorators) {
696
- if (!ts.isCallExpression(dec.expression)) continue;
697
- const decName = dec.expression.expression.getText(origSourceFile);
698
- if (FIELD_DECORATORS.has(decName)) memberDecorators.push(dec);
699
- }
700
- }
708
+ for (const member of node.body.body) for (const dec of member.decorators ?? []) if (FIELD_DECORATORS.has(decoratorCallName(dec, sourceCode) ?? "")) memberDecorators.push(dec);
701
709
  classResults.push({
702
710
  ivyCode,
703
711
  decorators: [...angularDecorators, ...memberDecorators],
704
- classEnd: node.getEnd()
712
+ classEnd: node.end,
713
+ scopedMetadata
705
714
  });
706
715
  }
707
716
  const ms = new MagicString(sourceCode, { filename: fileName });
@@ -711,45 +720,40 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
711
720
  importedNames.add(name);
712
721
  }
713
722
  if (classResults.length > 0) {
723
+ const statements = oxcProgram.body.map(toTopLevelStatement);
714
724
  let firstClassPos = Infinity;
715
725
  const nonHoistableNames = /* @__PURE__ */ new Set();
716
- for (const stmt of origSourceFile.statements) if (ts.isClassDeclaration(stmt)) {
717
- firstClassPos = stmt.getStart(origSourceFile);
718
- if (stmt.name) nonHoistableNames.add(stmt.name.text);
726
+ for (const { decl, start } of statements) if (decl.type === "ClassDeclaration") {
727
+ firstClassPos = start;
728
+ if (decl.id) nonHoistableNames.add(decl.id.name);
719
729
  break;
720
730
  }
721
- for (const stmt of origSourceFile.statements) {
722
- if (stmt.getStart(origSourceFile) <= firstClassPos) continue;
723
- if (ts.isClassDeclaration(stmt) && stmt.name) nonHoistableNames.add(stmt.name.text);
724
- if (ts.isEnumDeclaration(stmt)) nonHoistableNames.add(stmt.name.text);
725
- if (ts.isVariableStatement(stmt) && hasExportModifier(stmt)) for (const decl of stmt.declarationList.declarations) {
726
- const names = [];
727
- collectBindingNames(decl.name, names);
728
- for (const n of names) nonHoistableNames.add(n);
729
- }
730
- if (ts.isFunctionDeclaration(stmt) && hasExportModifier(stmt) && stmt.name) nonHoistableNames.add(stmt.name.text);
731
+ for (const { decl, exported, start } of statements) {
732
+ if (start <= firstClassPos) continue;
733
+ if (decl.type === "ClassDeclaration" || decl.type === "TSEnumDeclaration") {
734
+ if (decl.id) nonHoistableNames.add(decl.id.name);
735
+ } else if (exported && (decl.type === "VariableDeclaration" || decl.type === "FunctionDeclaration")) for (const n of getDefinedNames(decl)) nonHoistableNames.add(n);
731
736
  }
732
- for (const stmt of origSourceFile.statements) {
733
- const stmtStart = stmt.getStart(origSourceFile);
734
- if (stmtStart <= firstClassPos) continue;
735
- if (!(ts.isVariableStatement(stmt) && !hasExportModifier(stmt) || ts.isFunctionDeclaration(stmt) && !hasExportModifier(stmt))) continue;
736
- const referencedIds = collectIdentifiers(stmt);
737
+ for (const { decl, exported, start, end } of statements) {
738
+ if (start <= firstClassPos) continue;
739
+ if (!(!exported && (decl.type === "VariableDeclaration" || decl.type === "FunctionDeclaration"))) continue;
740
+ const referencedIds = collectIdentifiers(decl);
737
741
  let referencesNonHoistable = false;
738
742
  for (const id of referencedIds) if (nonHoistableNames.has(id)) {
739
743
  referencesNonHoistable = true;
740
744
  break;
741
745
  }
742
- if (referencesNonHoistable) for (const name of getDefinedNames(stmt)) nonHoistableNames.add(name);
746
+ if (referencesNonHoistable) for (const name of getDefinedNames(decl)) nonHoistableNames.add(name);
743
747
  else {
744
- ms.appendLeft(stmt.getEnd(), "\n");
745
- ms.move(stmtStart, stmt.getEnd(), firstClassPos);
748
+ ms.appendLeft(end, "\n");
749
+ ms.move(start, end, firstClassPos);
746
750
  }
747
751
  }
748
752
  }
749
753
  for (const cr of classResults) {
750
754
  for (const dec of cr.decorators) {
751
- const start = dec.getStart(origSourceFile);
752
- let trimEnd = dec.getEnd();
755
+ const start = dec.start;
756
+ let trimEnd = dec.end;
753
757
  while (trimEnd < sourceCode.length && (sourceCode[trimEnd] === " " || sourceCode[trimEnd] === "\n" || sourceCode[trimEnd] === "\r")) trimEnd++;
754
758
  ms.remove(start, trimEnd);
755
759
  }
@@ -757,6 +761,7 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
757
761
  const memberCode = cr.ivyCode.map((c) => " " + c + ";").join("\n");
758
762
  ms.appendLeft(cr.classEnd - 1, "\n" + memberCode + "\n");
759
763
  }
764
+ for (const stmt of cr.scopedMetadata) ms.appendLeft(cr.classEnd, `\n/*@__PURE__*/ ${emitAngularStmt(stmt)}`);
760
765
  }
761
766
  const helpers = [];
762
767
  const sideEffects = [];
@@ -765,25 +770,26 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
765
770
  if (s instanceof o.ExpressionStatement && s.expr instanceof o.InvokeFunctionExpr) sideEffects.push(`/*@__PURE__*/ ${code}`);
766
771
  else helpers.push(code);
767
772
  }
773
+ if (sideEffects.length > 0) ms.append("\n\n" + sideEffects.join("\n"));
774
+ if (!useDefineForClassFields) lowerClassFields(ms, sourceCode, oxcProgram);
775
+ const helperCode = helpers.join("\n");
776
+ const willElide = detectTypeOnlyImportNames(ms.toString() + "\n" + helperCode);
768
777
  if (helpers.length > 0) {
769
- const willElide = detectTypeOnlyImportNames(ms.toString());
770
778
  let insertPos = 0;
771
- for (const stmt of origSourceFile.statements) if (ts.isImportDeclaration(stmt)) {
772
- if (willElide.size > 0 && stmt.importClause) {
773
- const clause = stmt.importClause;
774
- const namedBindings = clause.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements : void 0;
775
- const defaultName = clause.name;
776
- if ((!defaultName || willElide.has(defaultName.text)) && (!namedBindings || namedBindings.every((el) => el.isTypeOnly || willElide.has(el.name.text)))) continue;
777
- }
778
- insertPos = stmt.getEnd();
779
- } else if (ts.isVariableStatement(stmt) && !stmt.getText(origSourceFile).includes("class")) insertPos = stmt.getEnd();
780
- else if (!ts.isExportAssignment(stmt)) break;
781
- if (insertPos === 0) ms.appendLeft(0, helpers.join("\n") + "\n");
782
- else ms.appendRight(insertPos, "\n" + helpers.join("\n") + "\n");
779
+ for (const stmt of oxcProgram.body) {
780
+ const { decl } = toTopLevelStatement(stmt);
781
+ if (stmt.type === "ImportDeclaration") {
782
+ if (willElide.size > 0 && stmt.specifiers.length > 0) {
783
+ if (stmt.specifiers.every((spec) => spec.type === "ImportNamespaceSpecifier" || spec.importKind === "type" || willElide.has(spec.local.name))) continue;
784
+ }
785
+ insertPos = stmt.end;
786
+ } else if (decl.type === "VariableDeclaration" && !sourceCode.slice(stmt.start, stmt.end).includes("class")) insertPos = stmt.end;
787
+ else if (stmt.type !== "TSExportAssignment" && !(stmt.type === "ExportDefaultDeclaration" && decl.type !== "ClassDeclaration" && decl.type !== "FunctionDeclaration")) break;
788
+ }
789
+ if (insertPos === 0) ms.appendLeft(0, helperCode + "\n");
790
+ else ms.appendRight(insertPos, "\n" + helperCode + "\n");
783
791
  }
784
- if (sideEffects.length > 0) ms.append("\n\n" + sideEffects.join("\n"));
785
- if (!useDefineForClassFields) lowerClassFields(ms, sourceCode, oxcProgram);
786
- elideTypeOnlyImportsMagicString(ms, oxcProgram);
792
+ elideTypeOnlyImportsMagicString(ms, oxcProgram, willElide);
787
793
  const map = ms.generateMap({
788
794
  source: fileName,
789
795
  file: fileName + ".js",
@@ -797,9 +803,6 @@ function compile(sourceCode, fileName, optionsOrRegistry) {
797
803
  resourceDependencies
798
804
  };
799
805
  }
800
- function injectAngularImport(sf) {
801
- return ts.factory.updateSourceFile(sf, [ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamespaceImport(ts.factory.createIdentifier("i0"))), ts.factory.createStringLiteral("@angular/core")), ...sf.statements]);
802
- }
803
806
  //#endregion
804
807
  export { compile };
805
808