@openrewrite/recipes-react 0.32.0 → 0.33.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 (150) hide show
  1. package/dist/index.d.ts +37 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +146 -2
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/shared.d.ts +2 -8
  6. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  7. package/dist/migration/cra-to-vite/shared.js +21 -53
  8. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  9. package/dist/nextjs-config/config-recipes.d.ts +90 -0
  10. package/dist/nextjs-config/config-recipes.d.ts.map +1 -0
  11. package/dist/nextjs-config/config-recipes.js +222 -0
  12. package/dist/nextjs-config/config-recipes.js.map +1 -0
  13. package/dist/nextjs-config/next-config.d.ts +25 -0
  14. package/dist/nextjs-config/next-config.d.ts.map +1 -0
  15. package/dist/nextjs-config/next-config.js +199 -0
  16. package/dist/nextjs-config/next-config.js.map +1 -0
  17. package/dist/nextjs-search/find-nextjs-projects-below.d.ts +37 -0
  18. package/dist/nextjs-search/find-nextjs-projects-below.d.ts.map +1 -0
  19. package/dist/nextjs-search/find-nextjs-projects-below.js +196 -0
  20. package/dist/nextjs-search/find-nextjs-projects-below.js.map +1 -0
  21. package/dist/nextjs-search/find-nextjs-upgrade-issues.d.ts +18 -0
  22. package/dist/nextjs-search/find-nextjs-upgrade-issues.d.ts.map +1 -0
  23. package/dist/nextjs-search/find-nextjs-upgrade-issues.js +269 -0
  24. package/dist/nextjs-search/find-nextjs-upgrade-issues.js.map +1 -0
  25. package/dist/nextjs-search/find-pages-router-candidates.d.ts +14 -0
  26. package/dist/nextjs-search/find-pages-router-candidates.d.ts.map +1 -0
  27. package/dist/nextjs-search/find-pages-router-candidates.js +136 -0
  28. package/dist/nextjs-search/find-pages-router-candidates.js.map +1 -0
  29. package/dist/nextjs-search/mark-pending-nextjs-upgrade.d.ts +16 -0
  30. package/dist/nextjs-search/mark-pending-nextjs-upgrade.d.ts.map +1 -0
  31. package/dist/nextjs-search/mark-pending-nextjs-upgrade.js +125 -0
  32. package/dist/nextjs-search/mark-pending-nextjs-upgrade.js.map +1 -0
  33. package/dist/nextjs13/new-link.d.ts +8 -0
  34. package/dist/nextjs13/new-link.d.ts.map +1 -0
  35. package/dist/nextjs13/new-link.js +82 -0
  36. package/dist/nextjs13/new-link.js.map +1 -0
  37. package/dist/nextjs13/next-image-to-legacy-image.d.ts +8 -0
  38. package/dist/nextjs13/next-image-to-legacy-image.d.ts.map +1 -0
  39. package/dist/nextjs13/next-image-to-legacy-image.js +103 -0
  40. package/dist/nextjs13/next-image-to-legacy-image.js.map +1 -0
  41. package/dist/nextjs13/next-modules.d.ts +18 -0
  42. package/dist/nextjs13/next-modules.d.ts.map +1 -0
  43. package/dist/nextjs13/next-modules.js +127 -0
  44. package/dist/nextjs13/next-modules.js.map +1 -0
  45. package/dist/nextjs14/metadata-to-viewport-export.d.ts +8 -0
  46. package/dist/nextjs14/metadata-to-viewport-export.d.ts.map +1 -0
  47. package/dist/nextjs14/metadata-to-viewport-export.js +223 -0
  48. package/dist/nextjs14/metadata-to-viewport-export.js.map +1 -0
  49. package/dist/nextjs14/next-og-import.d.ts +8 -0
  50. package/dist/nextjs14/next-og-import.d.ts.map +1 -0
  51. package/dist/nextjs14/next-og-import.js +29 -0
  52. package/dist/nextjs14/next-og-import.js.map +1 -0
  53. package/dist/nextjs15/add-vercel-functions.d.ts +17 -0
  54. package/dist/nextjs15/add-vercel-functions.d.ts.map +1 -0
  55. package/dist/nextjs15/add-vercel-functions.js +86 -0
  56. package/dist/nextjs15/add-vercel-functions.js.map +1 -0
  57. package/dist/nextjs15/app-dir-runtime-config-experimental-edge.d.ts +11 -0
  58. package/dist/nextjs15/app-dir-runtime-config-experimental-edge.d.ts.map +1 -0
  59. package/dist/nextjs15/app-dir-runtime-config-experimental-edge.js +62 -0
  60. package/dist/nextjs15/app-dir-runtime-config-experimental-edge.js.map +1 -0
  61. package/dist/nextjs15/app-router.d.ts +26 -0
  62. package/dist/nextjs15/app-router.d.ts.map +1 -0
  63. package/dist/nextjs15/app-router.js +302 -0
  64. package/dist/nextjs15/app-router.js.map +1 -0
  65. package/dist/nextjs15/async-params.d.ts +8 -0
  66. package/dist/nextjs15/async-params.d.ts.map +1 -0
  67. package/dist/nextjs15/async-params.js +484 -0
  68. package/dist/nextjs15/async-params.js.map +1 -0
  69. package/dist/nextjs15/async-request-apis.d.ts +8 -0
  70. package/dist/nextjs15/async-request-apis.d.ts.map +1 -0
  71. package/dist/nextjs15/async-request-apis.js +204 -0
  72. package/dist/nextjs15/async-request-apis.js.map +1 -0
  73. package/dist/nextjs15/fetch-cache-defaults.d.ts +8 -0
  74. package/dist/nextjs15/fetch-cache-defaults.d.ts.map +1 -0
  75. package/dist/nextjs15/fetch-cache-defaults.js +160 -0
  76. package/dist/nextjs15/fetch-cache-defaults.js.map +1 -0
  77. package/dist/nextjs15/next-request-geo-ip.d.ts +10 -0
  78. package/dist/nextjs15/next-request-geo-ip.d.ts.map +1 -0
  79. package/dist/nextjs15/next-request-geo-ip.js +71 -0
  80. package/dist/nextjs15/next-request-geo-ip.js.map +1 -0
  81. package/dist/nextjs15/route-handler-cache-defaults.d.ts +8 -0
  82. package/dist/nextjs15/route-handler-cache-defaults.d.ts.map +1 -0
  83. package/dist/nextjs15/route-handler-cache-defaults.js +231 -0
  84. package/dist/nextjs15/route-handler-cache-defaults.js.map +1 -0
  85. package/dist/nextjs16/middleware-to-proxy.d.ts +16 -0
  86. package/dist/nextjs16/middleware-to-proxy.d.ts.map +1 -0
  87. package/dist/nextjs16/middleware-to-proxy.js +159 -0
  88. package/dist/nextjs16/middleware-to-proxy.js.map +1 -0
  89. package/dist/nextjs16/next-lint-to-eslint.d.ts +9 -0
  90. package/dist/nextjs16/next-lint-to-eslint.d.ts.map +1 -0
  91. package/dist/nextjs16/next-lint-to-eslint.js +60 -0
  92. package/dist/nextjs16/next-lint-to-eslint.js.map +1 -0
  93. package/dist/nextjs16/remove-experimental-ppr-config.d.ts +9 -0
  94. package/dist/nextjs16/remove-experimental-ppr-config.d.ts.map +1 -0
  95. package/dist/nextjs16/remove-experimental-ppr-config.js +17 -0
  96. package/dist/nextjs16/remove-experimental-ppr-config.js.map +1 -0
  97. package/dist/nextjs16/remove-experimental-ppr.d.ts +8 -0
  98. package/dist/nextjs16/remove-experimental-ppr.d.ts.map +1 -0
  99. package/dist/nextjs16/remove-experimental-ppr.js +67 -0
  100. package/dist/nextjs16/remove-experimental-ppr.js.map +1 -0
  101. package/dist/nextjs16/revalidate-tag-profile.d.ts +8 -0
  102. package/dist/nextjs16/revalidate-tag-profile.d.ts.map +1 -0
  103. package/dist/nextjs16/revalidate-tag-profile.js +46 -0
  104. package/dist/nextjs16/revalidate-tag-profile.js.map +1 -0
  105. package/dist/nextjs16/stable-cache-apis.d.ts +8 -0
  106. package/dist/nextjs16/stable-cache-apis.d.ts.map +1 -0
  107. package/dist/nextjs16/stable-cache-apis.js +29 -0
  108. package/dist/nextjs16/stable-cache-apis.js.map +1 -0
  109. package/dist/react19/replace-default-props.d.ts.map +1 -1
  110. package/dist/react19/replace-default-props.js +50 -13
  111. package/dist/react19/replace-default-props.js.map +1 -1
  112. package/dist/util/java-recipe-proxy.d.ts +1 -0
  113. package/dist/util/java-recipe-proxy.d.ts.map +1 -1
  114. package/dist/util/java-recipe-proxy.js +8 -5
  115. package/dist/util/java-recipe-proxy.js.map +1 -1
  116. package/dist/util/package-json.d.ts +11 -0
  117. package/dist/util/package-json.d.ts.map +1 -0
  118. package/dist/util/package-json.js +46 -0
  119. package/dist/util/package-json.js.map +1 -0
  120. package/package.json +2 -2
  121. package/src/index.ts +123 -0
  122. package/src/migration/cra-to-vite/shared.ts +3 -42
  123. package/src/nextjs-config/config-recipes.ts +219 -0
  124. package/src/nextjs-config/next-config.ts +190 -0
  125. package/src/nextjs-search/find-nextjs-projects-below.ts +216 -0
  126. package/src/nextjs-search/find-nextjs-upgrade-issues.ts +225 -0
  127. package/src/nextjs-search/find-pages-router-candidates.ts +110 -0
  128. package/src/nextjs-search/mark-pending-nextjs-upgrade.ts +131 -0
  129. package/src/nextjs13/new-link.ts +57 -0
  130. package/src/nextjs13/next-image-to-legacy-image.ts +71 -0
  131. package/src/nextjs13/next-modules.ts +93 -0
  132. package/src/nextjs14/metadata-to-viewport-export.ts +224 -0
  133. package/src/nextjs14/next-og-import.ts +19 -0
  134. package/src/nextjs15/add-vercel-functions.ts +78 -0
  135. package/src/nextjs15/app-dir-runtime-config-experimental-edge.ts +38 -0
  136. package/src/nextjs15/app-router.ts +316 -0
  137. package/src/nextjs15/async-params.ts +487 -0
  138. package/src/nextjs15/async-request-apis.ts +213 -0
  139. package/src/nextjs15/fetch-cache-defaults.ts +141 -0
  140. package/src/nextjs15/next-request-geo-ip.ts +49 -0
  141. package/src/nextjs15/route-handler-cache-defaults.ts +189 -0
  142. package/src/nextjs16/middleware-to-proxy.ts +146 -0
  143. package/src/nextjs16/next-lint-to-eslint.ts +43 -0
  144. package/src/nextjs16/remove-experimental-ppr-config.ts +15 -0
  145. package/src/nextjs16/remove-experimental-ppr.ts +39 -0
  146. package/src/nextjs16/revalidate-tag-profile.ts +28 -0
  147. package/src/nextjs16/stable-cache-apis.ts +20 -0
  148. package/src/react19/replace-default-props.ts +65 -27
  149. package/src/util/java-recipe-proxy.ts +9 -3
  150. package/src/util/package-json.ts +43 -0
