@openrewrite/recipes-angular 1.33.0 → 1.34.0

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 (50) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +35 -5
  4. package/dist/index.js.map +1 -1
  5. package/dist/libraries/components/lst.d.ts +7 -0
  6. package/dist/libraries/components/lst.d.ts.map +1 -1
  7. package/dist/libraries/components/lst.js +11 -0
  8. package/dist/libraries/components/lst.js.map +1 -1
  9. package/dist/libraries/components/package-version.d.ts +7 -2
  10. package/dist/libraries/components/package-version.d.ts.map +1 -1
  11. package/dist/libraries/components/package-version.js +5 -3
  12. package/dist/libraries/components/package-version.js.map +1 -1
  13. package/dist/libraries/components/symbols.d.ts +3 -0
  14. package/dist/libraries/components/symbols.d.ts.map +1 -1
  15. package/dist/libraries/components/symbols.js +8 -0
  16. package/dist/libraries/components/symbols.js.map +1 -1
  17. package/dist/libraries/ng-inline-svg/migrate-ng-inline-svg.d.ts +127 -0
  18. package/dist/libraries/ng-inline-svg/migrate-ng-inline-svg.d.ts.map +1 -0
  19. package/dist/libraries/ng-inline-svg/migrate-ng-inline-svg.js +708 -0
  20. package/dist/libraries/ng-inline-svg/migrate-ng-inline-svg.js.map +1 -0
  21. package/dist/libraries/ng2-cookies/migrate-ng2-cookies.d.ts +60 -0
  22. package/dist/libraries/ng2-cookies/migrate-ng2-cookies.d.ts.map +1 -0
  23. package/dist/libraries/ng2-cookies/migrate-ng2-cookies.js +472 -0
  24. package/dist/libraries/ng2-cookies/migrate-ng2-cookies.js.map +1 -0
  25. package/dist/migration/package-major.d.ts +43 -0
  26. package/dist/migration/package-major.d.ts.map +1 -0
  27. package/dist/migration/package-major.js +100 -0
  28. package/dist/migration/package-major.js.map +1 -0
  29. package/dist/migration/replace-platform-browser-dynamic.d.ts +32 -0
  30. package/dist/migration/replace-platform-browser-dynamic.d.ts.map +1 -0
  31. package/dist/migration/replace-platform-browser-dynamic.js +212 -0
  32. package/dist/migration/replace-platform-browser-dynamic.js.map +1 -0
  33. package/dist/migration/upgrade-to-angular-20.d.ts.map +1 -1
  34. package/dist/migration/upgrade-to-angular-20.js +4 -1
  35. package/dist/migration/upgrade-to-angular-20.js.map +1 -1
  36. package/dist/migration/use-angular-build-builders.d.ts +51 -0
  37. package/dist/migration/use-angular-build-builders.d.ts.map +1 -0
  38. package/dist/migration/use-angular-build-builders.js +280 -0
  39. package/dist/migration/use-angular-build-builders.js.map +1 -0
  40. package/package.json +2 -2
  41. package/src/index.ts +19 -0
  42. package/src/libraries/components/lst.ts +11 -0
  43. package/src/libraries/components/package-version.ts +7 -7
  44. package/src/libraries/components/symbols.ts +7 -0
  45. package/src/libraries/ng-inline-svg/migrate-ng-inline-svg.ts +613 -0
  46. package/src/libraries/ng2-cookies/migrate-ng2-cookies.ts +425 -0
  47. package/src/migration/package-major.ts +93 -0
  48. package/src/migration/replace-platform-browser-dynamic.ts +197 -0
  49. package/src/migration/upgrade-to-angular-20.ts +4 -1
  50. package/src/migration/use-angular-build-builders.ts +285 -0
