@openrewrite/recipes-react 0.31.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.
- package/dist/index.d.ts +37 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +146 -2
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/shared.d.ts +2 -8
- package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/shared.js +21 -53
- package/dist/migration/cra-to-vite/shared.js.map +1 -1
- package/dist/nextjs-config/config-recipes.d.ts +90 -0
- package/dist/nextjs-config/config-recipes.d.ts.map +1 -0
- package/dist/nextjs-config/config-recipes.js +222 -0
- package/dist/nextjs-config/config-recipes.js.map +1 -0
- package/dist/nextjs-config/next-config.d.ts +25 -0
- package/dist/nextjs-config/next-config.d.ts.map +1 -0
- package/dist/nextjs-config/next-config.js +199 -0
- package/dist/nextjs-config/next-config.js.map +1 -0
- package/dist/nextjs-search/find-nextjs-projects-below.d.ts +37 -0
- package/dist/nextjs-search/find-nextjs-projects-below.d.ts.map +1 -0
- package/dist/nextjs-search/find-nextjs-projects-below.js +196 -0
- package/dist/nextjs-search/find-nextjs-projects-below.js.map +1 -0
- package/dist/nextjs-search/find-nextjs-upgrade-issues.d.ts +18 -0
- package/dist/nextjs-search/find-nextjs-upgrade-issues.d.ts.map +1 -0
- package/dist/nextjs-search/find-nextjs-upgrade-issues.js +269 -0
- package/dist/nextjs-search/find-nextjs-upgrade-issues.js.map +1 -0
- package/dist/nextjs-search/find-pages-router-candidates.d.ts +14 -0
- package/dist/nextjs-search/find-pages-router-candidates.d.ts.map +1 -0
- package/dist/nextjs-search/find-pages-router-candidates.js +136 -0
- package/dist/nextjs-search/find-pages-router-candidates.js.map +1 -0
- package/dist/nextjs-search/mark-pending-nextjs-upgrade.d.ts +16 -0
- package/dist/nextjs-search/mark-pending-nextjs-upgrade.d.ts.map +1 -0
- package/dist/nextjs-search/mark-pending-nextjs-upgrade.js +125 -0
- package/dist/nextjs-search/mark-pending-nextjs-upgrade.js.map +1 -0
- package/dist/nextjs13/new-link.d.ts +8 -0
- package/dist/nextjs13/new-link.d.ts.map +1 -0
- package/dist/nextjs13/new-link.js +82 -0
- package/dist/nextjs13/new-link.js.map +1 -0
- package/dist/nextjs13/next-image-to-legacy-image.d.ts +8 -0
- package/dist/nextjs13/next-image-to-legacy-image.d.ts.map +1 -0
- package/dist/nextjs13/next-image-to-legacy-image.js +103 -0
- package/dist/nextjs13/next-image-to-legacy-image.js.map +1 -0
- package/dist/nextjs13/next-modules.d.ts +18 -0
- package/dist/nextjs13/next-modules.d.ts.map +1 -0
- package/dist/nextjs13/next-modules.js +127 -0
- package/dist/nextjs13/next-modules.js.map +1 -0
- package/dist/nextjs14/metadata-to-viewport-export.d.ts +8 -0
- package/dist/nextjs14/metadata-to-viewport-export.d.ts.map +1 -0
- package/dist/nextjs14/metadata-to-viewport-export.js +223 -0
- package/dist/nextjs14/metadata-to-viewport-export.js.map +1 -0
- package/dist/nextjs14/next-og-import.d.ts +8 -0
- package/dist/nextjs14/next-og-import.d.ts.map +1 -0
- package/dist/nextjs14/next-og-import.js +29 -0
- package/dist/nextjs14/next-og-import.js.map +1 -0
- package/dist/nextjs15/add-vercel-functions.d.ts +17 -0
- package/dist/nextjs15/add-vercel-functions.d.ts.map +1 -0
- package/dist/nextjs15/add-vercel-functions.js +86 -0
- package/dist/nextjs15/add-vercel-functions.js.map +1 -0
- package/dist/nextjs15/app-dir-runtime-config-experimental-edge.d.ts +11 -0
- package/dist/nextjs15/app-dir-runtime-config-experimental-edge.d.ts.map +1 -0
- package/dist/nextjs15/app-dir-runtime-config-experimental-edge.js +62 -0
- package/dist/nextjs15/app-dir-runtime-config-experimental-edge.js.map +1 -0
- package/dist/nextjs15/app-router.d.ts +26 -0
- package/dist/nextjs15/app-router.d.ts.map +1 -0
- package/dist/nextjs15/app-router.js +302 -0
- package/dist/nextjs15/app-router.js.map +1 -0
- package/dist/nextjs15/async-params.d.ts +8 -0
- package/dist/nextjs15/async-params.d.ts.map +1 -0
- package/dist/nextjs15/async-params.js +484 -0
- package/dist/nextjs15/async-params.js.map +1 -0
- package/dist/nextjs15/async-request-apis.d.ts +8 -0
- package/dist/nextjs15/async-request-apis.d.ts.map +1 -0
- package/dist/nextjs15/async-request-apis.js +204 -0
- package/dist/nextjs15/async-request-apis.js.map +1 -0
- package/dist/nextjs15/fetch-cache-defaults.d.ts +8 -0
- package/dist/nextjs15/fetch-cache-defaults.d.ts.map +1 -0
- package/dist/nextjs15/fetch-cache-defaults.js +160 -0
- package/dist/nextjs15/fetch-cache-defaults.js.map +1 -0
- package/dist/nextjs15/next-request-geo-ip.d.ts +10 -0
- package/dist/nextjs15/next-request-geo-ip.d.ts.map +1 -0
- package/dist/nextjs15/next-request-geo-ip.js +71 -0
- package/dist/nextjs15/next-request-geo-ip.js.map +1 -0
- package/dist/nextjs15/route-handler-cache-defaults.d.ts +8 -0
- package/dist/nextjs15/route-handler-cache-defaults.d.ts.map +1 -0
- package/dist/nextjs15/route-handler-cache-defaults.js +231 -0
- package/dist/nextjs15/route-handler-cache-defaults.js.map +1 -0
- package/dist/nextjs16/middleware-to-proxy.d.ts +16 -0
- package/dist/nextjs16/middleware-to-proxy.d.ts.map +1 -0
- package/dist/nextjs16/middleware-to-proxy.js +159 -0
- package/dist/nextjs16/middleware-to-proxy.js.map +1 -0
- package/dist/nextjs16/next-lint-to-eslint.d.ts +9 -0
- package/dist/nextjs16/next-lint-to-eslint.d.ts.map +1 -0
- package/dist/nextjs16/next-lint-to-eslint.js +60 -0
- package/dist/nextjs16/next-lint-to-eslint.js.map +1 -0
- package/dist/nextjs16/remove-experimental-ppr-config.d.ts +9 -0
- package/dist/nextjs16/remove-experimental-ppr-config.d.ts.map +1 -0
- package/dist/nextjs16/remove-experimental-ppr-config.js +17 -0
- package/dist/nextjs16/remove-experimental-ppr-config.js.map +1 -0
- package/dist/nextjs16/remove-experimental-ppr.d.ts +8 -0
- package/dist/nextjs16/remove-experimental-ppr.d.ts.map +1 -0
- package/dist/nextjs16/remove-experimental-ppr.js +67 -0
- package/dist/nextjs16/remove-experimental-ppr.js.map +1 -0
- package/dist/nextjs16/revalidate-tag-profile.d.ts +8 -0
- package/dist/nextjs16/revalidate-tag-profile.d.ts.map +1 -0
- package/dist/nextjs16/revalidate-tag-profile.js +46 -0
- package/dist/nextjs16/revalidate-tag-profile.js.map +1 -0
- package/dist/nextjs16/stable-cache-apis.d.ts +8 -0
- package/dist/nextjs16/stable-cache-apis.d.ts.map +1 -0
- package/dist/nextjs16/stable-cache-apis.js +29 -0
- package/dist/nextjs16/stable-cache-apis.js.map +1 -0
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +50 -13
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/util/java-recipe-proxy.d.ts +1 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -1
- package/dist/util/java-recipe-proxy.js +8 -5
- package/dist/util/java-recipe-proxy.js.map +1 -1
- package/dist/util/package-json.d.ts +11 -0
- package/dist/util/package-json.d.ts.map +1 -0
- package/dist/util/package-json.js +46 -0
- package/dist/util/package-json.js.map +1 -0
- package/package.json +2 -2
- package/src/index.ts +123 -0
- package/src/migration/cra-to-vite/shared.ts +3 -42
- package/src/nextjs-config/config-recipes.ts +219 -0
- package/src/nextjs-config/next-config.ts +190 -0
- package/src/nextjs-search/find-nextjs-projects-below.ts +216 -0
- package/src/nextjs-search/find-nextjs-upgrade-issues.ts +225 -0
- package/src/nextjs-search/find-pages-router-candidates.ts +110 -0
- package/src/nextjs-search/mark-pending-nextjs-upgrade.ts +131 -0
- package/src/nextjs13/new-link.ts +57 -0
- package/src/nextjs13/next-image-to-legacy-image.ts +71 -0
- package/src/nextjs13/next-modules.ts +93 -0
- package/src/nextjs14/metadata-to-viewport-export.ts +224 -0
- package/src/nextjs14/next-og-import.ts +19 -0
- package/src/nextjs15/add-vercel-functions.ts +78 -0
- package/src/nextjs15/app-dir-runtime-config-experimental-edge.ts +38 -0
- package/src/nextjs15/app-router.ts +316 -0
- package/src/nextjs15/async-params.ts +487 -0
- package/src/nextjs15/async-request-apis.ts +213 -0
- package/src/nextjs15/fetch-cache-defaults.ts +141 -0
- package/src/nextjs15/next-request-geo-ip.ts +49 -0
- package/src/nextjs15/route-handler-cache-defaults.ts +189 -0
- package/src/nextjs16/middleware-to-proxy.ts +146 -0
- package/src/nextjs16/next-lint-to-eslint.ts +43 -0
- package/src/nextjs16/remove-experimental-ppr-config.ts +15 -0
- package/src/nextjs16/remove-experimental-ppr.ts +39 -0
- package/src/nextjs16/revalidate-tag-profile.ts +28 -0
- package/src/nextjs16/stable-cache-apis.ts +20 -0
- package/src/react19/replace-default-props.ts +65 -27
- package/src/util/java-recipe-proxy.ts +9 -3
- package/src/util/package-json.ts +43 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import {check, Cursor, ExecutionContext, or, SourceFile, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {Json} from "@openrewrite/rewrite/json";
|
|
3
|
+
import {JS} from "@openrewrite/rewrite/javascript";
|
|
4
|
+
import {JavaDependencyRecipe, manifestTrees, treesOfType} from "../util/java-recipe-proxy";
|
|
5
|
+
import {dirName, isPackageJson, nearestRoot} from "../util/package-json";
|
|
6
|
+
import {usesRequestGeoIp} from "./next-request-geo-ip";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Replacing those reads writes `import {ipAddress} from "@vercel/functions"` into a file, so a project without the package
|
|
10
|
+
* no longer builds. A recipe cannot see another recipe's edit, so this one predicts it while it scans: a source file that
|
|
11
|
+
* reads `geo` or `ip` of a `NextRequest` (the same test the rewrite applies) marks the nearest `package.json`, and only
|
|
12
|
+
* those manifests go to `AddDependency`, which declines the edit where the package manager rejects it and leaves a
|
|
13
|
+
* package that already declares `@vercel/functions` alone.
|
|
14
|
+
*
|
|
15
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/version-15#nextrequest-geolocation
|
|
16
|
+
*/
|
|
17
|
+
export class AddVercelFunctions extends JavaDependencyRecipe {
|
|
18
|
+
readonly name = "io.moderne.nextjs.15.add-vercel-functions";
|
|
19
|
+
readonly displayName = "Add `@vercel/functions` where `request.geo` and `request.ip` are replaced";
|
|
20
|
+
readonly description = "Adds the `@vercel/functions` dependency to a package with a source file that reads `geo` or `ip` of a `NextRequest`, which Next.js 15 no longer provides and the helpers of that package replace. Packages that do not use either property, and packages that already declare it, are left alone.";
|
|
21
|
+
|
|
22
|
+
/** The source files, by path, that read `geo` or `ip` of a `NextRequest`. Mutated in place, as copies of a prepared recipe share it. */
|
|
23
|
+
private readonly users = new Set<string>();
|
|
24
|
+
|
|
25
|
+
/** Every `package.json` seen while scanning, held back from `AddDependency` until the packages that need the dependency are known. */
|
|
26
|
+
private readonly manifests: Json.Document[] = [];
|
|
27
|
+
|
|
28
|
+
constructor() {
|
|
29
|
+
super("org.openrewrite.javascript.AddDependency", {packageName: "@vercel/functions", version: "^3.0.0"});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
override initialValue(): number {
|
|
33
|
+
this.users.clear();
|
|
34
|
+
this.manifests.length = 0;
|
|
35
|
+
return super.initialValue();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
protected override scanned(manifest: SourceFile): boolean {
|
|
39
|
+
if (manifest.kind !== Json.Kind.Document || !isPackageJson(manifest.sourcePath.replace(/\\/g, "/"))) return true;
|
|
40
|
+
this.manifests.push(manifest as Json.Document);
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The manifests of the packages that hold a user of the helpers. A file belongs to the nearest `package.json` above it. */
|
|
45
|
+
needing(): Json.Document[] {
|
|
46
|
+
const roots = new Set(this.manifests.map(manifest => dirName(manifest.sourcePath.replace(/\\/g, "/"))));
|
|
47
|
+
const needed = new Set([...this.users].map(path => nearestRoot(roots, path)).filter((root): root is string => root !== undefined));
|
|
48
|
+
return this.manifests.filter(manifest => needed.has(dirName(manifest.sourcePath.replace(/\\/g, "/"))));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
override async scanner(acc: number): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
52
|
+
const manifests = await super.scanner(acc);
|
|
53
|
+
const users = this.users;
|
|
54
|
+
const scan = new class extends TreeVisitor<any, ExecutionContext> {
|
|
55
|
+
override async isAcceptable(sourceFile: SourceFile, ctx: ExecutionContext): Promise<boolean> {
|
|
56
|
+
return sourceFile.kind === JS.Kind.CompilationUnit || await manifests.isAcceptable(sourceFile, ctx);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
|
|
60
|
+
if (tree.kind !== JS.Kind.CompilationUnit) return await manifests.visit(tree, ctx, parent) as R | undefined;
|
|
61
|
+
const cu = tree as JS.CompilationUnit;
|
|
62
|
+
if (await usesRequestGeoIp(cu)) users.add(cu.sourcePath.replace(/\\/g, "/"));
|
|
63
|
+
return tree as R;
|
|
64
|
+
}
|
|
65
|
+
}();
|
|
66
|
+
// HACK: the host infers which trees to send only from a typed visitor, and sends a plain TreeVisitor every tree
|
|
67
|
+
return check(or(manifestTrees(), treesOfType("org.openrewrite.javascript.tree.JS")), scan);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// NOTE: `AddDependency` scans only the manifests it is given and then edits exactly those, so the others never reach it
|
|
71
|
+
override async generate(acc: number, ctx: ExecutionContext) {
|
|
72
|
+
const scanner = await this.java.scanner(acc);
|
|
73
|
+
const needed = this.needing();
|
|
74
|
+
for (const manifest of needed) await scanner.visit(manifest, ctx);
|
|
75
|
+
this.manifests.splice(0, this.manifests.length, ...needed);
|
|
76
|
+
return super.generate(acc, ctx);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import {check, ExecutionContext, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isVendoredOrBundled, JavaScriptVisitor, JS, withStringValue} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {pathInAppDir} from "./app-router";
|
|
5
|
+
|
|
6
|
+
const SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
|
|
7
|
+
|
|
8
|
+
/** The script files of the App Router folder, `app` or `src/app`, as a matcher on a source path. */
|
|
9
|
+
export const APP_DIR_FILE = {test: (sourcePath: string): boolean => SCRIPT_FILE.test(sourcePath) && pathInAppDir(sourcePath) !== undefined};
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/codemods#app-dir-runtime-config-experimental-edge
|
|
13
|
+
*/
|
|
14
|
+
export class AppDirRuntimeConfigExperimentalEdge extends Recipe {
|
|
15
|
+
readonly name = "io.moderne.nextjs.15.app-dir-runtime-config-experimental-edge";
|
|
16
|
+
readonly displayName = "Use the `edge` runtime in App Router files";
|
|
17
|
+
readonly description = "Next.js 15 reports an error for the `experimental-edge` value of the `runtime` segment config, which meant the same as `edge`. Changes `export const runtime = 'experimental-edge'` to `'edge'` in the files of the App Router folder, `app` or `src/app`. Files of the Pages Router are left alone.";
|
|
18
|
+
|
|
19
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
20
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
21
|
+
private active = false;
|
|
22
|
+
|
|
23
|
+
protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
24
|
+
this.active = APP_DIR_FILE.test(cu.sourcePath);
|
|
25
|
+
return this.active ? super.visitJsCompilationUnit(cu, ctx) : cu;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
override async visitVariable(variable: J.VariableDeclarations.NamedVariable, ctx: ExecutionContext): Promise<J | undefined> {
|
|
29
|
+
const v = await super.visitVariable(variable, ctx) as J.VariableDeclarations.NamedVariable;
|
|
30
|
+
const init = v.initializer?.element as J.Literal | undefined;
|
|
31
|
+
const declaration = this.cursor.firstEnclosing((t: any): t is J.VariableDeclarations => t?.kind === J.Kind.VariableDeclarations) as any;
|
|
32
|
+
const exported = declaration?.kind === J.Kind.VariableDeclarations && (declaration.modifiers ?? []).some((m: any) => m.keyword === 'export');
|
|
33
|
+
if (!exported || !isIdentifier(v.name) || v.name.simpleName !== 'runtime' || init?.kind !== J.Kind.Literal || init.value !== 'experimental-edge') return v;
|
|
34
|
+
return {...v, initializer: {...v.initializer!, element: withStringValue(init, 'edge')}} as J.VariableDeclarations.NamedVariable;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import {Cursor, emptyMarkers, findMarker, printer, randomId} from "@openrewrite/rewrite";
|
|
2
|
+
import {FunctionDeclaration, JS, prologueLength, walk} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {emptySpace, isIdentifier, J, rightPadded, space} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {create} from "mutative";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The App Router's special files whose exports Next.js calls with request-time data.
|
|
8
|
+
* `params` reaches every one of them, `searchParams` only pages.
|
|
9
|
+
*
|
|
10
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/version-15#params--searchparams
|
|
11
|
+
*/
|
|
12
|
+
const PARAMS_FILES = new Set(['page', 'layout', 'route', 'default', 'opengraph-image', 'twitter-image', 'icon', 'apple-icon']);
|
|
13
|
+
|
|
14
|
+
/** Special files that render on the server and so may be async, beyond those Next.js passes `params`. */
|
|
15
|
+
const SERVER_FILES = new Set([...PARAMS_FILES, 'not-found', 'template', 'loading', 'sitemap', 'robots', 'manifest']);
|
|
16
|
+
|
|
17
|
+
/** Route handler methods, which receive the segment data as their second argument. */
|
|
18
|
+
export const HTTP_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']);
|
|
19
|
+
|
|
20
|
+
/** Named exports a page or layout has Next.js call with the same props as the default export. */
|
|
21
|
+
export const METADATA_FUNCTIONS = new Set(['generateMetadata', 'generateViewport']);
|
|
22
|
+
|
|
23
|
+
export type FunctionLike = J.MethodDeclaration | JS.ArrowFunction;
|
|
24
|
+
|
|
25
|
+
/** Folders that hold source code of a project, which are not its root: an `app` folder below one is no App Router. */
|
|
26
|
+
const NOT_A_PROJECT_ROOT = new Set(['app', 'pages', 'lib', 'components', 'utils', 'src', 'node_modules']);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The path below the project's App Router folder, `app` or `src/app`, or undefined for a file outside it.
|
|
30
|
+
* Folders above the project, as `apps/web` in a monorepo, are allowed; a folder named `app` below
|
|
31
|
+
* `pages` or `lib` is not the App Router.
|
|
32
|
+
*/
|
|
33
|
+
export function pathInAppDir(sourcePath: string): string | undefined {
|
|
34
|
+
const parts = sourcePath.replace(/\\/g, '/').split('/');
|
|
35
|
+
const app = parts.indexOf('app');
|
|
36
|
+
if (app < 0) return undefined;
|
|
37
|
+
const project = parts.slice(0, app);
|
|
38
|
+
if (project[project.length - 1] === 'src') project.pop();
|
|
39
|
+
if (project.some(segment => NOT_A_PROJECT_ROOT.has(segment))) return undefined;
|
|
40
|
+
const below = parts.slice(app + 1);
|
|
41
|
+
return below.length ? below.join('/') : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The name of the file `sourcePath` is below the App Router folder, such as `page` or `route`, or undefined. */
|
|
45
|
+
export function appRouterFile(sourcePath: string): string | undefined {
|
|
46
|
+
const path = pathInAppDir(sourcePath);
|
|
47
|
+
const match = path && /^((?:[^/]+\/)*)([^/.]+)\.(?:[cm]?[jt]sx?)$/.exec(path);
|
|
48
|
+
// Next.js routes no file in a private `_folder`.
|
|
49
|
+
if (!match || match[1].split('/').some(segment => segment.startsWith('_'))) return undefined;
|
|
50
|
+
return match[2];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function isParamsFile(sourcePath: string): boolean {
|
|
54
|
+
const file = appRouterFile(sourcePath);
|
|
55
|
+
return file !== undefined && PARAMS_FILES.has(file);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function isServerFile(cu: JS.CompilationUnit): boolean {
|
|
59
|
+
const file = appRouterFile(cu.sourcePath);
|
|
60
|
+
return file !== undefined && SERVER_FILES.has(file) && !isClientFile(cu);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Whether the file opens with the `'use client'` directive. */
|
|
64
|
+
export function isClientFile(cu: JS.CompilationUnit): boolean {
|
|
65
|
+
return cu.statements.slice(0, prologueLength(cu))
|
|
66
|
+
.some(s => ((s.element as JS.ExpressionStatement).expression as J.Literal | undefined)?.value === 'use client');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function isFunctionLike(tree: unknown): tree is FunctionLike {
|
|
70
|
+
const kind = (tree as J | undefined)?.kind;
|
|
71
|
+
return kind === J.Kind.MethodDeclaration || kind === JS.Kind.ArrowFunction;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function isAsync(fn: FunctionLike): boolean {
|
|
75
|
+
return fn.modifiers.some(m => m.keyword === 'async');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Whether the function calls a hook — `useX()` or `React.useX()` — which an async component
|
|
80
|
+
* cannot, so it has to stay synchronous and unwrap request data with `use` instead.
|
|
81
|
+
*/
|
|
82
|
+
export function callsHooks(fn: FunctionLike): boolean {
|
|
83
|
+
let found = false;
|
|
84
|
+
walk(fn, node => {
|
|
85
|
+
const n = node as J;
|
|
86
|
+
if (n.kind === J.Kind.MethodInvocation && /^use[A-Z0-9]/.test((n as J.MethodInvocation).name.simpleName)) {
|
|
87
|
+
found = true;
|
|
88
|
+
}
|
|
89
|
+
return !found;
|
|
90
|
+
});
|
|
91
|
+
return found;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The function `cursor` stands in, nearest first, or undefined at module scope. */
|
|
95
|
+
export function enclosingFunction(cursor: Cursor): Cursor | undefined {
|
|
96
|
+
for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {
|
|
97
|
+
if (isFunctionLike(c.value)) return c;
|
|
98
|
+
if (c.value?.kind === J.Kind.ClassDeclaration) return c;
|
|
99
|
+
}
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The names the file's `export default <name>` or `export { <name> as default }` point at. */
|
|
104
|
+
export function defaultExportedNames(cu: JS.CompilationUnit): Set<string> {
|
|
105
|
+
const names = new Set<string>();
|
|
106
|
+
for (const s of cu.statements) {
|
|
107
|
+
const statement = s.element as J;
|
|
108
|
+
if (statement.kind === JS.Kind.ExportAssignment) {
|
|
109
|
+
const expression = (statement as JS.ExportAssignment).expression.element;
|
|
110
|
+
if (isIdentifier(expression)) names.add(expression.simpleName);
|
|
111
|
+
} else if (statement.kind === JS.Kind.ExportDeclaration) {
|
|
112
|
+
const clause = (statement as JS.ExportDeclaration).exportClause;
|
|
113
|
+
if (clause?.kind !== JS.Kind.NamedExports) continue;
|
|
114
|
+
for (const e of (clause as JS.NamedExports).elements.elements) {
|
|
115
|
+
const specifier = (e.element as JS.ExportSpecifier).specifier;
|
|
116
|
+
if (specifier.kind === JS.Kind.Alias) {
|
|
117
|
+
const alias = specifier as JS.Alias;
|
|
118
|
+
const local = alias.propertyName.element;
|
|
119
|
+
if (isIdentifier(alias.alias) && alias.alias.simpleName === 'default' && isIdentifier(local)) {
|
|
120
|
+
names.add(local.simpleName);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return names;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The name a top-level function is exported under — `default` for a default export — or
|
|
131
|
+
* undefined when the function is not one of the module's own top-level exports.
|
|
132
|
+
*/
|
|
133
|
+
export function exportedName(fnCursor: Cursor, cu: JS.CompilationUnit): string | undefined {
|
|
134
|
+
const fn = fnCursor.value as FunctionLike;
|
|
135
|
+
const exported = (modifiers: J.Modifier[]) => modifiers.some(m => m.keyword === 'export');
|
|
136
|
+
const isDefault = (modifiers: J.Modifier[]) => modifiers.some(m => m.keyword === 'default');
|
|
137
|
+
const defaults = defaultExportedNames(cu);
|
|
138
|
+
|
|
139
|
+
if (fn.kind === J.Kind.MethodDeclaration && isTopLevel(fnCursor)) {
|
|
140
|
+
const name = fn.name.simpleName;
|
|
141
|
+
if (isDefault(fn.modifiers) || defaults.has(name)) return 'default';
|
|
142
|
+
return exported(fn.modifiers) ? name : undefined;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// `const Page = async (...) => {}` or `const Page = function (...) {}`
|
|
146
|
+
const declarations = declarationOf(fnCursor);
|
|
147
|
+
if (!declarations) return undefined;
|
|
148
|
+
const variable = declarations.variable;
|
|
149
|
+
if (!isIdentifier(variable.name)) return undefined;
|
|
150
|
+
const name = variable.name.simpleName;
|
|
151
|
+
if (defaults.has(name)) return 'default';
|
|
152
|
+
return exported(declarations.declarations.modifiers) ? name : undefined;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The top-level `const X = <fn>` declaring the function, looking through a function expression's wrapper. */
|
|
156
|
+
function declarationOf(fnCursor: Cursor): {declarations: J.VariableDeclarations, variable: J.VariableDeclarations.NamedVariable} | undefined {
|
|
157
|
+
let c = fnCursor.parentTree();
|
|
158
|
+
if (c?.value?.kind === JS.Kind.StatementExpression) c = c.parentTree();
|
|
159
|
+
if (c?.value?.kind !== J.Kind.NamedVariable) return undefined;
|
|
160
|
+
const declarations = c.parentTree();
|
|
161
|
+
if (declarations?.value?.kind !== J.Kind.VariableDeclarations || !isTopLevel(declarations)) return undefined;
|
|
162
|
+
return {declarations: declarations.value, variable: c.value};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function isTopLevel(cursor: Cursor): boolean {
|
|
166
|
+
return cursor.parentTree()?.value?.kind === JS.Kind.CompilationUnit;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Marks a function `async`, placing the keyword where it reads `async function` or `async (...) =>`. */
|
|
170
|
+
export function makeAsync<F extends FunctionLike>(fn: F): F {
|
|
171
|
+
if (isAsync(fn)) return fn;
|
|
172
|
+
const asyncModifier = (prefix: J.Space): J.Modifier => ({
|
|
173
|
+
kind: J.Kind.Modifier,
|
|
174
|
+
id: randomId(),
|
|
175
|
+
prefix,
|
|
176
|
+
markers: emptyMarkers,
|
|
177
|
+
keyword: 'async',
|
|
178
|
+
type: "LanguageExtension" as J.ModifierType,
|
|
179
|
+
annotations: []
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
if (fn.kind === JS.Kind.ArrowFunction) {
|
|
183
|
+
const arrow = fn as JS.ArrowFunction;
|
|
184
|
+
return create(arrow, draft => {
|
|
185
|
+
draft.modifiers.push(asyncModifier(emptySpace) as any);
|
|
186
|
+
if (arrow.returnTypeExpression) draft.returnTypeExpression = promiseReturn(arrow.returnTypeExpression) as any;
|
|
187
|
+
const parameters = draft.lambda.parameters;
|
|
188
|
+
if (parameters.parenthesized) {
|
|
189
|
+
parameters.prefix = space(' ') as any;
|
|
190
|
+
} else {
|
|
191
|
+
// `x => ...` has to become `async x => ...`
|
|
192
|
+
const first = parameters.parameters[0];
|
|
193
|
+
if (first) (first.element as any).prefix = space(' ');
|
|
194
|
+
}
|
|
195
|
+
}) as F;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const method = fn as J.MethodDeclaration;
|
|
199
|
+
const functionMarker = findMarker<FunctionDeclaration>(method, JS.Markers.FunctionDeclaration);
|
|
200
|
+
return create(method, draft => {
|
|
201
|
+
if (method.returnTypeExpression) draft.returnTypeExpression = promiseReturn(method.returnTypeExpression) as any;
|
|
202
|
+
if (functionMarker) {
|
|
203
|
+
const marker = draft.markers.markers.find(m => m.kind === JS.Markers.FunctionDeclaration) as any;
|
|
204
|
+
draft.modifiers.push(asyncModifier(method.modifiers.length ? space(' ') : functionMarker.prefix) as any);
|
|
205
|
+
marker.prefix = space(' ');
|
|
206
|
+
} else {
|
|
207
|
+
draft.modifiers.push(asyncModifier(method.modifiers.length ? space(' ') : method.name.prefix) as any);
|
|
208
|
+
draft.name.prefix = space(' ') as any;
|
|
209
|
+
}
|
|
210
|
+
}) as F;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** An async function returns a promise of what it returned, so its declared return type says so. */
|
|
214
|
+
function promiseReturn(returnType: J): J {
|
|
215
|
+
const declared = returnType.kind === JS.Kind.TypeInfo ? (returnType as JS.TypeInfo).typeIdentifier : returnType;
|
|
216
|
+
if (declared.kind === J.Kind.ParameterizedType) {
|
|
217
|
+
const clazz = (declared as J.ParameterizedType).class;
|
|
218
|
+
if (isIdentifier(clazz) && clazz.simpleName === 'Promise') return returnType;
|
|
219
|
+
}
|
|
220
|
+
return returnType.kind === JS.Kind.TypeInfo
|
|
221
|
+
? {...returnType, typeIdentifier: promiseOf(declared)} as JS.TypeInfo
|
|
222
|
+
: promiseOf(returnType);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** `Promise<type>`, or another generic type `name` of it. */
|
|
226
|
+
export function promiseOf(type: J, name = 'Promise'): J.ParameterizedType {
|
|
227
|
+
return {
|
|
228
|
+
kind: J.Kind.ParameterizedType,
|
|
229
|
+
id: randomId(),
|
|
230
|
+
prefix: type.prefix,
|
|
231
|
+
markers: emptyMarkers,
|
|
232
|
+
class: identifier(name),
|
|
233
|
+
typeParameters: {
|
|
234
|
+
kind: J.Kind.Container,
|
|
235
|
+
before: emptySpace,
|
|
236
|
+
elements: [rightPadded({...type, prefix: emptySpace} as any, emptySpace)],
|
|
237
|
+
markers: emptyMarkers,
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function identifier(name: string, prefix: J.Space = emptySpace): J.Identifier {
|
|
243
|
+
return {kind: J.Kind.Identifier, id: randomId(), prefix, markers: emptyMarkers, annotations: [], simpleName: name};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function parenthesize<T extends J>(tree: T): J.Parentheses<T> {
|
|
247
|
+
return {
|
|
248
|
+
kind: J.Kind.Parentheses,
|
|
249
|
+
id: randomId(),
|
|
250
|
+
prefix: tree.prefix,
|
|
251
|
+
markers: emptyMarkers,
|
|
252
|
+
tree: rightPadded({...tree, prefix: emptySpace} as T, emptySpace)
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function awaitOf(expression: J): JS.Await {
|
|
257
|
+
return {
|
|
258
|
+
kind: JS.Kind.Await,
|
|
259
|
+
id: randomId(),
|
|
260
|
+
prefix: expression.prefix,
|
|
261
|
+
markers: emptyMarkers,
|
|
262
|
+
expression: {...expression, prefix: space(' ')} as any,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Whether the expression at `cursor` is read from — `x.y`, `x()`, `x[0]`, `` x`...` `` — so
|
|
268
|
+
* that wrapping it in `await` or `as` needs parentheses to keep binding first.
|
|
269
|
+
*/
|
|
270
|
+
export function needsParentheses(cursor: Cursor): boolean {
|
|
271
|
+
const self = cursor.value as J;
|
|
272
|
+
const parent = cursor.parentTree()?.value as J | undefined;
|
|
273
|
+
if (!parent) return false;
|
|
274
|
+
switch (parent.kind) {
|
|
275
|
+
case J.Kind.MethodInvocation:
|
|
276
|
+
return (parent as J.MethodInvocation).select?.element === self;
|
|
277
|
+
case J.Kind.FieldAccess:
|
|
278
|
+
return (parent as J.FieldAccess).target === self;
|
|
279
|
+
case J.Kind.ArrayAccess:
|
|
280
|
+
return (parent as J.ArrayAccess).indexed === self;
|
|
281
|
+
case JS.Kind.FunctionCall:
|
|
282
|
+
return (parent as JS.FunctionCall).function?.element === self;
|
|
283
|
+
case JS.Kind.TaggedTemplateExpression:
|
|
284
|
+
return (parent as JS.TaggedTemplateExpression).tag?.element === self;
|
|
285
|
+
case J.Kind.Unary:
|
|
286
|
+
case J.Kind.Binary:
|
|
287
|
+
case JS.Kind.As:
|
|
288
|
+
// `await x` binds tighter than any binary operator; only a following member read needs parentheses.
|
|
289
|
+
return false;
|
|
290
|
+
default:
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Statements that end in their own block or body, and so say nothing about whether the file writes semicolons. */
|
|
296
|
+
export const SELF_TERMINATED = new Set<string>([
|
|
297
|
+
J.Kind.Try, J.Kind.If, J.Kind.Block, J.Kind.ForLoop, J.Kind.ForEachLoop, J.Kind.WhileLoop, J.Kind.Switch,
|
|
298
|
+
J.Kind.MethodDeclaration, J.Kind.ClassDeclaration, J.Kind.Label, JS.Kind.ForOfLoop, JS.Kind.ForInLoop,
|
|
299
|
+
]);
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Ends with a semicolon the statement before each one that a rewrite made start with a parenthesis,
|
|
303
|
+
* which code without semicolons would otherwise read as a call of the statement before it.
|
|
304
|
+
*/
|
|
305
|
+
export async function guardLeadingParentheses(statements: J.RightPadded<J>[], original: J.RightPadded<J>[], cursor: Cursor): Promise<J.RightPadded<J>[]> {
|
|
306
|
+
const startsWithParenthesis = async (statement: J) => (await printer(cursor).print({...statement, prefix: emptySpace} as J)).startsWith('(');
|
|
307
|
+
let result = statements;
|
|
308
|
+
for (let i = 1; i < statements.length; i++) {
|
|
309
|
+
const previous = result[i - 1];
|
|
310
|
+
if (statements[i] === original[i] || SELF_TERMINATED.has(previous.element.kind) ||
|
|
311
|
+
previous.markers.markers.some(m => m.kind === J.Markers.Semicolon)) continue;
|
|
312
|
+
if (!await startsWithParenthesis(statements[i].element) || await startsWithParenthesis(original[i].element)) continue;
|
|
313
|
+
result = result.map((s, j) => j !== i - 1 ? s : {...s, markers: {...s.markers, markers: [...s.markers.markers, {kind: J.Markers.Semicolon, id: randomId()}]}} as J.RightPadded<J>);
|
|
314
|
+
}
|
|
315
|
+
return result;
|
|
316
|
+
}
|