@@ -0,0 +1,213 @@
1
+ import {check, Cursor, emptyMarkers, ExecutionContext, foundSearchResult, MarkersKind, not, randomId, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeBind, MethodMatcher} from "@openrewrite/rewrite/javascript";
3
+ import {emptySpace, isIdentifier, J, rightPadded, space} from "@openrewrite/rewrite/java";
4
+ import {
5
+ awaitOf,
6
+ callsHooks,
7
+ enclosingFunction,
8
+ exportedName,
9
+ FunctionLike,
10
+ guardLeadingParentheses,
11
+ HTTP_METHODS,
12
+ identifier,
13
+ isAsync,
14
+ isFunctionLike,
15
+ isServerFile,
16
+ makeAsync,
17
+ METADATA_FUNCTIONS,
18
+ needsParentheses,
19
+ parenthesize
20
+ } from "./app-router";
21
+
22
+ const PROMISE_COMBINATORS = new Set(['all', 'allSettled', 'any', 'race']);
23
+
24
+ /** The request APIs `next/headers` exports, and the type each resolves to when read synchronously. */
25
+ const REQUEST_APIS: [MethodMatcher, string][] = [
26
+ [new MethodMatcher('next/headers cookies()'), 'UnsafeUnwrappedCookies'],
27
+ [new MethodMatcher('next/headers headers()'), 'UnsafeUnwrappedHeaders'],
28
+ [new MethodMatcher('next/headers draftMode()'), 'UnsafeUnwrappedDraftMode'],
29
+ ];
30
+
31
+ /**
32
+ * Where the call sits in an async function, it is awaited. A synchronous App Router entry — a
33
+ * server page, layout or route handler export, or their `generateMetadata` — becomes async first,
34
+ * since Next.js awaits what it returns. Anywhere else synchronous, making the function async would
35
+ * change what its callers get, so in TypeScript the call is cast to the `UnsafeUnwrapped` type the
36
+ * upgrade guide gives for temporary synchronous use; JavaScript still reads it synchronously as is.
37
+ *
38
+ * Before:
39
+ * ```tsx
40
+ * import { cookies } from 'next/headers'
41
+ *
42
+ * export default async function Page() {
43
+ * const token = cookies().get('token')
44
+ * }
45
+ * ```
46
+ *
47
+ * After:
48
+ * ```tsx
49
+ * import { cookies } from 'next/headers'
50
+ *
51
+ * export default async function Page() {
52
+ * const token = (await cookies()).get('token')
53
+ * }
54
+ * ```
55
+ *
56
+ * @see https://nextjs.org/docs/app/guides/upgrading/version-15#async-request-apis-breaking-change
57
+ */
58
+ export class AsyncRequestApis extends Recipe {
59
+ readonly name = "io.moderne.nextjs.15.async-request-apis";
60
+ readonly displayName: string = "Await `cookies`, `headers` and `draftMode`";
61
+ readonly description: string = "Next.js 15 made `cookies()`, `headers()` and `draftMode()` from `next/headers` asynchronous. " +
62
+ "Awaits each call in an async function, making a synchronous App Router page, layout or route handler async first. " +
63
+ "Elsewhere in synchronous TypeScript code, casts the call to its `UnsafeUnwrapped` type, the upgrade guide's temporary synchronous usage. " +
64
+ "Meant for projects on Next.js 15; run it through `UpgradeToNextjs15` when upgrading.";
65
+
66
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
67
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
68
+ /** The `next/headers` specifier as the file writes it, which an added import of it copies. */
69
+ private module!: J.Literal;
70
+ private toMakeAsync = new Set<string>();
71
+ private cu!: JS.CompilationUnit;
72
+
73
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
74
+ const marked = markUnfollowedImports(cu);
75
+ if (marked !== cu) cu = marked;
76
+ const module = headersSpecifier(cu);
77
+ if (!module) return cu;
78
+ this.module = module;
79
+ this.toMakeAsync = new Set();
80
+ this.cu = cu;
81
+ const c = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
82
+ const statements = await guardLeadingParentheses(c.statements, cu.statements, this.cursor);
83
+ return statements === c.statements ? c : {...c, statements} as JS.CompilationUnit;
84
+ }
85
+
86
+ override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
87
+ const b = await super.visitBlock(block, ctx) as J.Block;
88
+ const statements = await guardLeadingParentheses(b.statements, block.statements, this.cursor);
89
+ return statements === b.statements ? b : {...b, statements} as J.Block;
90
+ }
91
+
92
+ override async visitMethodDeclaration(method: J.MethodDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
93
+ const m = await super.visitMethodDeclaration(method, ctx) as J.MethodDeclaration;
94
+ return this.toMakeAsync.has(method.id) ? makeAsync(m) : m;
95
+ }
96
+
97
+ protected override async visitArrowFunction(arrow: JS.ArrowFunction, ctx: ExecutionContext): Promise<J | undefined> {
98
+ const a = await super.visitArrowFunction(arrow, ctx) as JS.ArrowFunction;
99
+ return this.toMakeAsync.has(arrow.id) ? makeAsync(a) : a;
100
+ }
101
+
102
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
103
+ const m = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
104
+ const typeName = REQUEST_APIS.find(([api]) => api.matches(m.methodType))?.[1];
105
+ if (!typeName) return m;
106
+
107
+ const parent = this.cursor.parentTree()?.value as J | undefined;
108
+ if (parent?.kind === JS.Kind.Await || isUnwrappingCast(parent)) return m;
109
+ if (this.awaitedByPromiseCombinator()) return m;
110
+
111
+ const cu = this.cu;
112
+ const fnCursor = enclosingFunction(this.cursor);
113
+ const fn = fnCursor?.value;
114
+ if (isFunctionLike(fn) && (isAsync(fn) || this.canMakeAsync(fnCursor!, cu))) {
115
+ if (!isAsync(fn)) this.toMakeAsync.add(fn.id);
116
+ const awaited = awaitOf(m);
117
+ return needsParentheses(this.cursor) ? parenthesize(awaited) : awaited;
118
+ }
119
+
120
+ if (!isTypeScript(cu)) return m;
121
+ const namespace = m.select && isIdentifier(m.select.element) ? m.select.element.simpleName : undefined;
122
+ if (!namespace) maybeBind(this, {module: this.module, member: typeName, typeOnly: true});
123
+ const type = namespace ? qualified(namespace, typeName) : identifier(typeName);
124
+ const cast = asType(asType(m, identifier('unknown')), type);
125
+ // `as` binds looser than any operator, so under one it needs parentheses to stay on the call.
126
+ return needsParentheses(this.cursor) || OPERATORS.has(parent?.kind ?? '') ? parenthesize(cast) : cast;
127
+ }
128
+
129
+ /** Whether the call is an element of `Promise.all([...])` or its siblings, which resolve it already. */
130
+ private awaitedByPromiseCombinator(): boolean {
131
+ const array = this.cursor.parentTree();
132
+ if (array?.value?.kind !== J.Kind.NewArray) return false;
133
+ const call = array.parentTree()?.value as J | undefined;
134
+ if (call?.kind !== J.Kind.MethodInvocation) return false;
135
+ const combinator = call as J.MethodInvocation;
136
+ const target = combinator.select?.element;
137
+ return isIdentifier(target) && target.simpleName === 'Promise' &&
138
+ PROMISE_COMBINATORS.has(combinator.name.simpleName);
139
+ }
140
+
141
+ /**
142
+ * A server entry Next.js calls and awaits: its default export, metadata functions and route
143
+ * handlers. One that calls hooks stays synchronous, since an async component cannot.
144
+ */
145
+ private canMakeAsync(fnCursor: Cursor, cu: JS.CompilationUnit): boolean {
146
+ if (!isServerFile(cu) || callsHooks(fnCursor.value as FunctionLike)) return false;
147
+ const name = exportedName(fnCursor, cu);
148
+ return name !== undefined && (name === 'default' || METADATA_FUNCTIONS.has(name) || HTTP_METHODS.has(name));
149
+ }
150
+ }());
151
+ }
152
+ }
153
+
154
+ const HEADERS_MODULE = 'next/headers';
155
+
156
+ /** Marks each `require` of `next/headers`, whose bindings the recipe does not follow. */
157
+ function markUnfollowedImports(cu: JS.CompilationUnit): JS.CompilationUnit {
158
+ const message = "Await `cookies()`, `headers()` and `draftMode()` where they are called, as Next.js 15 made them asynchronous; " +
159
+ "the recipe does not follow `require('next/headers')`.";
160
+ const unfollowed = (statement: J): boolean => {
161
+ if (statement.kind !== J.Kind.VariableDeclarations) return false;
162
+ if (statement.markers.markers.some(m => m.kind === MarkersKind.SearchResult)) return false;
163
+ return (statement as J.VariableDeclarations).variables.some(v => {
164
+ const init = v.element.initializer?.element;
165
+ if (init?.kind !== J.Kind.MethodInvocation || (init as J.MethodInvocation).select) return false;
166
+ const call = init as J.MethodInvocation;
167
+ const arg = call.arguments.elements[0]?.element;
168
+ return call.name.simpleName === 'require' && arg?.kind === J.Kind.Literal && (arg as J.Literal).value === HEADERS_MODULE;
169
+ });
170
+ };
171
+ if (!cu.statements.some(s => unfollowed(s.element))) return cu;
172
+ return {...cu, statements: cu.statements.map(s => unfollowed(s.element) ? {...s, element: foundSearchResult(s.element, message)} : s)} as JS.CompilationUnit;
173
+ }
174
+
175
+ function headersSpecifier(cu: JS.CompilationUnit): J.Literal | undefined {
176
+ for (const s of cu.statements) {
177
+ const module = s.element.kind === JS.Kind.Import ? (s.element as JS.Import).moduleSpecifier?.element : undefined;
178
+ if (module?.kind === J.Kind.Literal && (module as J.Literal).value === HEADERS_MODULE) return module as J.Literal;
179
+ }
180
+ return undefined;
181
+ }
182
+
183
+ /** Operators that would take a bare `x as T` operand with them. */
184
+ const OPERATORS = new Set<string>([J.Kind.Binary, J.Kind.Unary, JS.Kind.Binary, JS.Kind.TypeOf, JS.Kind.Void, JS.Kind.Delete]);
185
+
186
+ /** The `as unknown as UnsafeUnwrappedX` cast of the guide's temporary synchronous usage, which this recipe writes itself. */
187
+ function isUnwrappingCast(tree: J | undefined): boolean {
188
+ if (tree?.kind !== JS.Kind.As) return false;
189
+ const right = (tree as JS.As).right;
190
+ return isIdentifier(right) && (right.simpleName === 'unknown' || right.simpleName.startsWith('UnsafeUnwrapped'));
191
+ }
192
+
193
+ function asType(expression: J, type: J.Identifier | J.FieldAccess): JS.As {
194
+ return {
195
+ kind: JS.Kind.As,
196
+ id: randomId(),
197
+ prefix: expression.prefix,
198
+ markers: emptyMarkers,
199
+ left: rightPadded({...expression, prefix: emptySpace} as any, space(' ')),
200
+ right: {...type, prefix: space(' ')},
201
+ } as JS.As;
202
+ }
203
+
204
+ function qualified(namespace: string, member: string): J.FieldAccess {
205
+ return {
206
+ kind: J.Kind.FieldAccess,
207
+ id: randomId(),
208
+ prefix: emptySpace,
209
+ markers: emptyMarkers,
210
+ target: identifier(namespace),
211
+ name: {kind: J.Kind.LeftPadded, before: emptySpace, element: identifier(member), markers: emptyMarkers},
212
+ } as J.FieldAccess;
213
+ }
@@ -0,0 +1,141 @@
1
+ import {check, ExecutionContext, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS, namesDeclaredIn, Template} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J, Type} from "@openrewrite/rewrite/java";
4
+ import {isServerFile} from "./app-router";
5
+ import {appendProp, findProp, isObject, propName} from "../nextjs-config/next-config";
6
+ import {importedModule} from "../nextjs13/next-modules";
7
+
8
+ /** Headers that identify a user or a client: a response fetched with one must not be shared through the cache. */
9
+ const CREDENTIAL_HEADER = /auth|token|api[-_]?key|secret|cookie|session|credential/i;
10
+
11
+ /**
12
+ * True when the first argument is known to be a URL: a string literal, a template string, a concatenation, or an
13
+ * expression the type attribution says is a string or a `URL`. Anything else may be a `Request`, whose method and body
14
+ * the recipe cannot see, so the call is left alone.
15
+ */
16
+ function isUrlArgument(arg: any): boolean {
17
+ if (arg.kind === J.Kind.Literal || arg.kind === J.Kind.Binary || arg.kind === JS.Kind.TemplateExpression) return true;
18
+ const type = arg.type;
19
+ if (Type.isPrimitive(type)) return (type as any).keyword === 'String';
20
+ return Type.isOfTypeWithName(type, false, name => /(^|\.)(String|URL)$/.test(name));
21
+ }
22
+
23
+ /** Route segment configs that decide how every `fetch` of the file caches: forcing `force-cache` would override them. */
24
+ const SEGMENT_CONFIGS = new Set(['dynamic', 'revalidate', 'fetchCache']);
25
+
26
+ /**
27
+ * True when Next.js 14 may not have cached the file's `fetch` calls: a segment config decides it for the file, the
28
+ * file reads `cookies()` or `headers()`, after which Next.js 14 did not cache, or it opts out with `unstable_noStore`.
29
+ */
30
+ async function cachingDecidedElsewhere(cu: JS.CompilationUnit): Promise<boolean> {
31
+ for (const s of cu.statements) {
32
+ const st = s.element as any;
33
+ if (st.kind === JS.Kind.Import && importedModule(st) === 'next/cache' && await bindsName(st, 'unstable_noStore')) return true;
34
+ }
35
+ return cu.statements.some(s => {
36
+ const st = s.element as any;
37
+ if (st.kind === JS.Kind.Import) return importedModule(st) === 'next/headers';
38
+ return st.kind === J.Kind.VariableDeclarations && (st.modifiers ?? []).some((m: any) => m.keyword === 'export')
39
+ && st.variables.some((v: any) => isIdentifier(v.element.name) && SEGMENT_CONFIGS.has(v.element.name.simpleName));
40
+ });
41
+ }
42
+
43
+ /** True when an identifier called `name` appears in the tree (an import binding). Walks the tree: the nodes carry circular type attribution, so they cannot be serialized. */
44
+ async function bindsName(tree: J, name: string): Promise<boolean> {
45
+ let found = false;
46
+ await new class extends JavaScriptVisitor<ExecutionContext> {
47
+ override async visitIdentifier(id: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
48
+ if (id.simpleName === name) found = true;
49
+ return super.visitIdentifier(id, ctx);
50
+ }
51
+ }().visit(tree, new ExecutionContext());
52
+ return found;
53
+ }
54
+
55
+ /** True when the options object cannot take the default: not a plain GET, or already says how to cache. */
56
+ function hasExplicitCaching(options: J.NewClass): boolean {
57
+ const statements = options.body!.statements.map(s => s.element as any);
58
+ if (statements.some(s => s.kind !== JS.Kind.PropertyAssignment || propName(s) === undefined)) return true;
59
+ if (findProp(options, 'cache')) return true;
60
+ // Next.js 14 did not cache requests that carry credentials after a dynamic function, so forcing the cache could serve one user's response to another
61
+ const headers = findProp(options, 'headers');
62
+ if (headers) {
63
+ const value = headers.initializer as any;
64
+ if (!isObject(value)) return true;
65
+ if (value.body!.statements.some(s => propName(s.element) === undefined || CREDENTIAL_HEADER.test(propName(s.element)!))) return true;
66
+ }
67
+ if (findProp(options, 'body')) return true;
68
+ const method = findProp(options, 'method');
69
+ if (method) {
70
+ const value = method.initializer as any;
71
+ if (value?.kind !== J.Kind.Literal || typeof value.value !== 'string' || value.value.toUpperCase() !== 'GET') return true;
72
+ }
73
+ const next = findProp(options, 'next');
74
+ if (next) {
75
+ const value = next.initializer as any;
76
+ if (!isObject(value)) return true;
77
+ const inner = value.body!.statements.map(s => s.element as any);
78
+ if (inner.some(s => s.kind !== JS.Kind.PropertyAssignment || propName(s) === 'revalidate')) return true;
79
+ }
80
+ return false;
81
+ }
82
+
83
+ /** Finds the object literal inside a template result. */
84
+ function objectIn(tree: any): J.NewClass | undefined {
85
+ let t = tree;
86
+ for (let i = 0; t && i < 6 && !isObject(t); i++) t = t.expression ?? t.tree?.element ?? t.statements?.[0]?.element ?? t.initializer;
87
+ return isObject(t) ? t : undefined;
88
+ }
89
+
90
+ /**
91
+ * Changed: calls to the global `fetch` in the server files of the App Router (`page`, `layout`, `route`, `default`,
92
+ * `template`, `loading`, `not-found`, `sitemap`, `robots`, `manifest` and the metadata image files)
93
+ * without a `'use client'` directive, with one argument or an object literal of options, when the request is a GET
94
+ * (no `method`, or `'GET'`) and the options have no `cache` and no `next.revalidate`.
95
+ *
96
+ * Left alone: files that export the segment configs `dynamic`, `revalidate` or `fetchCache`, import `next/headers` or `unstable_noStore`,
97
+ * since Next.js 14 did not cache a `fetch` there by default.
98
+ *
99
+ * Not handled: a `fetch` that is imported or declared in the file, `globalThis.fetch`, a first argument that is not known to be a URL
100
+ * (a `Request`, or an expression without a string or `URL` type),
101
+ * a variable as the options, options with a spread, shorthand or computed keys, and `fetch` in other modules, such as helpers below `app/` or outside it.
102
+ * Calls with a header that looks like a credential (names containing auth, token, api key, secret, cookie or session) are left alone.
103
+ *
104
+ * @see https://nextjs.org/docs/app/guides/upgrading/version-15#fetch-requests
105
+ */
106
+ export class FetchCacheDefaults extends Recipe {
107
+ readonly name = "io.moderne.nextjs.15.fetch-cache-defaults";
108
+ readonly displayName = "Keep the Next.js 14 caching default of `fetch`";
109
+ readonly description = "Next.js 15 no longer caches `fetch` by default. Adds `cache: 'force-cache'` to GET `fetch` calls in App Router server files that do not say how to cache, so they keep the Next.js 14 behavior. Calls with a `cache` or `next.revalidate` option, other methods, spread options and a locally declared `fetch` are left alone, and so are files with a `dynamic`, `revalidate` or `fetchCache` segment config, a `next/headers` import, or an `unstable_noStore` import from `next/cache`.";
110
+
111
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
112
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
113
+ private active = false;
114
+
115
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
116
+ this.active = isServerFile(cu) && !(await cachingDecidedElsewhere(cu)) && !namesDeclaredIn(cu).has('fetch');
117
+ return this.active ? super.visitJsCompilationUnit(cu, ctx) : cu;
118
+ }
119
+
120
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
121
+ const m = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
122
+ if (!this.active || m.select || m.name.simpleName !== 'fetch') return m;
123
+ const args = m.arguments.elements.map(e => e.element).filter(e => e.kind !== J.Kind.Empty);
124
+ if (args.length === 0 || args.length > 2 || !isUrlArgument(args[0])) return m;
125
+ if (args.length === 1) {
126
+ const result = await Template.builder().code("fetch(").param(args[0]).code(", { cache: 'force-cache' })").build().apply(m, this.cursor);
127
+ return result ? {...result, prefix: m.prefix} as J : m;
128
+ }
129
+ const options = args[1];
130
+ if (!isObject(options) || hasExplicitCaching(options)) return m;
131
+ const sample = objectIn(await Template.builder().code("({ cache: 'force-cache' })").build().apply(m, this.cursor));
132
+ const prop = sample && findProp(sample, 'cache');
133
+ if (!sample || !prop) return m;
134
+ const edited = options.body!.statements.length === 0
135
+ ? {...options, body: {...options.body!, statements: sample.body!.statements}} as J.NewClass
136
+ : appendProp(options, prop);
137
+ return {...m, arguments: {...m.arguments, elements: m.arguments.elements.map(e => e.element === options ? {...e, element: edited} : e)}} as J.MethodInvocation;
138
+ }
139
+ });
140
+ }
141
+ }
@@ -0,0 +1,49 @@
1
+ import {check, ExecutionContext, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS, maybeBind, Template} from "@openrewrite/rewrite/javascript";
3
+ import {J, Type} from "@openrewrite/rewrite/java";
4
+
5
+ /** `NextRequest` property to the `@vercel/functions` helper that replaces it. */
6
+ const HELPERS = new Map<string, string>([['geo', 'geolocation'], ['ip', 'ipAddress']]);
7
+
8
+ function readsGeoOrIp(fieldAccess: J.FieldAccess): boolean {
9
+ return HELPERS.has(fieldAccess.name.element.simpleName) &&
10
+ Type.isOfTypeWithName((fieldAccess.target as any).type, false, name => name === 'next.NextRequest');
11
+ }
12
+
13
+ /** True when {@link NextRequestGeoIp} would rewrite a read of `geo` or `ip` in the file, so that it imports `@vercel/functions`. */
14
+ export async function usesRequestGeoIp(cu: JS.CompilationUnit): Promise<boolean> {
15
+ let found = false;
16
+ await new class extends JavaScriptVisitor<ExecutionContext> {
17
+ override async visitFieldAccess(fieldAccess: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
18
+ if (readsGeoOrIp(fieldAccess)) found = true;
19
+ return super.visitFieldAccess(fieldAccess, ctx);
20
+ }
21
+ }().visit(cu, new ExecutionContext());
22
+ return found;
23
+ }
24
+
25
+ /**
26
+ * Handled: property reads on any expression whose type is `NextRequest`, including `request.geo?.country`. Not handled:
27
+ * untyped requests, as in JavaScript files, and destructuring (`const { geo } = request`).
28
+ *
29
+ * @see https://nextjs.org/docs/app/guides/upgrading/version-15#nextrequest-geolocation
30
+ */
31
+ export class NextRequestGeoIp extends Recipe {
32
+ readonly name = "io.moderne.nextjs.15.next-request-geo-ip";
33
+ readonly displayName = "Replace `request.geo` and `request.ip` with `@vercel/functions`";
34
+ readonly description = "Next.js 15 removed `geo` and `ip` from `NextRequest`. Replaces reads of them with `geolocation(request)` and `ipAddress(request)` from `@vercel/functions` and adds the import. It does not add the `@vercel/functions` dependency to `package.json`.";
35
+
36
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
37
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
38
+ override async visitFieldAccess(fieldAccess: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
39
+ const f = await super.visitFieldAccess(fieldAccess, ctx) as J.FieldAccess;
40
+ if (!readsGeoOrIp(f)) return f;
41
+ const helper = HELPERS.get(f.name.element.simpleName)!;
42
+ const result = await Template.builder().code(`${helper}(`).param(f.target).code(')').build().apply(f, this.cursor);
43
+ if (!result) return f;
44
+ maybeBind(this, {module: '@vercel/functions', member: helper});
45
+ return {...result, prefix: f.prefix} as J;
46
+ }
47
+ });
48
+ }
49
+ }
@@ -0,0 +1,189 @@
1
+ import {and, check, ExecutionContext, foundSearchResult, MarkersKind, not, randomId, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {hasSourcePath, isVendoredOrBundled, JavaScriptVisitor, JS, namesUsedWithin, Template} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
+ import {importedModule, importedNames} from "../nextjs13/next-modules";
5
+ import {HTTP_METHODS, pathInAppDir} from "./app-router";
6
+
7
+ const ROUTE_FILE = /^(?:[^/]+\/)*route\.[cm]?[jt]s$/;
8
+
9
+ /** Names a top-level statement declares and exports, with the declaration. */
10
+ function exported(statement: any): { name: string; node: any }[] {
11
+ const exports = (statement.modifiers ?? []).some((m: any) => m.keyword === 'export');
12
+ if (!exports) return [];
13
+ if (statement.kind === J.Kind.MethodDeclaration) return [{name: statement.name.simpleName, node: statement}];
14
+ if (statement.kind === J.Kind.VariableDeclarations) {
15
+ return statement.variables.filter((v: any) => isIdentifier(v.element.name))
16
+ .map((v: any) => ({name: v.element.name.simpleName, node: v.element.initializer?.element}));
17
+ }
18
+ return [];
19
+ }
20
+
21
+ function parametersOf(fn: any): any[] | undefined {
22
+ const list = fn?.parameters?.elements ?? fn?.lambda?.parameters?.parameters;
23
+ return list?.map((e: any) => e.element ?? e).filter((e: any) => e.kind !== J.Kind.Empty);
24
+ }
25
+
26
+ /** Every identifier a tree holds, which for an import clause or a binding pattern is the names it binds. */
27
+ async function identifiersOf(tree: any, names: Set<string>): Promise<void> {
28
+ await new class extends JavaScriptVisitor<undefined> {
29
+ protected override async visitIdentifier(identifier: J.Identifier): Promise<J | undefined> {
30
+ names.add(identifier.simpleName);
31
+ return identifier;
32
+ }
33
+ }().visit(tree, undefined);
34
+ }
35
+
36
+ /** The module a `require('...')` call loads, also under an `await`. */
37
+ function requiredModule(initializer: any): string | undefined {
38
+ const call = initializer?.kind === JS.Kind.Await ? initializer.expression : initializer;
39
+ if (call?.kind !== J.Kind.MethodInvocation || call.select || call.name?.simpleName !== 'require') return undefined;
40
+ const first = call.arguments?.elements?.[0]?.element;
41
+ return first?.kind === J.Kind.Literal && typeof first.value === 'string' ? first.value : undefined;
42
+ }
43
+
44
+ /**
45
+ * The names the imports of a file bind, as local names: `import` declarations and `const x = require('...')`, including
46
+ * destructuring. An imported name that is renamed counts under both spellings.
47
+ */
48
+ async function importedBindings(cu: JS.CompilationUnit): Promise<Set<string>> {
49
+ const names = new Set<string>();
50
+ for (const statement of cu.statements.map(s => s.element as any)) {
51
+ if (statement.kind === JS.Kind.Import) {
52
+ if (importedModule(statement) !== 'next/server') await identifiersOf(statement, names);
53
+ } else if (statement.kind === J.Kind.VariableDeclarations) {
54
+ for (const v of statement.variables) {
55
+ const module = requiredModule(v.element.initializer?.element);
56
+ if (module !== undefined && module !== 'next/server') await identifiersOf(v.element.name, names);
57
+ }
58
+ }
59
+ }
60
+ return names;
61
+ }
62
+
63
+ /** The identifier a call chain starts from: `a` for `a.b().c`, or the name of a call without a target. */
64
+ function rootOf(expression: any): string | undefined {
65
+ let node = expression;
66
+ for (let i = 0; node && i < 100; i++) {
67
+ if (isIdentifier(node)) return node.simpleName;
68
+ if (node.kind === J.Kind.MethodInvocation) {
69
+ if (!node.select) return node.name?.simpleName;
70
+ node = node.select.element ?? node.select;
71
+ } else if (node.kind === J.Kind.FieldAccess) node = node.target?.element ?? node.target;
72
+ else if (node.kind === J.Kind.Parentheses) node = node.tree?.element ?? node.tree;
73
+ else return undefined;
74
+ }
75
+ return undefined;
76
+ }
77
+
78
+ /**
79
+ * True when the file calls, or constructs, something it imports, apart from `next/server`. Such a call can read
80
+ * `cookies()` or `headers()` out of sight, which made the handler dynamic in Next.js 14.
81
+ */
82
+ async function callsImportedCode(cu: JS.CompilationUnit): Promise<boolean> {
83
+ const imported = await importedBindings(cu);
84
+ let found = false;
85
+ const visitor = new class extends JavaScriptVisitor<undefined> {
86
+ protected override async visitMethodInvocation(call: J.MethodInvocation, p: undefined): Promise<J | undefined> {
87
+ const root = rootOf(call);
88
+ if (root && imported.has(root)) found = true;
89
+ // import('./session') loads code the file may call later, under a name this scan does not follow
90
+ if (!call.select && root === 'import') found = true;
91
+ return super.visitMethodInvocation(call, p);
92
+ }
93
+
94
+ protected override async visitFunctionCall(call: JS.FunctionCall, p: undefined): Promise<J | undefined> {
95
+ const callee = (call.function as any)?.element;
96
+ if (isIdentifier(callee) && callee.simpleName === 'import') found = true;
97
+ return super.visitFunctionCall(call, p);
98
+ }
99
+
100
+ protected override async visitNewClass(newClass: J.NewClass, p: undefined): Promise<J | undefined> {
101
+ const root = rootOf((newClass as any).class?.element ?? (newClass as any).class);
102
+ if (root && imported.has(root)) found = true;
103
+ return super.visitNewClass(newClass, p);
104
+ }
105
+ }();
106
+ for (const statement of cu.statements.map(s => s.element as any)) {
107
+ if (statement.kind !== JS.Kind.Import) await visitor.visit(statement, undefined);
108
+ }
109
+ return found;
110
+ }
111
+
112
+ const NOT_MIGRATED = "Next.js 15 no longer prerenders this `GET` route handler. This file calls code it imports, which may read " +
113
+ "cookies or headers, so `export const dynamic = 'force-static'` was not added. Add it if the handler keeps the same response " +
114
+ "for every request.";
115
+
116
+ /** Marks the `GET` handler that was left alone because the file calls imported code. */
117
+ function markNotMigrated(cu: JS.CompilationUnit): JS.CompilationUnit {
118
+ const handler = cu.statements.find(s => exported(s.element).some(n => n.name === 'GET'));
119
+ if (!handler) return cu;
120
+ // A second cycle sees the marker of the first, and adding it again would change the tree without changing the source
121
+ if ((handler.element as any).markers.markers.some((m: any) => m.kind === MarkersKind.SearchResult && m.description === NOT_MIGRATED)) return cu;
122
+ return {...cu, statements: cu.statements.map(s => s === handler ? {...s, element: foundSearchResult(s.element as any, NOT_MIGRATED)} : s)} as JS.CompilationUnit;
123
+ }
124
+
125
+ /** True when the handler is a function that does not read its first argument. */
126
+ async function ignoresRequest(handler: any): Promise<boolean> {
127
+ const kind = handler?.kind;
128
+ if (kind !== J.Kind.MethodDeclaration && kind !== JS.Kind.ArrowFunction) return false;
129
+ const params = parametersOf(handler);
130
+ if (!params) return false;
131
+ if (params.length === 0) return true;
132
+ const first = params[0];
133
+ const name = first.kind === J.Kind.VariableDeclarations && first.variables.length === 1 ? first.variables[0].element.name : undefined;
134
+ if (!name || !isIdentifier(name)) return false;
135
+ const body = kind === J.Kind.MethodDeclaration ? handler.body : handler.lambda?.body;
136
+ return !!body && !namesUsedWithin(body).has(name.simpleName);
137
+ }
138
+
139
+ /**
140
+ * Changed: `app/**\/route.{js,ts}` files that export `GET` as a function or an arrow function whose first parameter is
141
+ * absent or never used, that export no other HTTP method, no `dynamic`, `revalidate` or `fetchCache`, and no `runtime` other than `'nodejs'`, that import neither `next/headers` nor `unstable_noStore`, that call nothing they import apart from `next/server` (a helper may read the request; such a `GET` is marked instead), and, in a dynamic
142
+ * segment such as `[id]`, that export `generateStaticParams`.
143
+ *
144
+ * Not handled: a `GET` that is re-exported or wrapped in another function, handlers that read the request through
145
+ * `arguments`, other dynamic APIs that make a handler dynamic in Next.js 14 (`NextResponse.next`, a `Response` built from
146
+ * the request URL elsewhere), and an imported helper that is passed on or aliased without being called
147
+ * (`items.map(getSession)`, `const load = getSession`), which the check for calls into imported code does not follow.
148
+ *
149
+ * @see https://nextjs.org/docs/app/guides/upgrading/version-15#route-handlers
150
+ */
151
+ export class RouteHandlerCacheDefaults extends Recipe {
152
+ readonly name = "io.moderne.nextjs.15.route-handler-cache-defaults";
153
+ readonly displayName = "Keep static `GET` route handlers static";
154
+ readonly description = "Next.js 15 no longer prerenders `GET` route handlers by default. Adds `export const dynamic = 'force-static'` to a `GET` handler that does not read the request and uses no `next/headers` or `unstable_noStore` and calls no imported code other than `next/server`, since a helper could read cookies or headers (such a handler gets a marker instead), so it keeps the Next.js 14 behavior. Files that export another HTTP method, a `runtime` other than `'nodejs'` or a `fetchCache` segment config are left alone.";
155
+
156
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
157
+ return check(and(hasSourcePath("**/route.{js,cjs,mjs,ts,cts,mts}"), not(isVendoredOrBundled())), new class extends JavaScriptVisitor<ExecutionContext> {
158
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
159
+ if (!ROUTE_FILE.test(pathInAppDir(cu.sourcePath) ?? '')) return cu;
160
+ const statements = cu.statements.map(s => s.element as any);
161
+ if (statements.some(s => s.kind === JS.Kind.Import && importedModule(s) === 'next/headers')) return cu;
162
+ if (statements.some(s => s.kind === JS.Kind.Import && importedModule(s) === 'next/cache' && importedNames(s as JS.Import).includes('unstable_noStore'))) return cu;
163
+ const names = statements.flatMap(exported);
164
+ // Next.js 14 prerendered a dynamic segment only when generateStaticParams listed its values
165
+ if (cu.sourcePath.includes('[') && !names.some(n => n.name === 'generateStaticParams')) return cu;
166
+ if (names.some(n => n.name === 'dynamic' || n.name === 'revalidate' || n.name === 'fetchCache')) return cu;
167
+ // Next.js 14 evaluated a handler dynamically where the file exports another method, and did not prerender one of the edge runtime
168
+ if (names.some(n => HTTP_METHODS.has(n.name) && n.name !== 'GET')) return cu;
169
+ if (names.some(n => n.name === 'runtime' && n.node?.value !== 'nodejs')) return cu;
170
+ const get = names.find(n => n.name === 'GET');
171
+ if (!get || !(await ignoresRequest(get.node))) return cu;
172
+ // Next.js 14 made the handler dynamic where a helper it calls reads the request, and nothing here sees into one
173
+ if (await callsImportedCode(cu)) return markNotMigrated(cu);
174
+ const imports = cu.statements.map((s, i) => s.element.kind === JS.Kind.Import ? i : -1);
175
+ const at = Math.max(...imports) + 1;
176
+ const declaration = await Template.builder().code("export const dynamic = 'force-static';").build().apply(cu, this.cursor) as any;
177
+ const added = declaration?.statements?.find((s: any) => exported(s.element ?? s).some(n => n.name === 'dynamic'))
178
+ ?? (declaration?.kind === J.Kind.VariableDeclarations ? {element: declaration} : undefined);
179
+ if (!added) return cu;
180
+ const first = cu.statements[at] ?? cu.statements[at - 1];
181
+ const element = {...(added.element ?? added), prefix: {...first.element.prefix, whitespace: at === 0 ? '' : '\n\n', comments: []}};
182
+ const list = [...cu.statements];
183
+ list.splice(at, 0, {...first, element, markers: {...first.markers, markers: [{kind: J.Markers.Semicolon, id: randomId()}]}} as any);
184
+ if (at === 0 && list[1]) list[1] = {...list[1], element: {...list[1].element, prefix: {...list[1].element.prefix, whitespace: '\n\n'}}};
185
+ return {...cu, statements: list} as JS.CompilationUnit;
186
+ }
187
+ });
188
+ }
189
+ }