@@ -0,0 +1,197 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+
7
+ import {ExecutionContext, foundSearchResult, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {AddImport, ChangeImport, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
9
+ import {J} from "@openrewrite/rewrite/java";
10
+ import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
11
+ import {posix} from "path";
12
+ import {hasSearchResult, inSequence} from "../libraries/components/lst";
13
+ import {moduleOf} from "../libraries/components/symbols";
14
+ import {directoryOf, majorFor} from "../libraries/components/package-version";
15
+
16
+ const DYNAMIC = '@angular/platform-browser-dynamic';
17
+ const DYNAMIC_TESTING = '@angular/platform-browser-dynamic/testing';
18
+
19
+ /** The members of `@angular/platform-browser-dynamic` that have a replacement of the same shape elsewhere. */
20
+ const MOVES: {oldModule: string, oldMember: string, newModule: string, newMember: string}[] = [
21
+ {oldModule: DYNAMIC, oldMember: 'platformBrowserDynamic', newModule: '@angular/platform-browser', newMember: 'platformBrowser'},
22
+ // The package is versioned in lockstep with `@angular/core`, so the two `VERSION`s are the same version.
23
+ {oldModule: DYNAMIC, oldMember: 'VERSION', newModule: '@angular/core', newMember: 'VERSION'},
24
+ {oldModule: DYNAMIC_TESTING, oldMember: 'platformBrowserDynamicTesting', newModule: '@angular/platform-browser/testing', newMember: 'platformBrowserTesting'},
25
+ {oldModule: DYNAMIC_TESTING, oldMember: 'BrowserDynamicTestingModule', newModule: '@angular/platform-browser/testing', newMember: 'BrowserTestingModule'},
26
+ ];
27
+
28
+ /** The files that say an Angular CLI or Nx builder builds the projects beneath them. */
29
+ const WORKSPACE_FILES = new Set(['angular.json', '.angular-cli.json', 'project.json', 'workspace.json']);
30
+
31
+ const LEFTOVER = "`@angular/platform-browser-dynamic` is deprecated since Angular 20. This import has no replacement of the same shape (`JitCompilerFactory` is not needed under Ivy, " +
32
+ "and a bare or namespace import is left for a hand migration): use `@angular/platform-browser`, and import " +
33
+ "`@angular/compiler` where the application compiles just in time outside the Angular CLI.";
34
+
35
+ const RESETS = "This file resets the test environment and sets it up again, which needs the platform it creates to " +
36
+ "be the one the environment it replaces was set up with, here the `platformBrowserDynamicTesting` of a setup that " +
37
+ "no source of this project holds, such as the one `jest-preset-angular` runs. Angular throws NG0400 for a " +
38
+ "different one, so this import was left as it is: move it to `@angular/platform-browser/testing` together with " +
39
+ "that setup.";
40
+
41
+ const COMPILER = '@angular/compiler';
42
+
43
+ /** Whether a source file calls `resetTestEnvironment()` and `initTestEnvironment()`. */
44
+ async function testEnvironmentCalls(cu: JS.CompilationUnit, p: ExecutionContext): Promise<{resets: boolean, inits: boolean}> {
45
+ const calls = {resets: false, inits: false};
46
+ await new class extends JavaScriptVisitor<ExecutionContext> {
47
+ protected async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
48
+ if (method.name.simpleName === 'resetTestEnvironment') calls.resets = true;
49
+ if (method.name.simpleName === 'initTestEnvironment') calls.inits = true;
50
+ return super.visitMethodInvocation(method, ctx);
51
+ }
52
+ }().visit(cu, p);
53
+ return calls;
54
+ }
55
+
56
+ /**
57
+ * The directories of the workspace files, and for each project, by the directory of its `package.json`, whether one
58
+ * of its sources sets the test environment up without resetting it, as a Karma `test.ts` or a Jest setup file does.
59
+ */
60
+ interface Projects {
61
+ workspaces: Set<string>;
62
+ packages: Map<string, string>;
63
+ sharedSetup: Set<string>;
64
+ }
65
+
66
+ const isDynamicModule = (module: unknown) => module === DYNAMIC || module === DYNAMIC_TESTING;
67
+
68
+ /** The names a `{...}` import clause takes from its module, as the module exports them. */
69
+ function namedMembers(imp: JS.Import): string[] | undefined {
70
+ const named = imp.importClause?.namedBindings;
71
+ if (named?.kind !== JS.Kind.NamedImports) return undefined;
72
+ return (named as JS.NamedImports).elements.elements.map(({element}) => {
73
+ const imported = (element as JS.ImportSpecifier).specifier;
74
+ const name: J = imported.kind === JS.Kind.Alias ? (imported as JS.Alias).propertyName.element : imported;
75
+ return name.kind === J.Kind.Identifier ? (name as J.Identifier).simpleName :
76
+ name.kind === J.Kind.Literal ? String((name as J.Literal).value) : '';
77
+ });
78
+ }
79
+
80
+ function dynamicImports(cu: JS.CompilationUnit): JS.Import[] {
81
+ return cu.statements
82
+ .map(({element}) => element)
83
+ .filter((s): s is JS.Import => s.kind === JS.Kind.Import && isDynamicModule(moduleOf(s as JS.Import)));
84
+ }
85
+
86
+ function importsModule(cu: JS.CompilationUnit, module: string): boolean {
87
+ return cu.statements.some(({element}) => element.kind === JS.Kind.Import && moduleOf(element as JS.Import) === module);
88
+ }
89
+
90
+ /**
91
+ * Moves the `@angular/compiler` import that was just added to the top of the file, where the Angular CLI loads it too
92
+ * (as the first polyfill), so that it is in place before any other module evaluates. The import takes the place of
93
+ * the first statement, comments such as a license header included, and that statement the line the import had.
94
+ */
95
+ function loadCompilerFirst(cu: JS.CompilationUnit): JS.CompilationUnit {
96
+ const index = cu.statements.findIndex(({element}) => element.kind === JS.Kind.Import && moduleOf(element as JS.Import) === COMPILER);
97
+ if (index <= 0) return cu;
98
+ const statements = [...cu.statements];
99
+ const [compiler] = statements.splice(index, 1);
100
+ const first = statements[0];
101
+ statements[0] = {...first, element: {...first.element, prefix: compiler.element.prefix}};
102
+ statements.unshift({...compiler, element: {...compiler.element, prefix: first.element.prefix}});
103
+ return {...cu, statements};
104
+ }
105
+
106
+ const isBeneath = (path: string, dir: string) => !posix.relative(dir, path).startsWith('..');
107
+
108
+ /**
109
+ * Moves code off `@angular/platform-browser-dynamic`, which Angular 20 deprecated in favor of `@angular/platform-browser`.
110
+ *
111
+ * The only thing the dynamic platform adds to `platformBrowser` is loading `@angular/compiler`, for applications
112
+ * that compile just in time. The Angular CLI's builders add that import themselves to every JIT build (an `aot: false`
113
+ * build and the Karma and unit-test builders), and since Angular 20 `@angular/core/testing` imports it for `TestBed`.
114
+ * So in a project that `angular.json` (or an Nx `project.json`) builds, `platformBrowser` needs nothing more, and an
115
+ * ahead-of-time build stops shipping the compiler. A source file that no such workspace builds imports
116
+ * `@angular/compiler` itself, which is what the dynamic platform did for it before.
117
+ *
118
+ * @see https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/src/platform-browser-dynamic.ts
119
+ */
120
+ export class ReplacePlatformBrowserDynamic extends ScanningRecipe<Projects> {
121
+ readonly name = "org.openrewrite.angular.migration.replace-platform-browser-dynamic";
122
+ readonly displayName: string = "Replace `@angular/platform-browser-dynamic` with `@angular/platform-browser`";
123
+ readonly description: string = "Angular 20 deprecated `@angular/platform-browser-dynamic`. Replaces `platformBrowserDynamic` " +
124
+ "with `platformBrowser`, `platformBrowserDynamicTesting` and `BrowserDynamicTestingModule` with " +
125
+ "`platformBrowserTesting` and `BrowserTestingModule` from `@angular/platform-browser/testing`, and its `VERSION` " +
126
+ "with the one of `@angular/core`. Outside an Angular CLI or Nx workspace, where no builder adds the JIT " +
127
+ "compiler, the bootstrap file imports `@angular/compiler` as the dynamic platform did. `JitCompilerFactory` " +
128
+ "and bare or namespace imports of the package are flagged for a hand migration. So are the testing imports of a " +
129
+ "file that resets the test environment in a project where no source sets it up otherwise, as when " +
130
+ "`jest-preset-angular` does, since the file would set it up again on a different platform than that setup's.";
131
+
132
+ initialValue(_ctx: ExecutionContext): Projects {
133
+ return {workspaces: new Set(), packages: new Map(), sharedSetup: new Set()};
134
+ }
135
+
136
+ async scanner(projects: Projects): Promise<TreeVisitor<any, ExecutionContext>> {
137
+ const json = new class extends JsonVisitor<ExecutionContext> {
138
+ protected async visitDocument(doc: Json.Document, _p: ExecutionContext): Promise<Json | undefined> {
139
+ const name = posix.basename(doc.sourcePath);
140
+ if (WORKSPACE_FILES.has(name)) projects.workspaces.add(posix.dirname(posix.normalize(doc.sourcePath)));
141
+ if (name === 'package.json') projects.packages.set(directoryOf(doc.sourcePath), directoryOf(doc.sourcePath));
142
+ return doc;
143
+ }
144
+ }();
145
+ const sources = new class extends JavaScriptVisitor<ExecutionContext> {
146
+ protected async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
147
+ const calls = await testEnvironmentCalls(cu, p);
148
+ if (calls.inits && !calls.resets) projects.sharedSetup.add(cu.sourcePath);
149
+ return cu;
150
+ }
151
+ }();
152
+ return inSequence(json, sources);
153
+ }
154
+
155
+ async editorWithData(projects: Projects): Promise<TreeVisitor<any, ExecutionContext>> {
156
+ const workspaces = projects.workspaces;
157
+ const projectOf = (path: string) => majorFor(projects.packages, path) ?? '';
158
+ const shared = new Set([...projects.sharedSetup].map(projectOf));
159
+ const moves = await Promise.all(MOVES.map(async move => ({move, editor: await new ChangeImport(move).editor()})));
160
+ return new class extends JavaScriptVisitor<ExecutionContext> {
161
+ protected async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
162
+ const before = dynamicImports(cu);
163
+ if (before.length === 0) return cu;
164
+
165
+ const path = posix.normalize(cu.sourcePath);
166
+ const bootstraps = before.some(imp => moduleOf(imp) === DYNAMIC && namedMembers(imp)?.includes('platformBrowserDynamic'));
167
+ const needsCompiler = bootstraps && ![...workspaces].some(dir => isBeneath(path, dir));
168
+
169
+ const keepsTesting = before.some(imp => moduleOf(imp) === DYNAMIC_TESTING) &&
170
+ !shared.has(projectOf(cu.sourcePath)) && (await testEnvironmentCalls(cu, p)).resets;
171
+ let result: JS.CompilationUnit = cu;
172
+ for (const {move, editor} of moves) {
173
+ if (keepsTesting && move.oldModule === DYNAMIC_TESTING) continue;
174
+ result = (await editor.visit<JS.CompilationUnit>(result, p, this.cursor.parent)) ?? result;
175
+ }
176
+
177
+ // Whatever is still imported from the package has no replacement of the same shape, or is kept for
178
+ // the test environment this file sets up again.
179
+ const statements = result.statements.map(rp => {
180
+ const s = rp.element;
181
+ if (s.kind !== JS.Kind.Import) return rp;
182
+ const module = moduleOf(s as JS.Import);
183
+ const message = keepsTesting && module === DYNAMIC_TESTING ? RESETS : isDynamicModule(module) ? LEFTOVER : undefined;
184
+ return message && !hasSearchResult(s, message) ? {...rp, element: foundSearchResult(s, message)} : rp;
185
+ });
186
+ if (statements.some((rp, i) => rp !== result.statements[i])) result = {...result, statements};
187
+
188
+ if (needsCompiler && !importsModule(result, COMPILER)) {
189
+ const added = await new AddImport<ExecutionContext>({module: COMPILER, sideEffectOnly: true})
190
+ .visit<JS.CompilationUnit>(result, p, this.cursor.parent);
191
+ result = added ? loadCompilerFirst(added) : result;
192
+ }
193
+ return result;
194
+ }
195
+ }();
196
+ }
197
+ }
@@ -14,6 +14,7 @@ import {MoveDocumentImport} from "./move-document-to-core";
14
14
  import {RemoveStandaloneTrue} from "./remove-standalone-true";
