@openrewrite/recipes-angular 1.35.0 → 1.38.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 (130) hide show
  1. package/dist/index.d.ts +8 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +38 -6
  4. package/dist/index.js.map +1 -1
  5. package/dist/libraries/components/package-version.d.ts +1 -1
  6. package/dist/libraries/components/package-version.d.ts.map +1 -1
  7. package/dist/libraries/components/package-version.js +1 -1
  8. package/dist/libraries/components/package-version.js.map +1 -1
  9. package/dist/migration/add-static-false-to-view-queries.d.ts.map +1 -1
  10. package/dist/migration/add-static-false-to-view-queries.js +16 -13
  11. package/dist/migration/add-static-false-to-view-queries.js.map +1 -1
  12. package/dist/migration/angular-version.d.ts +22 -2
  13. package/dist/migration/angular-version.d.ts.map +1 -1
  14. package/dist/migration/angular-version.js +65 -18
  15. package/dist/migration/angular-version.js.map +1 -1
  16. package/dist/migration/jasmine-to-vitest/add-vitest-imports.d.ts +11 -0
  17. package/dist/migration/jasmine-to-vitest/add-vitest-imports.d.ts.map +1 -0
  18. package/dist/migration/jasmine-to-vitest/add-vitest-imports.js +76 -0
  19. package/dist/migration/jasmine-to-vitest/add-vitest-imports.js.map +1 -0
  20. package/dist/migration/jasmine-to-vitest/migrate-fake-async.d.ts +14 -0
  21. package/dist/migration/jasmine-to-vitest/migrate-fake-async.d.ts.map +1 -0
  22. package/dist/migration/jasmine-to-vitest/migrate-fake-async.js +225 -0
  23. package/dist/migration/jasmine-to-vitest/migrate-fake-async.js.map +1 -0
  24. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.d.ts +11 -0
  25. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.d.ts.map +1 -0
  26. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.js +379 -0
  27. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.js.map +1 -0
  28. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.d.ts +18 -0
  29. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.d.ts.map +1 -0
  30. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.js +446 -0
  31. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.js.map +1 -0
  32. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.d.ts +11 -0
  33. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.d.ts.map +1 -0
  34. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.js +209 -0
  35. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.js.map +1 -0
  36. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.d.ts +11 -0
  37. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.d.ts.map +1 -0
  38. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.js +567 -0
  39. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.js.map +1 -0
  40. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.d.ts +16 -0
  41. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.d.ts.map +1 -0
  42. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.js +90 -0
  43. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.js.map +1 -0
  44. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.d.ts +11 -0
  45. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.d.ts.map +1 -0
  46. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.js +142 -0
  47. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.js.map +1 -0
  48. package/dist/migration/jasmine-to-vitest/support.d.ts +88 -0
  49. package/dist/migration/jasmine-to-vitest/support.d.ts.map +1 -0
  50. package/dist/migration/jasmine-to-vitest/support.js +561 -0
  51. package/dist/migration/jasmine-to-vitest/support.js.map +1 -0
  52. package/dist/migration/remove-default-project.d.ts +1 -0
  53. package/dist/migration/remove-default-project.d.ts.map +1 -1
  54. package/dist/migration/remove-default-project.js +3 -1
  55. package/dist/migration/remove-default-project.js.map +1 -1
  56. package/dist/migration/upgrade-to-angular-10.d.ts.map +1 -1
  57. package/dist/migration/upgrade-to-angular-10.js +3 -2
  58. package/dist/migration/upgrade-to-angular-10.js.map +1 -1
  59. package/dist/migration/upgrade-to-angular-11.d.ts.map +1 -1
  60. package/dist/migration/upgrade-to-angular-11.js +3 -2
  61. package/dist/migration/upgrade-to-angular-11.js.map +1 -1
  62. package/dist/migration/upgrade-to-angular-12.d.ts.map +1 -1
  63. package/dist/migration/upgrade-to-angular-12.js +3 -2
  64. package/dist/migration/upgrade-to-angular-12.js.map +1 -1
  65. package/dist/migration/upgrade-to-angular-13.d.ts.map +1 -1
  66. package/dist/migration/upgrade-to-angular-13.js +4 -5
  67. package/dist/migration/upgrade-to-angular-13.js.map +1 -1
  68. package/dist/migration/upgrade-to-angular-14.d.ts.map +1 -1
  69. package/dist/migration/upgrade-to-angular-14.js +6 -2
  70. package/dist/migration/upgrade-to-angular-14.js.map +1 -1
  71. package/dist/migration/upgrade-to-angular-15.d.ts.map +1 -1
  72. package/dist/migration/upgrade-to-angular-15.js +3 -2
  73. package/dist/migration/upgrade-to-angular-15.js.map +1 -1
  74. package/dist/migration/upgrade-to-angular-16.d.ts.map +1 -1
  75. package/dist/migration/upgrade-to-angular-16.js +3 -2
  76. package/dist/migration/upgrade-to-angular-16.js.map +1 -1
  77. package/dist/migration/upgrade-to-angular-17.d.ts.map +1 -1
  78. package/dist/migration/upgrade-to-angular-17.js +3 -2
  79. package/dist/migration/upgrade-to-angular-17.js.map +1 -1
  80. package/dist/migration/upgrade-to-angular-18.d.ts.map +1 -1
  81. package/dist/migration/upgrade-to-angular-18.js +3 -2
  82. package/dist/migration/upgrade-to-angular-18.js.map +1 -1
  83. package/dist/migration/upgrade-to-angular-19.d.ts.map +1 -1
  84. package/dist/migration/upgrade-to-angular-19.js +3 -2
  85. package/dist/migration/upgrade-to-angular-19.js.map +1 -1
  86. package/dist/migration/upgrade-to-angular-20.d.ts.map +1 -1
  87. package/dist/migration/upgrade-to-angular-20.js +3 -2
  88. package/dist/migration/upgrade-to-angular-20.js.map +1 -1
  89. package/dist/migration/upgrade-to-angular-21.d.ts.map +1 -1
  90. package/dist/migration/upgrade-to-angular-21.js +3 -2
  91. package/dist/migration/upgrade-to-angular-21.js.map +1 -1
  92. package/dist/migration/upgrade-to-angular-22.d.ts.map +1 -1
  93. package/dist/migration/upgrade-to-angular-22.js +3 -2
  94. package/dist/migration/upgrade-to-angular-22.js.map +1 -1
  95. package/dist/migration/upgrade-to-angular-8.d.ts.map +1 -1
  96. package/dist/migration/upgrade-to-angular-8.js +3 -2
  97. package/dist/migration/upgrade-to-angular-8.js.map +1 -1
  98. package/dist/migration/upgrade-to-angular-9.d.ts.map +1 -1
  99. package/dist/migration/upgrade-to-angular-9.js +3 -2
  100. package/dist/migration/upgrade-to-angular-9.js.map +1 -1
  101. package/package.json +1 -1
  102. package/src/index.ts +24 -0
  103. package/src/libraries/components/package-version.ts +2 -2
  104. package/src/migration/add-static-false-to-view-queries.ts +16 -12
  105. package/src/migration/angular-version.ts +65 -16
  106. package/src/migration/jasmine-to-vitest/add-vitest-imports.ts +51 -0
  107. package/src/migration/jasmine-to-vitest/migrate-fake-async.ts +211 -0
  108. package/src/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.ts +346 -0
  109. package/src/migration/jasmine-to-vitest/migrate-jasmine-matchers.ts +410 -0
  110. package/src/migration/jasmine-to-vitest/migrate-jasmine-misc.ts +190 -0
  111. package/src/migration/jasmine-to-vitest/migrate-jasmine-spies.ts +533 -0
  112. package/src/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.ts +72 -0
  113. package/src/migration/jasmine-to-vitest/migrate-jasmine-types.ts +97 -0
  114. package/src/migration/jasmine-to-vitest/support.ts +516 -0
  115. package/src/migration/remove-default-project.ts +3 -1
  116. package/src/migration/upgrade-to-angular-10.ts +4 -3
  117. package/src/migration/upgrade-to-angular-11.ts +4 -3
  118. package/src/migration/upgrade-to-angular-12.ts +4 -3
  119. package/src/migration/upgrade-to-angular-13.ts +5 -6
  120. package/src/migration/upgrade-to-angular-14.ts +7 -3
  121. package/src/migration/upgrade-to-angular-15.ts +4 -3
  122. package/src/migration/upgrade-to-angular-16.ts +4 -3
  123. package/src/migration/upgrade-to-angular-17.ts +4 -3
  124. package/src/migration/upgrade-to-angular-18.ts +4 -3
  125. package/src/migration/upgrade-to-angular-19.ts +4 -3
  126. package/src/migration/upgrade-to-angular-20.ts +4 -3
  127. package/src/migration/upgrade-to-angular-21.ts +4 -3
  128. package/src/migration/upgrade-to-angular-22.ts +4 -3
  129. package/src/migration/upgrade-to-angular-8.ts +4 -3
  130. package/src/migration/upgrade-to-angular-9.ts +4 -3