15
15
  import {RemoveZoneJsPolyfill} from "./remove-zone-js-polyfill";
16
16
  import {ReplaceProvideServerRouting} from "./replace-provide-server-routing";
17
+ import {ReplacePlatformBrowserDynamic} from "./replace-platform-browser-dynamic";
17
18
  import {UpgradeToCdk20CodeChanges} from "../libraries/cdk/upgrade-to-cdk";
18
19
  import {UpgradeToMaterial20CodeChanges} from "../libraries/material/upgrade-to-material";
19
20
  import {beforeAngular} from "./angular-version";
@@ -54,6 +55,8 @@ export class UpgradeToAngular20CodeChanges extends Recipe {
54
55
  newModule: "@angular/ssr",
55
56
  }),
56
57
  new ReplaceProvideServerRouting(),
58
+ // `@angular/platform-browser-dynamic` is deprecated in favor of `@angular/platform-browser`
59
+ new ReplacePlatformBrowserDynamic(),
57
60
  new UpgradeToCdk20CodeChanges(),
58
61
  new UpgradeToMaterial20CodeChanges(),
59
62
  ]),
@@ -67,7 +70,7 @@ export class UpgradeToAngular20 extends Recipe {
67
70
  readonly description = "Migrates Angular 19.x applications to Angular 20. " +
68
71
  "This includes running the Angular 19 migration first, then updating Angular package versions, " +
69
72
  "renaming experimental APIs promoted to stable, moving `provideServerRendering` to `@angular/ssr` and " +
70
- "folding `provideServerRouting` into it, and upgrading TypeScript to 5.8.x." +
73
+ "folding `provideServerRouting` into it, moving off the deprecated `@angular/platform-browser-dynamic`, and upgrading TypeScript to 5.8.x." +
71
74
  " It includes the Angular Material code changes of version 20." +
72
75
  " Projects that use NgRx also get the NgRx 20 migration and its `@ngrx/*` versions.";
73
76
 
@@ -0,0 +1,285 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+
7
+ import {ExecutionContext, foundSearchResult, Recipe, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {
9
+ appendElement,
10
+ elementsOf,
11
+ emptyArray,
12
+ findMember,
13
+ isArray,
14
+ getMemberKeyName,
15
+ isLiteral,
16
+ isMember,
17
+ isObject,
18
+ Json,
19
+ jsonLiteral,
20
+ JsonVisitor,
21
+ removeMember,
22
+ setMember,
23
+ space,
24
+ updateMember
25
+ } from "@openrewrite/rewrite/json";
26
+ import {addDependencyByMajor, caretMajors, singleMajor} from "./package-major";
27
+ import {declaredVersion, directoryOf, majorFor, packageMajor} from "../libraries/components/package-version";
28
+ import {posix} from "path";
29
+ import {hasSearchResult} from "../libraries/components/lst";
30
+ import {mapObjectMember, mapObjectMembers, mapTargetOptions} from "./json-support";
31
+
32
+ const DEVKIT = '@angular-devkit/build-angular';
33
+ const DEVKIT_PREFIX = `${DEVKIT}:`;
34
+
35
+ /**
36
+ * The `@angular-devkit/build-angular` builders that `@angular/build` has a builder of the same name and options for,
37
+ * by the first `@angular/build` major that has it. `@angular/build` is released in step with Angular from 18 on.
38
+ */
39
+ const COUNTERPARTS: Record<string, number> = {
40
+ 'application': 18,
41
+ 'dev-server': 18,
42
+ 'extract-i18n': 18,
43
+ 'karma': 19,
44
+ 'ng-packagr': 19,
45
+ };
46
+
47
+ /** The first major of `@angular-devkit/build-angular` whose projects can move to `@angular/build`. */
48
+ const FIRST_MAJOR = 18;
49
+
50
+ /** The `@angular/build` that `UseAngularBuildBuilders` adds, by the major of `@angular-devkit/build-angular`. */
51
+ const ANGULAR_BUILD_VERSIONS = caretMajors(FIRST_MAJOR, 22);
52
+
53
+ const blocked = (builder: string) => `\`${builder}\` has no counterpart in \`@angular/build\`, so this workspace keeps ` +
54
+ `\`${DEVKIT}\`. Move it to the \`application\` builder first, as \`ng update @angular/cli --name use-application-builder\` ` +
55
+ "does for `browser` and `browser-esbuild`, and the other builders of the workspace then move to `@angular/build`.";
56
+ const BLOCKED_MARK = 'has no counterpart in `@angular/build`';
57
+ const UNDECLARED = "Every builder of this workspace has a counterpart in `@angular/build`, but its `package.json` does not " +
58
+ "declare `@angular/build`, and the recipe adds it only where the lock file, or a constraint within one major, shows " +
59
+ "which major of `" + DEVKIT + "` it resolves, so the builders stay on `" + DEVKIT + "`. npm may nest `@angular/build` " +
60
+ "under `" + DEVKIT + "`, and pnpm always does, where the Angular CLI does not find it. Declare `@angular/build` at the " +
61
+ "version of `" + DEVKIT + "`, as `ng update @angular/cli --name use-application-builder` does, and the builders then move.";
62
+ const UNDECLARED_MARK = 'does not declare `@angular/build`';
63
+
64
+ /**
65
+ * For each directory with a `package.json`, the major of `@angular-devkit/build-angular` and whether it declares
66
+ * `@angular/build`, or `UseAngularBuildBuilders` adds it there.
67
+ */
68
+ interface Workspaces {
69
+ majors: Map<string, number>;
70
+ declaring: Map<string, boolean>;
71
+ /** Whether the `package.json` declares `zone.js`. */
72
+ zone: Map<string, boolean>;
73
+ }
74
+
75
+ /** Whether `UseAngularBuildBuilders` adds `@angular/build` to a `package.json`, as its `addDependency` gates decide. */
76
+ function addsAngularBuild(doc: Json.Document): boolean {
77
+ if (declaredVersion(doc, DEVKIT) === undefined) return false;
78
+ const major = singleMajor(doc, DEVKIT);
79
+ return ANGULAR_BUILD_VERSIONS.some(v => v.major === major);
80
+ }
81
+
82
+ /** Applies `fn` to every target of every project, under `architect` or its alias `targets`. */
83
+ function mapTargets(root: Json.Object, fn: (target: Json.Object) => Json.Object): Json.Object {
84
+ return mapObjectMember(root, 'projects', projects =>
85
+ mapObjectMembers(projects, project => {
86
+ const architect = mapObjectMember(project, 'architect', targets => mapObjectMembers(targets, fn));
87
+ return mapObjectMember(architect, 'targets', targets => mapObjectMembers(targets, fn));
88
+ }));
89
+ }
90
+
91
+ /** The `builder` of a target, if it is a string. */
92
+ function builderOf(target: Json.Object): string | undefined {
93
+ const value = findMember(target, 'builder')?.value;
94
+ return value && isLiteral(value) && typeof value.value === 'string' ? value.value : undefined;
95
+ }
96
+
97
+ /** The builders of the workspace that `@angular/build` at `major` has no counterpart for. */
98
+ function blockers(root: Json.Object, major: number): Set<string> {
99
+ const found = new Set<string>();
100
+ mapTargets(root, target => {
101
+ const builder = builderOf(target);
102
+ if (builder?.startsWith(DEVKIT_PREFIX)) {
103
+ const since = COUNTERPARTS[builder.substring(DEVKIT_PREFIX.length)];
104
+ if (since === undefined || since > major) found.add(builder);
105
+ }
106
+ return target;
107
+ });
108
+ return found;
109
+ }
110
+
111
+ const ZONE_POLYFILLS = ['zone.js', 'zone.js/testing'];
112
+
113
+ function useAngularBuild(zone: boolean): (target: Json.Object) => Json.Object {
114
+ return target => {
115
+ const builder = builderOf(target);
116
+ if (!builder?.startsWith(DEVKIT_PREFIX)) return target;
117
+ const name = builder.substring(DEVKIT_PREFIX.length);
118
+ const moved = updateMember(target, 'builder', old => jsonLiteral(`@angular/build:${name}`, old.prefix));
119
+ if (name !== 'karma') return moved;
120
+ // `@angular/build:karma` always builds with the `application` builder, so it has no `builderMode` to choose one.
121
+ return mapTargetOptions(moved, options => {
122
+ const withoutMode = removeMember(options, 'builderMode');
123
+ return zone ? zoneTestingInPolyfills(withoutMode) : withoutMode;
124
+ });
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Lists `zone.js` and `zone.js/testing` in the `polyfills` of Karma options that have a `main`.
130
+ * `@angular/build:karma` builds `main` as one more entry point beside each spec, and sets up zone testing only from
131
+ * `polyfills`, so a `main` that imports `zone.js/testing` itself, as the `test.ts` of projects generated before Angular 15
132
+ * does, no longer sets it up for the specs, and every `fakeAsync` fails.
133
+ */
134
+ function zoneTestingInPolyfills(options: Json.Object): Json.Object {
135
+ if (!findMember(options, 'main')) return options;
136
+ const current = findMember(options, 'polyfills')?.value;
137
+ let polyfills: Json.Array;
138
+ if (current === undefined) {
139
+ polyfills = emptyArray(space(' '));
140
+ } else if (isLiteral(current) && typeof current.value === 'string') {
141
+ polyfills = appendElement(emptyArray(current.prefix), jsonLiteral(current.value));
142
+ } else if (isArray(current)) {
143
+ polyfills = current;
144
+ } else {
145
+ return options;
146
+ }
147
+ const listed = new Set(elementsOf(polyfills).map(e => isLiteral(e) ? e.value : undefined));
148
+ for (const entry of ZONE_POLYFILLS) {
149
+ if (!listed.has(entry)) polyfills = appendElement(polyfills, jsonLiteral(entry, elementsOf(polyfills).length ? space(' ') : undefined));
150
+ }
151
+ return polyfills === current ? options : setMember(options, 'polyfills', polyfills);
152
+ }
153
+
154
+ /**
155
+ * Moves the builders of an `angular.json` workspace from `@angular-devkit/build-angular` to `@angular/build`, as the
156
+ * last step of the Angular CLI's `use-application-builder` migration does once nothing in the workspace needs the
157
+ * webpack-based builders.
158
+ *
159
+ * A workspace moves only as a whole, since otherwise it would need both packages. One that still uses a builder
160
+ * that `@angular/build` lacks (`browser`, `server`, `app-shell`, `prerender`, `ssr-dev-server`, `jest`,
161
+ * `web-test-runner`, `protractor`, and `browser-esbuild`, whose migration changes the output location) keeps its
162
+ * builders, and that builder is flagged. So is a workspace on a major before `karma` and `ng-packagr` came to
163
+ * `@angular/build` (19) that uses them. Workspaces before Angular 18, or whose version it cannot tell, are left alone.
164
+ *
165
+ * The builders resolve from `@angular/build` only where the `package.json` declares it.
166
+ * `@angular-devkit/build-angular` depends on `@angular/build` of the same version from 18 on, but npm can nest it under
167
+ * `@angular-devkit/build-angular` and pnpm always does, where the CLI does not resolve builders. So a workspace moves
168
+ * only when its `package.json` declares `@angular/build`, or `UseAngularBuildBuilders` adds it there in the same run,
169
+ * and is flagged otherwise. The `package.json` keeps `@angular-devkit/build-angular`, so Karma configurations that load
170
+ * its plugin keep working.
171
+ *
172
+ * @see https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/use-application-builder/migration.ts
173
+ */
174
+ export class MoveToAngularBuildBuilders extends ScanningRecipe<Workspaces> {
175
+ readonly name = "org.openrewrite.angular.migration.move-to-angular-build-builders";
176
+ readonly displayName: string = "Move the builders of `angular.json` to `@angular/build`";
177
+ readonly description: string = "Moves the `application`, `dev-server`, `extract-i18n`, `karma` and `ng-packagr` builders " +
178
+ "of an `angular.json` workspace from `@angular-devkit/build-angular` to `@angular/build`, as the Angular CLI's " +
179
+ "`use-application-builder` migration does, and drops the `builderMode` option that `@angular/build:karma` does " +
180
+ "not have. A Karma target with a `main` gets `zone.js` and `zone.js/testing` in its `polyfills` where the project " +
181
+ "depends on `zone.js`, since `@angular/build:karma` sets zone testing up only from there. " +
182
+ "A workspace moves only when every one of its builders has a counterpart in `@angular/build` " +
183
+ "at its Angular version (18 for the first three, 19 for `karma` and `ng-packagr`). Otherwise the builders " +
184
+ "that block it, such as the webpack-based `browser` and `server`, are flagged and the workspace is left as it is. " +
185
+ "So is a workspace whose `package.json` neither declares `@angular/build`, which the builders need to resolve, nor " +
186
+ "gets it from `UseAngularBuildBuilders`.";
187
+
188
+ initialValue(_ctx: ExecutionContext): Workspaces {
189
+ return {majors: new Map(), declaring: new Map(), zone: new Map()};
190
+ }
191
+
192
+ async scanner({majors, declaring, zone}: Workspaces): Promise<TreeVisitor<any, ExecutionContext>> {
193
+ return new class extends JsonVisitor<ExecutionContext> {
194
+ protected async visitDocument(doc: Json.Document, _p: ExecutionContext): Promise<Json | undefined> {
195
+ if (posix.basename(doc.sourcePath) === 'package.json') {
196
+ const dir = directoryOf(doc.sourcePath);
197
+ const major = packageMajor(doc, DEVKIT);
198
+ if (major !== undefined) majors.set(dir, major);
199
+ declaring.set(dir, declaredVersion(doc, '@angular/build') !== undefined || addsAngularBuild(doc));
200
+ zone.set(dir, declaredVersion(doc, 'zone.js') !== undefined);
201
+ }
202
+ return doc;
203
+ }
204
+ }();
205
+ }
206
+
207
+ async editorWithData({majors, declaring, zone}: Workspaces): Promise<TreeVisitor<any, ExecutionContext>> {
208
+ return new class extends JsonVisitor<ExecutionContext> {
209
+ protected async visitDocument(doc: Json.Document, p: ExecutionContext): Promise<Json | undefined> {
210
+ if (posix.basename(doc.sourcePath) !== 'angular.json' || !isObject(doc.value)) return doc;
211
+ const major = majorFor(majors, doc.sourcePath);
212
+ if (major === undefined || major < FIRST_MAJOR) return doc;
213
+
214
+ const root = doc.value;
215
+ const blocking = blockers(root, major);
216
+ if (blocking.size === 0 && !declaresAngularBuild(declaring, doc.sourcePath)) {
217
+ const flagged = mapTargets(root, flagFirstDevkitBuilder());
218
+ return flagged === root ? doc : {...doc, value: flagged} as Json.Document;
219
+ }
220
+ if (blocking.size === 0) {
221
+ const updated = mapTargets(root, useAngularBuild(majorFor(zone, doc.sourcePath) ?? false));
222
+ return updated === root ? doc : {...doc, value: updated} as Json.Document;
223
+ }
224
+ const flagged = mapTargets(root, target => flagBuilder(target, blocking));
225
+ return flagged === root ? doc : {...doc, value: flagged} as Json.Document;
226
+ }
227
+ }();
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Moves the builders of `angular.json` to `@angular/build` and declares `@angular/build` in `devDependencies` at the
233
+ * major of `@angular-devkit/build-angular`, as the Angular CLI's `use-application-builder` migration does.
234
+ */
235
+ export class UseAngularBuildBuilders extends Recipe {
236
+ readonly name = "org.openrewrite.angular.migration.use-angular-build-builders";
237
+ readonly displayName: string = "Use the `@angular/build` builders in `angular.json`";
238
+ readonly description: string = "Moves the `application`, `dev-server`, `extract-i18n`, `karma` and `ng-packagr` builders " +
239
+ "of an `angular.json` workspace from `@angular-devkit/build-angular` to `@angular/build`, as the Angular CLI's " +
240
+ "`use-application-builder` migration does, and drops the `builderMode` option that `@angular/build:karma` does " +
241
+ "not have. A Karma target with a `main` gets `zone.js` and `zone.js/testing` in its `polyfills` where the project " +
242
+ "depends on `zone.js`, since `@angular/build:karma` sets zone testing up only from there. " +
243
+ "A workspace moves only when every one of its builders has a counterpart in `@angular/build` " +
244
+ "at its Angular version (18 for the first three, 19 for `karma` and `ng-packagr`). Otherwise the builders " +
245
+ "that block it, such as the webpack-based `browser` and `server`, are flagged and the workspace is left as it is. " +
246
+ "Each `package.json` that declares `@angular-devkit/build-angular` 18 or later gets `@angular/build` of the same " +
247
+ "major in `devDependencies`, which the builders need to resolve. It keeps `@angular-devkit/build-angular`, " +
248
+ "which Karma configurations may still load a plugin from.";
249
+
250
+ async recipeList(): Promise<Recipe[]> {
251
+ return [
252
+ new MoveToAngularBuildBuilders(),
253
+ ...await addDependencyByMajor('@angular/build', 'devDependencies', [DEVKIT], DEVKIT, ANGULAR_BUILD_VERSIONS),
254
+ ];
255
+ }
256
+ }
257
+
258
+ /** Whether the closest `package.json` at or above `sourcePath` declares `@angular/build`, or gets it added. */
259
+ function declaresAngularBuild(declaring: Map<string, boolean>, sourcePath: string): boolean {
260
+ return majorFor(declaring, sourcePath) ?? false;
261
+ }
262
+
263
+ /** Flags the `builder` of the first target on `@angular-devkit/build-angular`, once for the whole workspace. */
264
+ function flagFirstDevkitBuilder(): (target: Json.Object) => Json.Object {
265
+ let done = false;
266
+ return target => {
267
+ if (done || !builderOf(target)?.startsWith(DEVKIT_PREFIX)) return target;
268
+ done = true;
269
+ return markBuilder(target, UNDECLARED_MARK, UNDECLARED);
270
+ };
271
+ }
272
+
273
+ function markBuilder(target: Json.Object, mark: string, message: string): Json.Object {
274
+ const members = target.members.map(rp => {
275
+ const m = rp.element;
276
+ return isMember(m) && getMemberKeyName(m) === 'builder' && !hasSearchResult(m, mark) ?
277
+ {...rp, element: foundSearchResult(m, message)} : rp;
278
+ });
279
+ return members.some((rp, i) => rp !== target.members[i]) ? {...target, members} : target;
280
+ }
281
+
282
+ function flagBuilder(target: Json.Object, blocking: Set<string>): Json.Object {
283
+ const builder = builderOf(target);
284
+ return builder && blocking.has(builder) ? markBuilder(target, BLOCKED_MARK, blocked(builder)) : target;
285
+ }