@@ -0,0 +1,346 @@
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 {Cursor, ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {J, isFieldAccess, isMethodInvocation} from "@openrewrite/rewrite/java";
9
+ import {JS, JavaScriptVisitor} from "@openrewrite/rewrite/javascript";
10
+ import {create} from "mutative";
11
+ import {
12
+ JasmineToVitestVisitor,
13
+ Piece,
14
+ StatementResult,
15
+ args,
16
+ functionBody,
17
+ functionExpression,
18
+ isFunctionLike,
19
+ isGlobalCall,
20
+ isNamed,
21
+ parameterNames,
22
+ replaceWith,
23
+ select,
24
+ todoText,
25
+ walk,
26
+ withoutStatements
27
+ } from "./support";
28
+ import {commentedOut} from "./migrate-jasmine-matchers";
29
+
30
+ /**
31
+ * @see https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/refactor/jasmine-vitest/transformers/jasmine-lifecycle.ts
32
+ */
33
+ export class MigrateJasmineLifecycleToVitest extends Recipe {
34
+ readonly name = "org.openrewrite.angular.migration.migrate-jasmine-lifecycle-to-vitest";
35
+ readonly displayName = "Migrate Jasmine focused, skipped, pending and `done` tests to Vitest";
36
+ readonly description = "Rewrites `fdescribe`, `fit`, `xdescribe` and `xit` to `describe.only`, `it.only`, " +
37
+ "`describe.skip` and `it.skip`; turns a test that calls `pending()` into `it.skip`; and turns a test or hook " +
38
+ "taking a `done` callback into an `async` function, awaiting the promise `done` was chained to and throwing " +
39
+ "where it called `done.fail`. A test whose `done` is called from a nested callback, such as a `subscribe` " +
40
+ "or `setTimeout` callback, or passed on, returns a promise that the same `done` resolves, with `done.fail` " +
41
+ "rejecting it. A `done` called with an argument, or one in an async function, is left with a " +
42
+ "`TODO: vitest-migration` comment, as the Angular CLI's `refactor-jasmine-vitest` schematic does.";
43
+
44
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
45
+ return new LifecycleVisitor();
46
+ }
47
+ }
48
+
49
+ const FOCUSED_SKIPPED = new Map<string, string>([
50
+ ['fdescribe', 'describe.only'],
51
+ ['fit', 'it.only'],
52
+ ['xdescribe', 'describe.skip'],
53
+ ['xit', 'it.skip'],
54
+ ]);
55
+
56
+ const DONE_HOSTS = ['it', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll'];
57
+
58
+ class LifecycleVisitor extends JasmineToVitestVisitor {
59
+ /** The `it(...)` calls a `pending()` was removed from, which become `it.skip(...)`. */
60
+ private readonly pendingTests = new Set<string>();
61
+
62
+ protected override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
63
+ const visited = await super.visitMethodInvocation(method, p);
64
+ if (!visited || !isMethodInvocation(visited)) return visited;
65
+ let m: J = visited;
66
+ m = (await this.focusedAndSkipped(visited)) ?? m;
67
+ if (isMethodInvocation(m)) m = (await this.pending(m)) ?? m;
68
+ if (isMethodInvocation(m)) m = (await this.doneCallback(m, p)) ?? m;
69
+ return m;
70
+ }
71
+
72
+ /** The same call, its arguments as they were, under another name such as `it.only`. */
73
+ private async renamed(m: J.MethodInvocation, callee: string): Promise<J> {
74
+ const result = await replaceWith(m, this.cursor, `${callee}()`);
75
+ if (!isMethodInvocation(result)) return result;
76
+ return create(result, d => {
77
+ d.arguments = m.arguments as any;
78
+ d.typeParameters = m.typeParameters as any;
79
+ });
80
+ }
81
+
82
+ private async focusedAndSkipped(m: J.MethodInvocation): Promise<J | undefined> {
83
+ if (m.select) return undefined;
84
+ const callee = FOCUSED_SKIPPED.get(m.name.simpleName);
85
+ return callee ? this.renamed(m, callee) : undefined;
86
+ }
87
+
88
+ private async pending(m: J.MethodInvocation): Promise<J | undefined> {
89
+ if (!this.pendingTests.has(m.id)) return undefined;
90
+ this.pendingTests.delete(m.id);
91
+ return this.renamed(m, `${m.name.simpleName}.skip`);
92
+ }
93
+
94
+ protected override async visitBlockStatement(statement: J, cursor: Cursor): Promise<StatementResult | undefined> {
95
+ if (!isGlobalCall(statement, 'pending')) return undefined;
96
+ // Only inside the function of an `it(...)`, as the schematic does.
97
+ const test = cursor.firstEnclosing((t: any): t is J.MethodInvocation =>
98
+ isMethodInvocation(t) && isGlobalCall(t, 'it') && isFunctionLike(args(t)[1]));
99
+ if (!test) return undefined;
100
+ this.pendingTests.add(test.id);
101
+ return {
102
+ removeLeaving: [
103
+ todoText('The pending() function was converted to a skipped test (`it.skip`).', 'https://vitest.dev/api/vi.html#it-skip'),
104
+ ...await commentedOut(statement, cursor),
105
+ ]
106
+ };
107
+ }
108
+
109
+ private async doneCallback(m: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
110
+ if (m.select || !DONE_HOSTS.includes(m.name.simpleName)) return undefined;
111
+ const fn = args(m).find(isFunctionLike);
112
+ if (!fn) return undefined;
113
+ const params = parameterNames(fn);
114
+ if (params.length !== 1 || !params[0]) return undefined;
115
+ const done = params[0];
116
+ const body = functionBody(fn)!;
117
+
118
+ let total = 0;
119
+ walk(body, n => {
120
+ if (n.kind === J.Kind.Identifier && n.simpleName === done) total++;
121
+ });
122
+ const rewriter = new DoneRewriter(done);
123
+ const newBody = await rewriter.visit(body, p, new Cursor(fn, this.cursor)) as J;
124
+ if (rewriter.handled < total) {
125
+ const wrapped = await promiseWrapper(fn, done, body, this.cursor, p);
126
+ if (!wrapped) {
127
+ this.todo(m, "The 'done' callback was used in an unhandled way. Please migrate manually.");
128
+ return m;
129
+ }
130
+ return create(m, d => {
131
+ for (const e of d.arguments.elements) {
132
+ if (e.element.id === fn.id) e.element = wrapped as any;
133
+ }
134
+ });
135
+ }
136
+ if (rewriter.handled === 0) return undefined;
137
+
138
+ const fe = functionExpression(fn);
139
+ const name = fe && fe.name.simpleName ? ` ${fe.name.simpleName}` : '';
140
+ const shell = await replaceWith(fn, new Cursor(fn, this.cursor),
141
+ fn.kind === JS.Kind.ArrowFunction ? 'async () => {}' : `(async function${name}() {})`);
142
+ const asyncFn = {...withBody(shell, newBody), prefix: fn.prefix} as J;
143
+ return create(m, d => {
144
+ for (const e of d.arguments.elements) {
145
+ if (e.element.id === fn.id) e.element = asyncFn as any;
146
+ }
147
+ });
148
+ }
149
+ }
150
+
151
+ /**
152
+ * A test or hook whose `done` is called from a nested callback, such as `subscribe(() => { ...; done(); })`,
153
+ * or passed on, as in `setTimeout(done)`: the test returns a promise that the same `done` resolves, as the
154
+ * Vitest migration guide does. The body is left as it was, since `done` is now the promise's resolve function.
155
+ * `done.fail(e)` rejects it. Declined where `done` is called with an argument, which Jasmine reads as a
156
+ * failure and a resolve would not, and for an async function, which Jasmine rejects alongside `done`.
157
+ */
158
+ async function promiseWrapper(fn: J, done: string, body: J, cursor: Cursor, p: ExecutionContext): Promise<J | undefined> {
159
+ const isAsync = (mod: J.Modifier) => mod.type === J.ModifierType.Async || mod.keyword === 'async';
160
+ if ((fn as any).modifiers?.some(isAsync) || functionExpression(fn)?.modifiers?.some(isAsync)) {
161
+ return undefined;
162
+ }
163
+ let calledWithArgument = false, usesFail = false, rejectTaken = false, usedAsCallback = false;
164
+ walk(body, n => {
165
+ if (n.kind === J.Kind.MethodInvocation && !n.select && n.name.simpleName === done) {
166
+ usedAsCallback = true;
167
+ if (args(n).length > 0) calledWithArgument = true;
168
+ }
169
+ // Handed on, as in `setTimeout(done)` or `helper(done)`; read by `expect(done)` it is a value, not a callback.
170
+ if (n.kind === J.Kind.MethodInvocation && !isGlobalCall(n, 'expect') && args(n).some(a => isNamed(a, done))) {
171
+ usedAsCallback = true;
172
+ }
173
+ if (n.kind === JS.Kind.PropertyAssignment && n.initializer && isNamed(n.initializer, done)) {
174
+ usedAsCallback = true;
175
+ }
176
+ if (n.kind === J.Kind.MethodInvocation && n.select && isNamed(select(n), done) && n.name.simpleName === 'fail') {
177
+ usesFail = true;
178
+ }
179
+ if (n.kind === J.Kind.FieldAccess && isNamed(n.target, done) && n.name.element.simpleName === 'fail') {
180
+ usesFail = true;
181
+ }
182
+ if (n.kind === J.Kind.Identifier && n.simpleName === 'reject') rejectTaken = true;
183
+ });
184
+ if (!(usedAsCallback || usesFail) || calledWithArgument || (usesFail && rejectTaken)) return undefined;
185
+
186
+ const newBody = usesFail ? await new FailToReject(done).visit(body, p, new Cursor(fn, cursor)) as J : body;
187
+ // Only TypeScript specs reach here (`isJasmineTestFile`), so the type argument is always welcome.
188
+ const promise = `new Promise<void>((${done}${usesFail ? ', reject' : ''}) => `;
189
+ const fnCursor = new Cursor(fn, cursor);
190
+ const result = fn.kind === JS.Kind.ArrowFunction
191
+ ? await replaceWith(fn, fnCursor, `() => ${promise}`, newBody, ')')
192
+ : await replaceWith(fn, fnCursor, `(function${functionName(fn)}() { return ${promise}`, newBody, '); })');
193
+ return {...result, prefix: fn.prefix} as J;
194
+ }
195
+
196
+ function functionName(fn: J): string {
197
+ const fe = functionExpression(fn);
198
+ return fe && fe.name.simpleName ? ` ${fe.name.simpleName}` : '';
199
+ }
200
+
201
+ /** `done.fail(e)` to `reject(e)`, and `done.fail` passed on, as in `.catch(done.fail)`, to `reject`. */
202
+ class FailToReject extends JavaScriptVisitor<ExecutionContext> {
203
+ constructor(private readonly done: string) {
204
+ super();
205
+ }
206
+
207
+ protected override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
208
+ const m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
209
+ if (m.select && isNamed(select(m), this.done) && m.name.simpleName === 'fail') {
210
+ return replaceWith(m, this.cursor, 'reject(', ...interleave(args(m)), ')');
211
+ }
212
+ return m;
213
+ }
214
+
215
+ protected override async visitFieldAccess(fieldAccess: J.FieldAccess, p: ExecutionContext): Promise<J | undefined> {
216
+ const fa = await super.visitFieldAccess(fieldAccess, p) as J.FieldAccess;
217
+ if (isNamed(fa.target, this.done) && fa.name.element.simpleName === 'fail') {
218
+ return replaceWith(fa, this.cursor, 'reject');
219
+ }
220
+ return fa;
221
+ }
222
+ }
223
+
224
+ function interleave(trees: J[]): Piece[] {
225
+ const pieces: Piece[] = [];
226
+ trees.forEach((t, i) => pieces.push(...(i ? [', '] : []), t));
227
+ return pieces;
228
+ }
229
+
230
+ /**
231
+ * Takes `done` out of a test body: drops `done()`, throws where `done.fail(...)` was called, and
232
+ * awaits a promise whose `.then` or `.catch` called `done`. It counts the uses of `done` it handled.
233
+ */
234
+ class DoneRewriter extends JavaScriptVisitor<ExecutionContext> {
235
+ handled = 0;
236
+
237
+ constructor(private readonly done: string) {
238
+ super();
239
+ }
240
+
241
+ // A `done` called from a nested function, such as a `subscribe` or `setTimeout` callback, is how the test
242
+ // waits for that callback. Dropping it would let the async test end first, so it is left unhandled and the
243
+ // test gets the TODO. The schematic removes it. `.then` callbacks are handled in rewriteStatement.
244
+ override async visitArrowFunction(arrowFunction: JS.ArrowFunction, _p: ExecutionContext): Promise<J | undefined> {
245
+ return arrowFunction;
246
+ }
247
+
248
+ override async visitMethodDeclaration(method: J.MethodDeclaration, _p: ExecutionContext): Promise<J | undefined> {
249
+ return method;
250
+ }
251
+
252
+ override async visitBlock(block: J.Block, p: ExecutionContext): Promise<J | undefined> {
253
+ // Statements first, so a statement this rewrites is not also visited below.
254
+ const dropped = new Set<J>();
255
+ const statements: J.RightPadded<J>[] = [];
256
+ for (const rp of block.statements) {
257
+ const s = rp.element;
258
+ const rewritten = await this.rewriteStatement(s, new Cursor(s, new Cursor(block, this.cursor)));
259
+ if (rewritten === null) {
260
+ dropped.add(s);
261
+ statements.push(rp);
262
+ continue;
263
+ }
264
+ const next = rewritten ?? await this.visit(s, p, new Cursor(block, this.cursor)) as J;
265
+ statements.push(next === s ? rp : {...rp, element: next});
266
+ }
267
+ if (dropped.size === 0 && statements.every((rp, i) => rp === block.statements[i])) return block;
268
+ const updated = create(block, d => {
269
+ d.statements = statements as any;
270
+ });
271
+ return withoutStatements(updated, s => dropped.has(s));
272
+ }
273
+
274
+ /** The statement's replacement, `null` to drop it, or undefined to leave it to the visitor. */
275
+ private async rewriteStatement(s: J, cursor: Cursor): Promise<J | null | undefined> {
276
+ if (!isMethodInvocation(s)) return undefined;
277
+ const done = this.done;
278
+
279
+ // promise.then(() => { ...; done(); }) to await promise.then(() => { ... })
280
+ if (s.name.simpleName === 'then' && s.select && args(s).length === 1 && isFunctionLike(args(s)[0])) {
281
+ const callback = args(s)[0];
282
+ const body = functionBody(callback)!;
283
+ const statements = body.kind === J.Kind.Block ? (body as J.Block).statements.map(r => r.element) : [body];
284
+ const kept = statements.filter(st => !isGlobalCall(st, done));
285
+ if (kept.length !== statements.length) {
286
+ this.handled++;
287
+ if (body.kind !== J.Kind.Block) {
288
+ // `() => done()` leaves nothing to do.
289
+ return replaceWith(s, cursor, 'await ', select(s)!, '.then(() => {})');
290
+ }
291
+ const newBody = withoutStatements(body as J.Block, st => isGlobalCall(st, done));
292
+ const pieces: Piece[] = ['await ', select(s)!, '.then(', withBody(callback, newBody), ')'];
293
+ return replaceWith(s, cursor, ...pieces);
294
+ }
295
+ }
296
+
297
+ // done.fail(message) to throw new Error(message)
298
+ if (s.select && isNamed(select(s), done) && s.name.simpleName === 'fail') {
299
+ this.handled++;
300
+ const message = args(s)[0];
301
+ return replaceWith(s, cursor, 'throw new Error(', ...(message ? [message] : []), ')');
302
+ }
303
+
304
+ // promise.then(done), promise.catch(done.fail) and promise.then(() => done()) to await promise
305
+ if (s.select && (s.name.simpleName === 'then' || s.name.simpleName === 'catch')) {
306
+ const handler = args(s)[0];
307
+ if (handler && this.isDoneHandler(handler)) {
308
+ this.handled++;
309
+ return replaceWith(s, cursor, 'await ', select(s)!);
310
+ }
311
+ }
312
+
313
+ // done()
314
+ if (isGlobalCall(s, done)) {
315
+ this.handled++;
316
+ return null;
317
+ }
318
+ return undefined;
319
+ }
320
+
321
+ private isDoneHandler(handler: J): boolean {
322
+ const done = this.done;
323
+ if (isNamed(handler, done)) return true;
324
+ if (isFieldAccess(handler) && isNamed(handler.target, done) && handler.name.element.simpleName === 'fail') return true;
325
+ if (handler.kind === JS.Kind.ArrowFunction && parameterNames(handler).length === 0) {
326
+ const body = functionBody(handler)!;
327
+ if (isGlobalCall(body, done)) return true;
328
+ if (body.kind === J.Kind.Block) {
329
+ const statements = (body as J.Block).statements;
330
+ return statements.length === 1 && isGlobalCall(statements[0].element, done);
331
+ }
332
+ }
333
+ return false;
334
+ }
335
+ }
336
+
337
+ function withBody(fn: J, body: J): J {
338
+ if (fn.kind === JS.Kind.ArrowFunction) {
339
+ return create(fn as JS.ArrowFunction, d => {
340
+ d.lambda.body = body as any;
341
+ });
342
+ }
343
+ return create(fn as JS.StatementExpression, d => {
344
+ (d.statement as any).body = body;
345
+ });
346
+ }