@openrewrite/recipes-react 0.20.0 → 0.21.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/i18n/translate-hard-coded-strings.d.ts +67 -0
- package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
- package/dist/i18n/translate-hard-coded-strings.js +439 -0
- package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/dist/search/find-enzyme-usage.d.ts +4 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +30 -3
- package/dist/search/find-enzyme-usage.js.map +1 -1
- package/dist/search/find-hard-coded-strings.d.ts +110 -0
- package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
- package/dist/search/find-hard-coded-strings.js +987 -0
- package/dist/search/find-hard-coded-strings.js.map +1 -0
- package/dist/search/find-missing-use-client-directive.d.ts +2 -0
- package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
- package/dist/search/find-missing-use-client-directive.js +1 -0
- package/dist/search/find-missing-use-client-directive.js.map +1 -1
- package/dist/testing/enzyme-portals.d.ts +3 -5
- package/dist/testing/enzyme-portals.d.ts.map +1 -1
- package/dist/testing/enzyme-portals.js +8 -39
- package/dist/testing/enzyme-portals.js.map +1 -1
- package/dist/testing/enzyme-render-blockers.d.ts +10 -0
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
- package/dist/testing/enzyme-render-blockers.js +119 -0
- package/dist/testing/enzyme-render-blockers.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +80 -17
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +2 -0
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +29 -3
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +5 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +12 -3
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/json-and-javascript.d.ts +4 -0
- package/dist/util/json-and-javascript.d.ts.map +1 -0
- package/dist/util/json-and-javascript.js +37 -0
- package/dist/util/json-and-javascript.js.map +1 -0
- package/dist/util/module-imports.d.ts +36 -0
- package/dist/util/module-imports.d.ts.map +1 -1
- package/dist/util/module-imports.js +216 -0
- package/dist/util/module-imports.js.map +1 -1
- package/dist/util/test-source.d.ts +2 -0
- package/dist/util/test-source.d.ts.map +1 -0
- package/dist/util/test-source.js +5 -0
- package/dist/util/test-source.js.map +1 -0
- package/dist/zustand/entry-store.d.ts +9 -0
- package/dist/zustand/entry-store.d.ts.map +1 -0
- package/dist/zustand/entry-store.js +136 -0
- package/dist/zustand/entry-store.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +5 -4
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +8 -5
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts +11 -2
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +137 -42
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +7 -5
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +87 -33
- package/dist/zustand/zustand-plan.js.map +1 -1
- package/package.json +1 -1
- package/src/i18n/translate-hard-coded-strings.ts +442 -0
- package/src/index.ts +7 -0
- package/src/search/find-enzyme-usage.ts +30 -6
- package/src/search/find-hard-coded-strings.ts +1006 -0
- package/src/search/find-missing-use-client-directive.ts +1 -1
- package/src/testing/enzyme-portals.ts +4 -44
- package/src/testing/enzyme-render-blockers.ts +113 -0
- package/src/testing/enzyme-to-react-testing-library.ts +90 -18
- package/src/testing/enzyme-usage.ts +35 -2
- package/src/testing/enzyme-wrapper-scope.ts +13 -2
- package/src/util/json-and-javascript.ts +26 -0
- package/src/util/module-imports.ts +223 -0
- package/src/util/test-source.ts +2 -0
- package/src/zustand/entry-store.ts +131 -0
- package/src/zustand/redux-stores.ts +12 -7
- package/src/zustand/redux-to-zustand.ts +168 -48
- package/src/zustand/zustand-plan.ts +98 -32
|
@@ -0,0 +1,1006 @@
|
|
|
1
|
+
import {check, Column, Cursor, DataTable, ExecutionContext, foundSearchResult, not, or, ScanningRecipe, SourceFile, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {bindingNames, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, JSX, resolve, scopeOf} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
4
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
5
|
+
import {jsonAndJavaScript} from "../util/json-and-javascript";
|
|
6
|
+
import {addPathsConfig, aliasResolver, importBindings, isAliasSpecifier, moduleExports, ModuleExports, namespaceImportModules, PathsConfigs, resolveModule} from "../util/module-imports";
|
|
7
|
+
import {TEST_SOURCE} from "../util/test-source";
|
|
8
|
+
import {isIdentifierNamed} from "../util/tree-search";
|
|
9
|
+
|
|
10
|
+
export const HARD_CODED_STRINGS_TABLE = "org.openrewrite.react.search.HardCodedStrings";
|
|
11
|
+
|
|
12
|
+
type Kind = "TEXT" | "ATTRIBUTE" | "MIXED";
|
|
13
|
+
type Context = "JSX" | "CALL" | "METADATA" | "VARIABLE";
|
|
14
|
+
|
|
15
|
+
interface Site {
|
|
16
|
+
element: string;
|
|
17
|
+
attribute: string;
|
|
18
|
+
mixed: boolean;
|
|
19
|
+
context: Context;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Where the visitor reports what it finds: the search recipe's data table, or a recipe collecting findings with their nodes. */
|
|
23
|
+
export interface FindingSink {
|
|
24
|
+
insertRow(ctx: ExecutionContext, row: HardCodedStringRow, node?: J, cursor?: Cursor): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A binding a source names: its own top-level `name`, or the export `name` of the module `specifier`. */
|
|
28
|
+
interface BindingRef {
|
|
29
|
+
file: string;
|
|
30
|
+
specifier?: string;
|
|
31
|
+
name: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** What a scan of every source learns about the constants that sources show, directly or through components' props. */
|
|
35
|
+
export class ImportedRenders {
|
|
36
|
+
readonly sources = new Set<string>();
|
|
37
|
+
/** Package roots, such as `packages/ui/` or `""`, to the dependencies their `package.json` declares. */
|
|
38
|
+
readonly packages = new Map<string, ReadonlySet<string>>();
|
|
39
|
+
readonly configs: PathsConfigs = new Map();
|
|
40
|
+
readonly exports = new Map<string, ModuleExports>();
|
|
41
|
+
/** Where a source first shows an export of a module, or the property `path` of one. */
|
|
42
|
+
private readonly renders = new Map<string, {from: string, specifier: string, name: string, path: string, site: Site}>();
|
|
43
|
+
/** Where each component, by file and name, shows a prop or a path into one, such as `item.title` or `list[].title`. */
|
|
44
|
+
private readonly componentRenders = new Map<string, Map<string, Site>>();
|
|
45
|
+
/** A component passing a path into its own props to a prop of another component. */
|
|
46
|
+
private readonly forwards: {file: string, component: string, path: string, child: BindingRef, prop: string}[] = [];
|
|
47
|
+
/** A constant, or a path into one, passed to a component's prop. */
|
|
48
|
+
private readonly passes: {child: BindingRef, prop: string, constant: BindingRef, path: string}[] = [];
|
|
49
|
+
/** A top-level constant naming another one at a path, as `[defaultSort, ...]` does at `[]`. */
|
|
50
|
+
private readonly aliases: {file: string, constant: string, path: string, target: string}[] = [];
|
|
51
|
+
private readonly modules = new Map<string, string | undefined>();
|
|
52
|
+
private resolved?: Map<string, Site>;
|
|
53
|
+
private rendered?: Map<string, Map<string, Site>>;
|
|
54
|
+
|
|
55
|
+
addRender(from: string, specifier: string, name: string, path: string, site: Site): void {
|
|
56
|
+
const key = [from, specifier, name, path].join("\0");
|
|
57
|
+
if (!this.renders.has(key)) this.renders.set(key, {from, specifier, name, path, site});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
addComponentRender(file: string, component: string, path: string, site: Site): void {
|
|
61
|
+
const key = `${file}\0${component}`;
|
|
62
|
+
const paths = this.componentRenders.get(key) ?? new Map<string, Site>();
|
|
63
|
+
if (!paths.has(path)) paths.set(path, site);
|
|
64
|
+
this.componentRenders.set(key, paths);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
addForward(file: string, component: string, path: string, child: BindingRef, prop: string): void {
|
|
68
|
+
this.forwards.push({file, component, path, child, prop});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
addPass(child: BindingRef, prop: string, constant: BindingRef, path: string): void {
|
|
72
|
+
this.passes.push({child, prop, constant, path});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
addAlias(file: string, constant: string, path: string, target: string): void {
|
|
76
|
+
this.aliases.push({file, constant, path, target});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Whether the component `child` shows its prop `prop` as it is. */
|
|
80
|
+
rendersProp(child: BindingRef, prop: string): boolean {
|
|
81
|
+
const component = this.locate(child);
|
|
82
|
+
return !!component && !!this.componentPaths().get(`${component.file}\0${component.local}`)?.has(prop);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Where some source shows the top-level constant `local` of `file`, or its property `path`. */
|
|
86
|
+
siteOf(file: string, local: string, path: string): Site | undefined {
|
|
87
|
+
this.resolved ??= this.resolveConstants();
|
|
88
|
+
return this.resolved.get([file, local, path].join("\0"));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private resolveConstants(): Map<string, Site> {
|
|
92
|
+
const resolved = new Map<string, Site>();
|
|
93
|
+
const add = (file: string, local: string, path: string, site: Site) => {
|
|
94
|
+
const key = [file, local, path].join("\0");
|
|
95
|
+
if (!resolved.has(key)) resolved.set(key, site);
|
|
96
|
+
};
|
|
97
|
+
for (const {from, specifier, name, path, site} of this.renders.values()) {
|
|
98
|
+
const constant = this.locate({file: from, specifier, name});
|
|
99
|
+
if (constant) add(constant.file, constant.local, path, site);
|
|
100
|
+
}
|
|
101
|
+
const paths = this.componentPaths();
|
|
102
|
+
for (const {child, prop, constant, path} of this.passes) {
|
|
103
|
+
const component = this.locate(child);
|
|
104
|
+
const target = this.locate(constant);
|
|
105
|
+
if (!component || !target) continue;
|
|
106
|
+
for (const [rendered, site] of paths.get(`${component.file}\0${component.local}`) ?? []) {
|
|
107
|
+
const rest = pathAfter(rendered, prop);
|
|
108
|
+
if (rest !== undefined) add(target.file, target.local, joinPath(path, rest), site);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// A constant named in another's array or object stands for it at that path
|
|
112
|
+
for (let changed = true, rounds = 0; changed && rounds < 5; rounds++) {
|
|
113
|
+
changed = false;
|
|
114
|
+
for (const {file, constant, path, target} of this.aliases) {
|
|
115
|
+
for (const [key, site] of [...resolved]) {
|
|
116
|
+
const [keyFile, keyLocal, keyPath] = key.split("\0");
|
|
117
|
+
const rest = keyFile === file && keyLocal === constant ? pathAfter(keyPath, path) : undefined;
|
|
118
|
+
const aliased = rest !== undefined ? [file, target, rest.replace(/^\./, "")].join("\0") : undefined;
|
|
119
|
+
if (aliased && !resolved.has(aliased)) {
|
|
120
|
+
resolved.set(aliased, site);
|
|
121
|
+
changed = true;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return resolved;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** What each component shows of its props, including through the props of the components it renders. */
|
|
130
|
+
private componentPaths(): Map<string, Map<string, Site>> {
|
|
131
|
+
if (this.rendered) return this.rendered;
|
|
132
|
+
const rendered = new Map([...this.componentRenders].map(([key, paths]) => [key, new Map(paths)]));
|
|
133
|
+
for (let changed = true, rounds = 0; changed && rounds < 10; rounds++) {
|
|
134
|
+
changed = false;
|
|
135
|
+
for (const {file, component, path, child, prop} of this.forwards) {
|
|
136
|
+
const target = this.locate(child);
|
|
137
|
+
const childPaths = target && rendered.get(`${target.file}\0${target.local}`);
|
|
138
|
+
if (!childPaths) continue;
|
|
139
|
+
const key = `${file}\0${component}`;
|
|
140
|
+
const paths = rendered.get(key) ?? new Map<string, Site>();
|
|
141
|
+
// A snapshot, since a recursive component forwards to its own paths
|
|
142
|
+
for (const [childPath, site] of [...childPaths]) {
|
|
143
|
+
const rest = pathAfter(childPath, prop);
|
|
144
|
+
const own = rest !== undefined ? joinPath(path, rest) : undefined;
|
|
145
|
+
if (own !== undefined && !paths.has(own)) {
|
|
146
|
+
paths.set(own, site);
|
|
147
|
+
changed = true;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
rendered.set(key, paths);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return this.rendered = rendered;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The file and local name of the declaration a binding names, following imports through up to three re-exports. */
|
|
157
|
+
private locate(ref: BindingRef): {file: string, local: string} | undefined {
|
|
158
|
+
if (ref.specifier === undefined) return {file: ref.file, local: ref.name};
|
|
159
|
+
const target = this.resolveModule(ref.file, ref.specifier);
|
|
160
|
+
return target ? this.exported(target, ref.name, 0) : undefined;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private exported(file: string, name: string, hops: number): {file: string, local: string} | undefined {
|
|
164
|
+
const exports = this.exports.get(file);
|
|
165
|
+
const local = exports?.locals.get(name);
|
|
166
|
+
if (local !== undefined) return {file, local};
|
|
167
|
+
if (!exports || hops >= 3) return undefined;
|
|
168
|
+
for (const {module, names} of exports.reExports) {
|
|
169
|
+
const imported = names === "*" ? (name === "default" ? undefined : name) : names.get(name);
|
|
170
|
+
const target = imported !== undefined ? this.resolveModule(file, module) : undefined;
|
|
171
|
+
const found = target && this.exported(target, imported!, hops + 1);
|
|
172
|
+
if (found) return found;
|
|
173
|
+
}
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private resolveModule(from: string, specifier: string): string | undefined {
|
|
178
|
+
const key = `${from}\0${specifier}`;
|
|
179
|
+
if (!this.modules.has(key)) {
|
|
180
|
+
const roots = [...this.packages.keys()].filter(root => from.startsWith(root)).sort((a, b) => b.length - a.length);
|
|
181
|
+
const declares = (name: string) => roots.some(root => this.packages.get(root)!.has(name));
|
|
182
|
+
const configured = isAliasSpecifier(specifier) ? resolveModule(from, specifier, this.sources, this.configs) : undefined;
|
|
183
|
+
this.modules.set(key, configured ?? aliasResolver(this.sources, [...new Set([...roots, ""])], declares)(from, specifier));
|
|
184
|
+
}
|
|
185
|
+
return this.modules.get(key);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export class HardCodedStringRow {
|
|
190
|
+
@Column({displayName: "Source path", description: "The file containing the string."})
|
|
191
|
+
sourcePath!: string;
|
|
192
|
+
|
|
193
|
+
@Column({displayName: "Element", description: "The JSX element the string renders in, empty for a fragment."})
|
|
194
|
+
element!: string;
|
|
195
|
+
|
|
196
|
+
@Column({displayName: "Attribute", description: "The attribute holding the string, empty for element text."})
|
|
197
|
+
attribute!: string;
|
|
198
|
+
|
|
199
|
+
@Column({
|
|
200
|
+
displayName: "Kind",
|
|
201
|
+
description: "`TEXT` for element text, `ATTRIBUTE` for an attribute value, or `MIXED` for a string that needs interpolation or a `<Trans>` component rather than a plain key: a sentence of text with expressions or elements, reported once for the element holding it, or a string with interpolations."
|
|
202
|
+
})
|
|
203
|
+
kind!: Kind;
|
|
204
|
+
|
|
205
|
+
@Column({
|
|
206
|
+
displayName: "Context",
|
|
207
|
+
description: "Where the string is rendered from, which decides how it can be translated: `JSX` for element text and attributes, `CALL` for a notification call such as `toast(...)`, `METADATA` for a Next.js `metadata` export, or `VARIABLE` for a variable, object property or array element shown elsewhere, possibly through components' props, whose `element` and `attribute` describe where it is shown, possibly in another file."
|
|
208
|
+
})
|
|
209
|
+
context!: Context;
|
|
210
|
+
|
|
211
|
+
@Column({
|
|
212
|
+
displayName: "Text",
|
|
213
|
+
description: "The string as React renders its whitespace, with HTML entities left as written. A sentence is written as react-i18next's `<Trans>` reads its children, " +
|
|
214
|
+
"such as `Hello <1>{{name}}</1>, read the <3>terms</3>`; a template literal's interpolations as `{0}`, `{1}`."
|
|
215
|
+
})
|
|
216
|
+
text!: string;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Props that components conventionally render as text; HTML elements only get {@link USER_FACING_ATTRIBUTES}. */
|
|
220
|
+
const COMPONENT_TEXT_PROP = /^(?:heading|subheading|subtitle|caption|description|message|tooltip|hint|text|helperText)$|(?:Label|Title|Text|Heading|Caption|Description|Message|Tooltip|Hint|Placeholder)$/;
|
|
221
|
+
|
|
222
|
+
/** The files Next.js reads `metadata` and `generateMetadata` from. */
|
|
223
|
+
const NEXT_METADATA_FILE = /(^|\/)app\/(.*\/)?(page|layout)\.[jt]sx?$/;
|
|
224
|
+
const METADATA_SECTIONS = new Set(["title", "description", "openGraph", "twitter"]);
|
|
225
|
+
const METADATA_TEXT_KEYS = new Set(["title", "description", "default", "absolute"]);
|
|
226
|
+
|
|
227
|
+
/** Notification libraries, and local modules wrapping one such as shadcn's `@/components/ui/use-toast`. */
|
|
228
|
+
const TOAST_MODULE = /^(?:sonner|react-hot-toast|react-toastify)$|(?:^|\/)(?:use-)?toast$/;
|
|
229
|
+
const TOAST_METHODS = new Set(["success", "error", "info", "warning", "warn", "loading", "message", "promise"]);
|
|
230
|
+
const TOAST_TEXT_KEYS = new Set(["title", "description", "loading", "success", "error"]);
|
|
231
|
+
const TOAST_BUTTONS = new Set(["action", "cancel"]);
|
|
232
|
+
|
|
233
|
+
/** Nodes an object literal sits in without changing what it is: its body, parentheses, `satisfies` and `as`. */
|
|
234
|
+
const OBJECT_WRAPPERS = new Set<string>([J.Kind.Block, J.Kind.Parentheses, JS.Kind.SatisfiesExpression, JS.Kind.As]);
|
|
235
|
+
export const FUNCTION_KINDS = new Set<string>([J.Kind.MethodDeclaration, J.Kind.Lambda, JS.Kind.ArrowFunction]);
|
|
236
|
+
|
|
237
|
+
const USER_FACING_ATTRIBUTES = new Set([
|
|
238
|
+
"alt", "title", "placeholder", "label",
|
|
239
|
+
"aria-label", "aria-description", "aria-placeholder", "aria-roledescription", "aria-valuetext",
|
|
240
|
+
]);
|
|
241
|
+
|
|
242
|
+
/** Elements whose text is not prose: code, keyboard keys, and embedded scripts and styles. */
|
|
243
|
+
const VERBATIM_ELEMENTS = new Set(["code", "pre", "kbd", "script", "style"]);
|
|
244
|
+
|
|
245
|
+
/** Modules whose components translate everything they render, props included, like `<Plural one={...}>` or `<FormattedMessage values={...}>`. */
|
|
246
|
+
const I18N_MODULE = /^(?:@lingui\/|@formatjs\/|react-intl$|react-i18next$|next-i18next$|next-intl(?:\/|$))/;
|
|
247
|
+
|
|
248
|
+
/** Sources users never see: example apps, playgrounds, developer and debug screens, and mock data. */
|
|
249
|
+
const NON_PRODUCT_SOURCE = /(^|\/)(examples?|__dev__|dev-?tools|\.storybook|__fixtures__|fixtures|developer|debug)(\/|$)|(^|\/)[^/]*playground[^/]*(\/|$)|(^|\/)(developer|[^/]*debug[^/]*)\.[cm]?[jt]sx?$|\.mocks?(-data)?\.[cm]?[jt]sx?$/i;
|
|
250
|
+
|
|
251
|
+
const LETTERS = /\p{L}/gu;
|
|
252
|
+
// A single character of these scripts is a word
|
|
253
|
+
const IDEOGRAPHIC = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
|
254
|
+
/** camelCase, snake_case and CONSTANT_CASE tokens, which name things in code rather than say something. */
|
|
255
|
+
const IDENTIFIER_LIKE = /^(?:[a-z]+(?:[A-Z][a-z\d]*)+|[a-z\d]+(?:_[a-z\d]+)+|[A-Z\d]+(?:_[A-Z\d]+)+)$/;
|
|
256
|
+
const ENTITY = /&(?:#\d+|#x[\da-f]+|[a-z][a-z\d]*);/gi;
|
|
257
|
+
const URL_EMAIL_DOMAIN_OR_PATH = /^(?:[a-z][\w+.-]*:\/\/\S*|[^\s@]+@[^\s@]+\.[^\s@]+|\.?[\w-]+(?:\.[\w-]+)+\/?|\/[\w./-]*|#[\da-f]{3,8})$/i;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Finds hard-coded strings that React components render to users, as a first step toward internationalization.
|
|
261
|
+
*
|
|
262
|
+
* @example
|
|
263
|
+
* <h1>Welcome</h1> // found: TEXT
|
|
264
|
+
* <img alt="Company logo" /> // found: ATTRIBUTE
|
|
265
|
+
* <p>Hello {name}!</p> // found: MIXED
|
|
266
|
+
* <div className="primary" /> // not found
|
|
267
|
+
*/
|
|
268
|
+
export class FindHardCodedStrings extends ScanningRecipe<ImportedRenders> {
|
|
269
|
+
readonly name = "org.openrewrite.react.search.find-hard-coded-strings";
|
|
270
|
+
readonly displayName = "Find hard-coded user-facing strings";
|
|
271
|
+
readonly description = "Finds hard-coded strings that React apps show to users, as a starting point for internationalization. " +
|
|
272
|
+
"Reports JSX text; string and template literal values of user-facing attributes (`alt`, `title`, `placeholder`, `label`, text-bearing `aria-*`) " +
|
|
273
|
+
"and of component text props such as `heading`, `text` or names ending in `Label`, `Title`, `Text` or `Message`; " +
|
|
274
|
+
"strings in variables, and in properties and array elements of objects, that the same file or an importing file shows, " +
|
|
275
|
+
"directly or through the props of the components it renders, `.map` callbacks included; string props a component shows; " +
|
|
276
|
+
"following relative, `baseUrl` and `@/` alias imports of named, default and namespace exports through up to three re-exports; " +
|
|
277
|
+
"titles and descriptions in Next.js `metadata` and `generateMetadata`; " +
|
|
278
|
+
"and messages passed to `toast(...)` from sonner, react-hot-toast, react-toastify or a local `toast`/`use-toast` module. " +
|
|
279
|
+
"Strings that need interpolation or `<Trans>` are marked `MIXED`; a sentence split by expressions or elements is one row, written as `<Trans>` reads it. " +
|
|
280
|
+
"Skips test, story, mock-data, example-app, playground, developer and debug sources; " +
|
|
281
|
+
"anything inside `<Trans>` or components imported from Lingui, react-intl, react-i18next, next-i18next or next-intl; " +
|
|
282
|
+
"text in `<code>`, `<pre>`, `<kbd>`, `<script>` and `<style>`; strings without a word (two letters, or one ideograph); " +
|
|
283
|
+
"and strings made of a single URL, email address, domain, path, hex colour, or camelCase, snake_case or CONSTANT_CASE identifier. " +
|
|
284
|
+
"Strings whose way to the screen goes through state, context or functions other than array callbacks are not followed.";
|
|
285
|
+
|
|
286
|
+
private readonly table = new DataTable<HardCodedStringRow>(HARD_CODED_STRINGS_TABLE, "Hard-coded strings",
|
|
287
|
+
"Hard-coded strings that React components render to users.", HardCodedStringRow);
|
|
288
|
+
|
|
289
|
+
initialValue(): ImportedRenders {
|
|
290
|
+
return new ImportedRenders();
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async scanner(acc: ImportedRenders): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
294
|
+
const sources = await check(not(isVendoredOrBundled()), new HardCodedStringsVisitor(acc));
|
|
295
|
+
const manifests = new class extends JsonVisitor<ExecutionContext> {
|
|
296
|
+
override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
|
|
297
|
+
if (!acc) return doc;
|
|
298
|
+
if (/(^|\/)package\.json$/.test(doc.sourcePath)) acc.packages.set(doc.sourcePath.slice(0, -"package.json".length), dependencyNames(doc));
|
|
299
|
+
await addPathsConfig(acc.configs, doc);
|
|
300
|
+
return doc;
|
|
301
|
+
}
|
|
302
|
+
}();
|
|
303
|
+
return jsonAndJavaScript(manifests, sources);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async editorWithData(acc: ImportedRenders): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
307
|
+
return check(not(isVendoredOrBundled()), new HardCodedStringsVisitor(acc, this.table));
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Reports hard-coded strings when given a sink; otherwise, scanning, records which imported constants each source shows. */
|
|
312
|
+
export class HardCodedStringsVisitor extends JavaScriptVisitor<ExecutionContext> {
|
|
313
|
+
constructor(private readonly acc: ImportedRenders | undefined, private readonly table?: FindingSink) {
|
|
314
|
+
super();
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private sourcePath = "";
|
|
318
|
+
private nextMetadataFile = false;
|
|
319
|
+
private toastNames = new Set<string>();
|
|
320
|
+
private i18nComponents = new Set<string>();
|
|
321
|
+
private translated = 0;
|
|
322
|
+
private verbatim = 0;
|
|
323
|
+
/** The JSX strings a reported sentence already includes. */
|
|
324
|
+
private covered = new Set<string>();
|
|
325
|
+
/** Module-level imports by local name: named and default ones, and namespace ones (`import * as name`). */
|
|
326
|
+
private imports = new Map<string, {module: string, name: string}>();
|
|
327
|
+
private namespaces = new Map<string, string>();
|
|
328
|
+
/** Strings assigned to variables, reported once the file shows that it renders the variable. */
|
|
329
|
+
private constants: {binding: string, name: string, path: string, topLevel: boolean, id: string, text: string, interpolated: boolean}[] = [];
|
|
330
|
+
private rendered = new Map<string, Site>();
|
|
331
|
+
|
|
332
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
333
|
+
if (TEST_SOURCE.test(cu.sourcePath) || NON_PRODUCT_SOURCE.test(cu.sourcePath)) return cu;
|
|
334
|
+
this.sourcePath = cu.sourcePath;
|
|
335
|
+
this.nextMetadataFile = NEXT_METADATA_FILE.test(cu.sourcePath);
|
|
336
|
+
const imports = importBindings(cu);
|
|
337
|
+
this.imports = new Map(imports.map(b => [b.local, {module: b.module, name: b.name}]));
|
|
338
|
+
this.namespaces = namespaceImportModules(cu);
|
|
339
|
+
this.i18nComponents = new Set(imports.filter(b => I18N_MODULE.test(b.module)).map(b => b.local));
|
|
340
|
+
const toastImports = imports.filter(b => TOAST_MODULE.test(b.module));
|
|
341
|
+
this.toastNames = new Set(toastImports.filter(b => b.name === "toast" || b.name === "default").map(b => b.local));
|
|
342
|
+
// shadcn's `const {toast} = useToast()` takes the function from a hook rather than an import
|
|
343
|
+
if (toastImports.some(b => /^use[A-Z]/.test(b.name))) this.toastNames.add("toast");
|
|
344
|
+
this.constants = [];
|
|
345
|
+
this.rendered = new Map();
|
|
346
|
+
this.covered = new Set();
|
|
347
|
+
if (!this.table) {
|
|
348
|
+
this.acc?.sources.add(cu.sourcePath);
|
|
349
|
+
this.acc?.exports.set(cu.sourcePath, moduleExports(cu));
|
|
350
|
+
return super.visitJsCompilationUnit(cu, ctx);
|
|
351
|
+
}
|
|
352
|
+
const visited = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
|
|
353
|
+
return this.reportConstants(visited, ctx);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
override async visitJsxTag(tag: JSX.Tag, ctx: ExecutionContext): Promise<J | undefined> {
|
|
357
|
+
const segments = tagName(tag).split(".");
|
|
358
|
+
const translated = +(this.i18nComponents.has(segments[0]) || segments[segments.length - 1] === "Trans");
|
|
359
|
+
const verbatim = +VERBATIM_ELEMENTS.has(segments[0]);
|
|
360
|
+
this.translated += translated;
|
|
361
|
+
this.verbatim += verbatim;
|
|
362
|
+
try {
|
|
363
|
+
const sentence = this.table && this.translated === 0 && this.verbatim === 0 && isSentenceRoot(tag, this.cursor) ? transContent(tag.children, this.covered) : undefined;
|
|
364
|
+
if (sentence !== undefined && isTranslatable(transPlainText(sentence))) {
|
|
365
|
+
this.insertRow(ctx, {element: tagName(tag), attribute: "", mixed: true, context: "JSX"}, sentence, true, tag);
|
|
366
|
+
return foundSearchResult(await super.visitJsxTag(tag, ctx) as JSX.Tag);
|
|
367
|
+
}
|
|
368
|
+
return await super.visitJsxTag(tag, ctx);
|
|
369
|
+
} finally {
|
|
370
|
+
this.translated -= translated;
|
|
371
|
+
this.verbatim -= verbatim;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
override async visitLiteral(literal: J.Literal, ctx: ExecutionContext): Promise<J | undefined> {
|
|
376
|
+
const value = stringValue(literal);
|
|
377
|
+
if (!this.table || value === undefined || this.translated > 0 || this.covered.has(literal.id) || !isTranslatable(value.trim())) return literal;
|
|
378
|
+
const site = this.siteOf() ?? this.interpolationSite();
|
|
379
|
+
if (!site) {
|
|
380
|
+
this.collectConstant(literal, value.trim(), false);
|
|
381
|
+
return literal;
|
|
382
|
+
}
|
|
383
|
+
const text = site.attribute ? value.trim() : jsxText(value).replace(/^ +| +$/g, "");
|
|
384
|
+
return this.report(ctx, literal, site, text, false);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
override async visitIdentifier(identifier: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
|
|
388
|
+
if (this.translated === 0 && (this.table || this.imports.has(identifier.simpleName))) {
|
|
389
|
+
const site = this.siteOf() ?? this.interpolationSite();
|
|
390
|
+
if (site) this.markRendered(identifier, site, "");
|
|
391
|
+
}
|
|
392
|
+
if (this.translated === 0 && !this.table) {
|
|
393
|
+
this.recordPropFlow(identifier, [], this.cursor);
|
|
394
|
+
this.recordAlias(identifier);
|
|
395
|
+
}
|
|
396
|
+
return super.visitIdentifier(identifier, ctx);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
override async visitFieldAccess(fieldAccess: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
|
|
400
|
+
const chain = memberChain(fieldAccess, this.cursor);
|
|
401
|
+
const root = chain?.root.simpleName;
|
|
402
|
+
if (chain && this.translated === 0 && (this.table || this.imports.has(root!) || this.namespaces.has(root!))) {
|
|
403
|
+
const site = this.siteOf() ?? this.interpolationSite();
|
|
404
|
+
if (site) this.markRendered(chain.root, site, chain.names.join("."), chain.holder);
|
|
405
|
+
}
|
|
406
|
+
if (chain && this.translated === 0 && !this.table) this.recordPropFlow(chain.root, chain.names, chain.holder);
|
|
407
|
+
return super.visitFieldAccess(fieldAccess, ctx);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
override async visitTemplateExpression(template: JS.TemplateExpression, ctx: ExecutionContext): Promise<J | undefined> {
|
|
411
|
+
const t = await super.visitTemplateExpression(template, ctx) as JS.TemplateExpression;
|
|
412
|
+
if (!this.table) return t;
|
|
413
|
+
const parts = [t.head, ...t.spans.map(span => span.element.tail)].map(part => stringValue(part) ?? "");
|
|
414
|
+
if (this.translated > 0 || !isTranslatable(parts.join("").trim())) return t;
|
|
415
|
+
const text = parts.map((part, i) => (i > 0 ? `{${i - 1}}` : "") + part).join("").trim();
|
|
416
|
+
const site = this.siteOf();
|
|
417
|
+
if (!site) {
|
|
418
|
+
this.collectConstant(t, text, t.spans.length > 0);
|
|
419
|
+
return t;
|
|
420
|
+
}
|
|
421
|
+
return this.report(ctx, t, site, text, t.spans.length > 0);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** Remembers a string that initializes a variable, or a property of an object that does, keyed by the binding it declares. */
|
|
425
|
+
private collectConstant(node: J, text: string, interpolated: boolean): void {
|
|
426
|
+
const {keys, owner, object} = objectPath(this.cursor);
|
|
427
|
+
const declaration = owner?.value as J | undefined;
|
|
428
|
+
const declared =
|
|
429
|
+
declaration?.kind === J.Kind.NamedVariable && (keys.length === 0 || (declaration as J.VariableDeclarations.NamedVariable).initializer?.element === object.value) ?
|
|
430
|
+
(declaration as J.VariableDeclarations.NamedVariable).name :
|
|
431
|
+
keys.length === 0 && declaration?.kind === JS.Kind.BindingElement && (declaration as JS.BindingElement).initializer?.element === object.value ?
|
|
432
|
+
(declaration as JS.BindingElement).name :
|
|
433
|
+
undefined;
|
|
434
|
+
if (!declared || !isIdentifier(declared)) return;
|
|
435
|
+
const scope = scopeOf(owner!).declaringScope(declared.simpleName);
|
|
436
|
+
if (!scope) return;
|
|
437
|
+
this.constants.push({
|
|
438
|
+
binding: `${scope.id}:${declared.simpleName}`, name: declared.simpleName, path: joinKeys(keys),
|
|
439
|
+
topLevel: scope.kind === JS.Kind.CompilationUnit, id: node.id, text, interpolated
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Scanning, records what an expression rooted at `root`, then `names`, does with a component's props:
|
|
445
|
+
* the component shows it, or passes it to another component's prop, or a constant reaches a prop.
|
|
446
|
+
*/
|
|
447
|
+
private recordPropFlow(root: J.Identifier, names: string[], holder: Cursor): void {
|
|
448
|
+
if (!this.acc) return;
|
|
449
|
+
const site = this.siteOf() ?? this.interpolationSite();
|
|
450
|
+
const passed = this.passedToComponent();
|
|
451
|
+
if (!site && !passed) return;
|
|
452
|
+
const suffix = names.map(name => `.${name}`).join("");
|
|
453
|
+
const prop = propRoot(root, holder);
|
|
454
|
+
if (prop && site) this.acc.addComponentRender(this.sourcePath, prop.component, joinPath(prop.path, suffix), site);
|
|
455
|
+
if (!passed) return;
|
|
456
|
+
if (prop) {
|
|
457
|
+
this.acc.addForward(this.sourcePath, prop.component, joinPath(prop.path, suffix), passed.child, passed.prop);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (resolve(holder, root)?.kind !== JS.Kind.CompilationUnit) return;
|
|
461
|
+
const imported = this.imports.get(root.simpleName);
|
|
462
|
+
const namespace = this.namespaces.get(root.simpleName);
|
|
463
|
+
if (imported) this.acc.addPass(passed.child, passed.prop, {file: this.sourcePath, specifier: imported.module, name: imported.name}, joinPath("", suffix));
|
|
464
|
+
else if (namespace && names.length > 0) {
|
|
465
|
+
this.acc.addPass(passed.child, passed.prop, {file: this.sourcePath, specifier: namespace, name: names[0]}, joinPath("", names.slice(1).map(name => `.${name}`).join("")));
|
|
466
|
+
} else if (!namespace) this.acc.addPass(passed.child, passed.prop, {file: this.sourcePath, name: root.simpleName}, joinPath("", suffix));
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Scanning, records a top-level constant named inside another's array or object, as `[defaultSort, ...]` does. */
|
|
470
|
+
private recordAlias(identifier: J.Identifier): void {
|
|
471
|
+
const {keys, owner, object} = objectPath(this.cursor);
|
|
472
|
+
const declaration = owner?.value as J | undefined;
|
|
473
|
+
if (keys.length === 0 || declaration?.kind !== J.Kind.NamedVariable) return;
|
|
474
|
+
const {name, initializer} = declaration as J.VariableDeclarations.NamedVariable;
|
|
475
|
+
if (!isIdentifier(name) || initializer?.element !== object.value || resolve(this.cursor, identifier)?.kind !== JS.Kind.CompilationUnit) return;
|
|
476
|
+
if (scopeOf(owner!).declaringScope(name.simpleName)?.kind === JS.Kind.CompilationUnit) {
|
|
477
|
+
this.acc?.addAlias(this.sourcePath, name.simpleName, joinKeys(keys), identifier.simpleName);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** The component and prop the value at the cursor is passed to, as in `<FilterItem item={item}>`. */
|
|
482
|
+
private passedToComponent(): {child: BindingRef, prop: string} | undefined {
|
|
483
|
+
const attribute = renderedFrom(this.cursor).parentTree();
|
|
484
|
+
if (attribute?.value.kind !== JS.Kind.JsxAttribute || !isIdentifier((attribute.value as JSX.Attribute).key)) return undefined;
|
|
485
|
+
const child = this.componentRef(attribute.firstEnclosing((t): t is JSX.Tag => t.kind === JS.Kind.JsxTag)!);
|
|
486
|
+
return child && {child, prop: ((attribute.value as JSX.Attribute).key as J.Identifier).simpleName};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** The component a JSX tag names: one the source declares, or an import. */
|
|
490
|
+
private componentRef(tag: JSX.Tag): BindingRef | undefined {
|
|
491
|
+
const name = tag.openName.element;
|
|
492
|
+
if (!isIdentifier(name) || !/^[A-Z]/.test(name.simpleName)) return undefined;
|
|
493
|
+
const imported = this.imports.get(name.simpleName);
|
|
494
|
+
return imported ? {file: this.sourcePath, specifier: imported.module, name: imported.name} : {file: this.sourcePath, name: name.simpleName};
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Remembers where the source first shows the binding an identifier reads, or its property `path`. Scanning,
|
|
499
|
+
* only an imported binding counts, keyed by the module and the export it names. `holder` is the cursor on
|
|
500
|
+
* the node directly holding the identifier.
|
|
501
|
+
*/
|
|
502
|
+
private markRendered(identifier: J.Identifier, site: Site, path: string, holder: Cursor = this.cursor): void {
|
|
503
|
+
const owner = resolve(holder, identifier);
|
|
504
|
+
if (!owner) return;
|
|
505
|
+
if (!this.table) {
|
|
506
|
+
if (owner.kind !== JS.Kind.CompilationUnit || !this.acc) return;
|
|
507
|
+
const imported = this.imports.get(identifier.simpleName);
|
|
508
|
+
const namespace = this.namespaces.get(identifier.simpleName);
|
|
509
|
+
if (imported) this.acc.addRender(this.sourcePath, imported.module, imported.name, path, site);
|
|
510
|
+
else if (namespace && path) {
|
|
511
|
+
const [name, ...rest] = path.split(".");
|
|
512
|
+
this.acc.addRender(this.sourcePath, namespace, name, rest.join("."), site);
|
|
513
|
+
}
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
const binding = `${owner.id}:${identifier.simpleName}|${path}`;
|
|
517
|
+
if (!this.rendered.has(binding)) this.rendered.set(binding, site);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private async reportConstants(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
521
|
+
const found = new Set<string>();
|
|
522
|
+
for (const {binding, name, path, topLevel, id, text, interpolated} of this.constants) {
|
|
523
|
+
const site = this.rendered.get(`${binding}|${path}`) ?? (topLevel ? this.acc?.siteOf(this.sourcePath, name, path) : undefined);
|
|
524
|
+
if (!site) continue;
|
|
525
|
+
this.insertRow(ctx, {...site, context: "VARIABLE"}, text, interpolated);
|
|
526
|
+
found.add(id);
|
|
527
|
+
}
|
|
528
|
+
if (found.size === 0) return cu;
|
|
529
|
+
return new class extends JavaScriptVisitor<ExecutionContext> {
|
|
530
|
+
override async visitLiteral(literal: J.Literal): Promise<J | undefined> {
|
|
531
|
+
return found.has(literal.id) ? foundSearchResult(literal) : literal;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
override async visitTemplateExpression(template: JS.TemplateExpression, ctx: ExecutionContext): Promise<J | undefined> {
|
|
535
|
+
const t = await super.visitTemplateExpression(template, ctx) as JS.TemplateExpression;
|
|
536
|
+
return found.has(t.id) ? foundSearchResult(t) : t;
|
|
537
|
+
}
|
|
538
|
+
}().visit(cu, ctx);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Where the value at the cursor is shown: in JSX, in Next.js metadata, or in a toast. */
|
|
542
|
+
private siteOf(cursor: Cursor = this.cursor): Site | undefined {
|
|
543
|
+
return this.jsxSite(cursor) ?? this.metadataSite(cursor) ?? this.callSite(cursor);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** The site of the shown template literal whose `${...}` holds the value at the cursor, which is then part of a larger message. */
|
|
547
|
+
private interpolationSite(): Site | undefined {
|
|
548
|
+
const child = renderedFrom(this.cursor);
|
|
549
|
+
const span = child.parentTree();
|
|
550
|
+
if (span?.value.kind !== JS.Kind.TemplateExpressionSpan || (span.value as JS.TemplateExpression.Span).expression !== child.value) return undefined;
|
|
551
|
+
const site = this.siteOf(span.parentTree()!);
|
|
552
|
+
return site && {...site, mixed: true};
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** The element and attribute that render the value at the cursor, or undefined where JSX does not render it as text. */
|
|
556
|
+
private jsxSite(cursor: Cursor = this.cursor): Site | undefined {
|
|
557
|
+
const child = renderedFrom(cursor);
|
|
558
|
+
const parent = child.parentTree();
|
|
559
|
+
if (parent?.value.kind === JS.Kind.JsxAttribute) {
|
|
560
|
+
const attr = parent.value as JSX.Attribute;
|
|
561
|
+
const tag = parent.firstEnclosing((t): t is JSX.Tag => t.kind === JS.Kind.JsxTag)!;
|
|
562
|
+
const element = tagName(tag);
|
|
563
|
+
const component = this.table && isIdentifier(attr.key) ? this.componentRef(tag) : undefined;
|
|
564
|
+
const shown = isUserFacing(attr, element) || !!component && !!this.acc?.rendersProp(component, (attr.key as J.Identifier).simpleName);
|
|
565
|
+
return shown ? {element, attribute: (attr.key as J.Identifier).simpleName, mixed: false, context: "JSX"} : undefined;
|
|
566
|
+
}
|
|
567
|
+
if (this.verbatim > 0 || !childOfTag(parent, child)) return undefined;
|
|
568
|
+
const tag = parent.value as JSX.Tag;
|
|
569
|
+
return {element: tagName(tag), attribute: "", mixed: hasOtherContent(tag, child.value) || sharesSentence(parent), context: "JSX"};
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** The Next.js metadata field holding the value at the cursor, such as `openGraph.title` of `export const metadata`. */
|
|
573
|
+
private metadataSite(cursor: Cursor): Site | undefined {
|
|
574
|
+
if (!this.nextMetadataFile) return undefined;
|
|
575
|
+
const {keys, owner, object} = objectPath(cursor);
|
|
576
|
+
const element = owner && metadataExport(owner, object);
|
|
577
|
+
const known = element && METADATA_SECTIONS.has(keys[0]) && METADATA_TEXT_KEYS.has(keys[keys.length - 1]);
|
|
578
|
+
return known ? {element, attribute: keys.join("."), mixed: false, context: "METADATA"} : undefined;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** The toast call taking the value at the cursor as its message, or as a text option such as `description`. */
|
|
582
|
+
private callSite(cursor: Cursor): Site | undefined {
|
|
583
|
+
if (this.toastNames.size === 0) return undefined;
|
|
584
|
+
const {keys, owner, object} = objectPath(cursor);
|
|
585
|
+
const textOption = keys.length === 0 || keys.length === 1 && TOAST_TEXT_KEYS.has(keys[0]) ||
|
|
586
|
+
keys.length === 2 && TOAST_BUTTONS.has(keys[0]) && keys[1] === "label";
|
|
587
|
+
if (!textOption || owner?.value.kind !== J.Kind.MethodInvocation) return undefined;
|
|
588
|
+
const call = owner.value as J.MethodInvocation;
|
|
589
|
+
const element = toastCallName(call, this.toastNames);
|
|
590
|
+
const argument = call.arguments.elements.some(a => a.element === object.value);
|
|
591
|
+
return element && argument ? {element, attribute: keys.join("."), mixed: false, context: "CALL"} : undefined;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
private report<T extends J>(ctx: ExecutionContext, node: T, site: Site, text: string, interpolated: boolean): T {
|
|
595
|
+
this.insertRow(ctx, site, text, interpolated, node);
|
|
596
|
+
return foundSearchResult(node);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
private insertRow(ctx: ExecutionContext, site: Site, text: string, interpolated: boolean, node?: J): void {
|
|
600
|
+
const kind: Kind = interpolated || site.mixed ? "MIXED" : site.attribute ? "ATTRIBUTE" : "TEXT";
|
|
601
|
+
this.table?.insertRow(ctx, {sourcePath: this.sourcePath, element: site.element, attribute: site.attribute, kind, context: site.context, text}, node, this.cursor);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
export function tagName(tag: JSX.Tag): string {
|
|
606
|
+
const name = tag.openName.element;
|
|
607
|
+
if (isIdentifier(name)) return name.simpleName;
|
|
608
|
+
if (name.kind === J.Kind.FieldAccess) {
|
|
609
|
+
const fa = name as J.FieldAccess;
|
|
610
|
+
return `${isIdentifier(fa.target) ? fa.target.simpleName + "." : ""}${fa.name.element.simpleName}`;
|
|
611
|
+
}
|
|
612
|
+
return "";
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function toastCallName(call: J.MethodInvocation, names: ReadonlySet<string>): string | undefined {
|
|
616
|
+
const name = call.name.simpleName;
|
|
617
|
+
if (!call.select) return names.has(name) ? name : undefined;
|
|
618
|
+
const target = call.select.element;
|
|
619
|
+
return isIdentifier(target) && names.has(target.simpleName) && TOAST_METHODS.has(name) ? `${target.simpleName}.${name}` : undefined;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* The property keys leading from the object literals around the value at the cursor, the outermost
|
|
624
|
+
* of those objects (or the value itself, outside any object), and the node holding it.
|
|
625
|
+
*/
|
|
626
|
+
function objectPath(cursor: Cursor): {keys: string[], object: Cursor, owner: Cursor | undefined} {
|
|
627
|
+
const keys: string[] = [];
|
|
628
|
+
let object = renderedFrom(cursor);
|
|
629
|
+
let child = object;
|
|
630
|
+
for (let parent = child.parentTree(); parent; child = parent, parent = parent.parentTree()) {
|
|
631
|
+
const node = parent.value as J;
|
|
632
|
+
if (node.kind === JS.Kind.PropertyAssignment) {
|
|
633
|
+
const {name, initializer} = node as JS.PropertyAssignment;
|
|
634
|
+
const key = isIdentifier(name.element) ? name.element.simpleName : stringValue(name.element);
|
|
635
|
+
if (initializer !== child.value || key === undefined) return {keys: [], object, owner: undefined};
|
|
636
|
+
keys.unshift(key);
|
|
637
|
+
} else if (node.kind === J.Kind.NewArray) {
|
|
638
|
+
keys.unshift("[]");
|
|
639
|
+
object = parent;
|
|
640
|
+
} else if (node.kind === J.Kind.NewClass && !(node as J.NewClass).class || OBJECT_WRAPPERS.has(node.kind)) {
|
|
641
|
+
if (node.kind !== J.Kind.Block) object = parent;
|
|
642
|
+
} else {
|
|
643
|
+
return {keys, object, owner: parent};
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return {keys, object, owner: undefined};
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** `metadata` or `generateMetadata` when the object is that export's value or what the function returns. */
|
|
650
|
+
function metadataExport(owner: Cursor, object: Cursor): string | undefined {
|
|
651
|
+
const node = owner.value as J;
|
|
652
|
+
if (node.kind === J.Kind.NamedVariable) {
|
|
653
|
+
return isIdentifierNamed((node as J.VariableDeclarations.NamedVariable).name, "metadata") && (node as J.VariableDeclarations.NamedVariable).initializer?.element === object.value ? "metadata" : undefined;
|
|
654
|
+
}
|
|
655
|
+
const fn = node.kind === J.Kind.Return ? enclosingFunction(owner) : FUNCTION_KINDS.has(node.kind) ? owner : undefined;
|
|
656
|
+
return fn && functionName(fn) === "generateMetadata" ? "generateMetadata" : undefined;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function enclosingFunction(cursor: Cursor): Cursor | undefined {
|
|
660
|
+
for (let c = cursor.parentTree(); c; c = c.parentTree()) {
|
|
661
|
+
if (FUNCTION_KINDS.has(c.value.kind)) return c;
|
|
662
|
+
}
|
|
663
|
+
return undefined;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** A function declaration's name, or the name of the variable an arrow function or function expression initializes. */
|
|
667
|
+
export function functionName(fn: Cursor): string | undefined {
|
|
668
|
+
if (fn.value.kind === J.Kind.MethodDeclaration) return (fn.value as J.MethodDeclaration).name.simpleName;
|
|
669
|
+
let c: Cursor | undefined = fn;
|
|
670
|
+
while (c && (FUNCTION_KINDS.has(c.value.kind) || c.value.kind === J.Kind.Parentheses)) c = c.parentTree();
|
|
671
|
+
const name = c?.value.kind === J.Kind.NamedVariable ? (c.value as J.VariableDeclarations.NamedVariable).name : undefined;
|
|
672
|
+
return name && isIdentifier(name) ? name.simpleName : undefined;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function isUserFacing(attr: JSX.Attribute, element: string): attr is JSX.Attribute & {key: J.Identifier} {
|
|
676
|
+
if (!isIdentifier(attr.key)) return false;
|
|
677
|
+
const name = attr.key.simpleName;
|
|
678
|
+
return USER_FACING_ATTRIBUTES.has(name) || /^[A-Z]|\./.test(element) && COMPONENT_TEXT_PROP.test(name);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
function renderedFrom(cursor: Cursor): Cursor {
|
|
682
|
+
let child = cursor;
|
|
683
|
+
for (let parent = child.parentTree(); parent && rendersChild(parent.value, child.value); parent = child.parentTree()) child = parent;
|
|
684
|
+
return child;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
function rendersChild(parent: J, child: J): boolean {
|
|
688
|
+
switch (parent.kind) {
|
|
689
|
+
case J.Kind.Parentheses:
|
|
690
|
+
case JS.Kind.JsxEmbeddedExpression:
|
|
691
|
+
return true;
|
|
692
|
+
case J.Kind.Ternary:
|
|
693
|
+
return (parent as J.Ternary).condition !== child;
|
|
694
|
+
case J.Kind.Binary: {
|
|
695
|
+
const {operator, right} = parent as J.Binary;
|
|
696
|
+
return operator.element === "Or" as J.Binary.Type || operator.element === "And" as J.Binary.Type && right === child;
|
|
697
|
+
}
|
|
698
|
+
case JS.Kind.Binary:
|
|
699
|
+
return (parent as JS.Binary).operator.element === "QuestionQuestion" as JS.Binary.Type;
|
|
700
|
+
default:
|
|
701
|
+
return false;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** Whether a tag sits in text of an enclosing tag, directly or through wrappers that hold nothing else. */
|
|
706
|
+
function sharesSentence(tagCursor: Cursor): boolean {
|
|
707
|
+
const child = renderedFrom(tagCursor);
|
|
708
|
+
const outer = child.parentTree();
|
|
709
|
+
if (!childOfTag(outer, child)) return false;
|
|
710
|
+
const tag = outer.value as JSX.Tag;
|
|
711
|
+
return hasText(tag) || !hasOtherContent(tag, child.value) && sharesSentence(outer);
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function childOfTag(cursor: Cursor | undefined, child: Cursor): cursor is Cursor {
|
|
715
|
+
return cursor?.value.kind === JS.Kind.JsxTag && !!(cursor.value as JSX.Tag).children?.includes(child.value);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function unwrap(expr: J | undefined): J | undefined {
|
|
719
|
+
return expr?.kind === JS.Kind.JsxEmbeddedExpression ? (expr as JSX.EmbeddedExpression).expression.element : expr;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
export function stringValue(expr: J | undefined): string | undefined {
|
|
723
|
+
return expr?.kind === J.Kind.Literal && typeof (expr as J.Literal).value === "string" ? (expr as J.Literal).value as string : undefined;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** Whether a child renders no text: whitespace, a tag without text, or a condition choosing between those. */
|
|
727
|
+
function isBlank(child: J): boolean {
|
|
728
|
+
switch (child.kind) {
|
|
729
|
+
case J.Kind.Empty:
|
|
730
|
+
return true;
|
|
731
|
+
case JS.Kind.JsxTag:
|
|
732
|
+
return (child as JSX.Tag).children?.every(isBlank) ?? true;
|
|
733
|
+
case JS.Kind.JsxEmbeddedExpression:
|
|
734
|
+
return isBlank((child as JSX.EmbeddedExpression).expression.element);
|
|
735
|
+
case J.Kind.Parentheses:
|
|
736
|
+
return isBlank((child as J.Parentheses<J>).tree.element);
|
|
737
|
+
case J.Kind.Ternary:
|
|
738
|
+
return isBlank((child as J.Ternary).truePart.element) && isBlank((child as J.Ternary).falsePart.element);
|
|
739
|
+
case J.Kind.Binary:
|
|
740
|
+
return (child as J.Binary).operator.element === "And" as J.Binary.Type && isBlank((child as J.Binary).right);
|
|
741
|
+
default:
|
|
742
|
+
return stringValue(child)?.trim() === "";
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function hasOtherContent(tag: JSX.Tag, self: J): boolean {
|
|
747
|
+
return !!tag.children?.some(c => c !== self && !isBlank(c));
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
function hasText(tag: JSX.Tag): boolean {
|
|
751
|
+
return !!tag.children?.some(c => {
|
|
752
|
+
const value = stringValue(unwrap(c));
|
|
753
|
+
return value !== undefined && hasLetters(value);
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
function isTranslatable(text: string): boolean {
|
|
758
|
+
return hasLetters(text) && !URL_EMAIL_DOMAIN_OR_PATH.test(text) && !IDENTIFIER_LIKE.test(text);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** Whether the text has a word: two letters, or one ideograph, not counting HTML entities. */
|
|
762
|
+
function hasLetters(text: string): boolean {
|
|
763
|
+
const plain = text.replace(ENTITY, "");
|
|
764
|
+
return IDEOGRAPHIC.test(plain) || (plain.match(LETTERS)?.length ?? 0) >= 2;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* The identifier at the root of `a.b.c` and the property names after it, with a cursor on the innermost access,
|
|
769
|
+
* which holds the root. Undefined where the root is not an identifier, as in `f().a`.
|
|
770
|
+
*/
|
|
771
|
+
function memberChain(access: J.FieldAccess, cursor: Cursor): {root: J.Identifier, names: string[], holder: Cursor} | undefined {
|
|
772
|
+
const names: string[] = [];
|
|
773
|
+
let holder = cursor;
|
|
774
|
+
let node: J = access;
|
|
775
|
+
for (;;) {
|
|
776
|
+
const current = node as J.FieldAccess;
|
|
777
|
+
names.unshift(current.name.element.simpleName);
|
|
778
|
+
if (isIdentifier(current.target)) return {root: current.target, names, holder};
|
|
779
|
+
if (current.target.kind !== J.Kind.FieldAccess) return undefined;
|
|
780
|
+
node = current.target;
|
|
781
|
+
holder = new Cursor(node, holder);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/** The packages a `package.json` declares, from its resolution where the parser recorded one and from its own text. */
|
|
786
|
+
export function dependencyNames(doc: Json.Document): Set<string> {
|
|
787
|
+
const resolution = findNodeResolutionResult(doc);
|
|
788
|
+
const names = new Set([...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? [],
|
|
789
|
+
...resolution?.optionalDependencies ?? [], ...resolution?.peerDependencies ?? []].map(dependency => dependency.name));
|
|
790
|
+
for (const {element: member} of (doc.value as Json.Object).members ?? []) {
|
|
791
|
+
const {key, value} = member as Json.Member;
|
|
792
|
+
if (!/^(dev|peer|optional)?[dD]ependencies$/.test(jsonKey(key.element) ?? "")) continue;
|
|
793
|
+
for (const {element: dependency} of (value as Json.Object).members ?? []) {
|
|
794
|
+
const name = jsonKey((dependency as Json.Member).key?.element);
|
|
795
|
+
if (name) names.add(name);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
return names;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function jsonKey(key: Json | undefined): string | undefined {
|
|
802
|
+
return key?.kind === Json.Kind.Literal ? String((key as Json.Literal).value) : key?.kind === Json.Kind.Identifier ? (key as Json.Identifier).name : undefined;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** A tag whose own text shares a sentence with other content, and which is not itself part of a larger sentence. */
|
|
806
|
+
function isSentenceRoot(tag: JSX.Tag, cursor: Cursor): boolean {
|
|
807
|
+
return hasText(tag) && (tag.children ?? []).filter(child => !isBlank(child)).length >= 2 && !sharesSentence(cursor);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** Basic HTML elements react-i18next writes by name rather than by index, by default. */
|
|
811
|
+
const TRANS_KEPT_ELEMENTS = new Set(["br", "strong", "i", "p"]);
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* The text react-i18next's `<Trans>` derives from these JSX children (`nodesToString`), once each
|
|
815
|
+
* interpolated value is passed as an object, as in `{{name}}`: elements become `<index>...</index>`,
|
|
816
|
+
* or keep their name when they are basic HTML without attributes, and a value that is no name
|
|
817
|
+
* becomes `{{index}}`. The strings it includes are added to `covered`.
|
|
818
|
+
*/
|
|
819
|
+
function transContent(children: readonly J[] | undefined, covered: Set<string>, names = new Map<string, string>()): string {
|
|
820
|
+
let text = "";
|
|
821
|
+
let index = 0;
|
|
822
|
+
for (const child of children ?? []) {
|
|
823
|
+
const piece = transChild(child, index, covered, names);
|
|
824
|
+
if (piece === undefined) continue;
|
|
825
|
+
text += piece;
|
|
826
|
+
index++;
|
|
827
|
+
}
|
|
828
|
+
return text;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/** One JSX child as `<Trans>` writes it, or undefined where React renders no child for it. */
|
|
832
|
+
function transChild(child: J, index: number, covered: Set<string>, names: Map<string, string>): string | undefined {
|
|
833
|
+
if (child.kind === J.Kind.Literal) {
|
|
834
|
+
const text = jsxText(stringValue(child) ?? "");
|
|
835
|
+
if (text) covered.add(child.id);
|
|
836
|
+
return text || undefined;
|
|
837
|
+
}
|
|
838
|
+
if (child.kind === JS.Kind.JsxTag) return transElement(child as JSX.Tag, index, covered, names);
|
|
839
|
+
if (child.kind !== JS.Kind.JsxEmbeddedExpression) return undefined;
|
|
840
|
+
const value = (child as JSX.EmbeddedExpression).expression.element;
|
|
841
|
+
if (value.kind === J.Kind.Empty) return undefined;
|
|
842
|
+
const string = stringValue(value);
|
|
843
|
+
if (string !== undefined) {
|
|
844
|
+
covered.add(value.id);
|
|
845
|
+
return string;
|
|
846
|
+
}
|
|
847
|
+
if (isIdentifier(value)) return `{{${placeholder(value.simpleName, value.simpleName, names)}}}`;
|
|
848
|
+
if (value.kind === J.Kind.FieldAccess) {
|
|
849
|
+
const path = propertyPath(value as J.FieldAccess);
|
|
850
|
+
return `{{${placeholder((value as J.FieldAccess).name.element.simpleName, path ?? `#${value.id}`, names)}}}`;
|
|
851
|
+
}
|
|
852
|
+
const shorthand = objectProperties(value);
|
|
853
|
+
if (shorthand?.length === 1) return `{{${shorthand[0]}}}`;
|
|
854
|
+
if (value.kind === J.Kind.Binary && (value as J.Binary).operator.element === "And" as J.Binary.Type && (value as J.Binary).right.kind === JS.Kind.JsxTag) {
|
|
855
|
+
return transElement((value as J.Binary).right as JSX.Tag, index, covered, names);
|
|
856
|
+
}
|
|
857
|
+
return `{{${index}}}`;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
function transElement(tag: JSX.Tag, index: number, covered: Set<string>, names: Map<string, string>): string {
|
|
861
|
+
const name = tagName(tag);
|
|
862
|
+
const content = transContent(tag.children, covered, names);
|
|
863
|
+
// React leaves `key` and `ref` out of props
|
|
864
|
+
const attributes = tag.attributes.filter(({element}) => element.kind !== JS.Kind.JsxAttribute ||
|
|
865
|
+
!isIdentifier((element as JSX.Attribute).key) || !["key", "ref"].includes(((element as JSX.Attribute).key as J.Identifier).simpleName)).length;
|
|
866
|
+
const props = attributes + (content ? 1 : 0);
|
|
867
|
+
const kept = TRANS_KEPT_ELEMENTS.has(name);
|
|
868
|
+
if (!content) return kept && props === 0 ? `<${name}/>` : `<${index}></${index}>`;
|
|
869
|
+
return kept && props <= 1 ? `<${name}>${content}</${name}>` : `<${index}>${content}</${index}>`;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* The name a value takes in a sentence: its own, unless a different value in the sentence already
|
|
874
|
+
* took it, when a number tells them apart, as `{{count}}` and `{{count2}}` do.
|
|
875
|
+
*/
|
|
876
|
+
function placeholder(name: string, value: string, names: Map<string, string>): string {
|
|
877
|
+
const taken = names.get(name);
|
|
878
|
+
if (taken === undefined || taken === value) {
|
|
879
|
+
names.set(name, value);
|
|
880
|
+
return name;
|
|
881
|
+
}
|
|
882
|
+
let n = 2;
|
|
883
|
+
while (names.has(`${name}${n}`) && names.get(`${name}${n}`) !== value) n++;
|
|
884
|
+
names.set(`${name}${n}`, value);
|
|
885
|
+
return `${name}${n}`;
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/** `a.b.c` as text, where the chain starts at an identifier. */
|
|
889
|
+
export function propertyPath(access: J.FieldAccess): string | undefined {
|
|
890
|
+
const names: string[] = [];
|
|
891
|
+
let node: J = access;
|
|
892
|
+
while (node.kind === J.Kind.FieldAccess) {
|
|
893
|
+
names.unshift((node as J.FieldAccess).name.element.simpleName);
|
|
894
|
+
node = (node as J.FieldAccess).target;
|
|
895
|
+
}
|
|
896
|
+
return isIdentifier(node) ? [node.simpleName, ...names].join(".") : undefined;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** The property names of an object literal such as `{{name}}`'s inner `{name}`. */
|
|
900
|
+
function objectProperties(value: J): string[] | undefined {
|
|
901
|
+
if (value.kind !== J.Kind.NewClass || (value as J.NewClass).class || !(value as J.NewClass).body) return undefined;
|
|
902
|
+
const names: string[] = [];
|
|
903
|
+
for (const {element} of (value as J.NewClass).body!.statements) {
|
|
904
|
+
if (element.kind !== JS.Kind.PropertyAssignment) return undefined;
|
|
905
|
+
const name = (element as JS.PropertyAssignment).name.element;
|
|
906
|
+
if (!isIdentifier(name)) return undefined;
|
|
907
|
+
names.push(name.simpleName);
|
|
908
|
+
}
|
|
909
|
+
return names;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** `<Trans>` text without its tags and placeholders, to decide whether any words are left. */
|
|
913
|
+
function transPlainText(text: string): string {
|
|
914
|
+
return text.replace(/\{\{[^}]*\}\}|<\/?(?:\d+|[a-z]+)\/?>/g, " ").trim();
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** JSX text as React renders it: lines trimmed where they meet a line break, blank lines dropped, the rest joined by spaces. */
|
|
918
|
+
export function jsxText(raw: string): string {
|
|
919
|
+
const lines = raw.split(/\r\n|\n|\r/);
|
|
920
|
+
// As Babel's cleanJSXElementLiteralChild, which starts at the first line
|
|
921
|
+
let last = 0;
|
|
922
|
+
lines.forEach((line, i) => {
|
|
923
|
+
if (/[^ \t]/.test(line)) last = i;
|
|
924
|
+
});
|
|
925
|
+
let text = "";
|
|
926
|
+
lines.forEach((line, i) => {
|
|
927
|
+
let trimmed = line.replace(/\t/g, " ");
|
|
928
|
+
if (i > 0) trimmed = trimmed.replace(/^[ ]+/, "");
|
|
929
|
+
if (i < lines.length - 1) trimmed = trimmed.replace(/[ ]+$/, "");
|
|
930
|
+
if (trimmed) text += i === last ? trimmed : trimmed + " ";
|
|
931
|
+
});
|
|
932
|
+
return text;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/** Calls whose callback's first parameter is an element of the array they are called on. */
|
|
936
|
+
const ELEMENT_CALLBACKS = new Set(["map", "flatMap", "forEach"]);
|
|
937
|
+
/** Array methods returning elements of the array they are called on. */
|
|
938
|
+
const ELEMENT_PRESERVING = new Set(["filter", "slice", "sort", "toSorted", "reverse", "toReversed"]);
|
|
939
|
+
|
|
940
|
+
/**
|
|
941
|
+
* The component whose props an identifier reads, and the path into them: `item` for a destructured prop,
|
|
942
|
+
* `""` for the whole props parameter, and `list[]` for a `.map` callback's element of the prop `list`.
|
|
943
|
+
*/
|
|
944
|
+
function propRoot(identifier: J.Identifier, holder: Cursor): {component: string, path: string} | undefined {
|
|
945
|
+
const owner = resolve(holder, identifier);
|
|
946
|
+
if (!owner || !FUNCTION_KINDS.has(owner.kind)) return undefined;
|
|
947
|
+
let fn: Cursor | undefined = holder;
|
|
948
|
+
while (fn && fn.value !== owner) fn = fn.parentTree();
|
|
949
|
+
const bound = fn && parameterPath(firstParameter(owner), identifier.simpleName);
|
|
950
|
+
if (!fn || bound === undefined) return undefined;
|
|
951
|
+
const component = functionName(fn);
|
|
952
|
+
if (component && /^[A-Z]/.test(component)) return {component, path: bound};
|
|
953
|
+
const call = fn.parentTree();
|
|
954
|
+
const invocation = call?.value as J.MethodInvocation | undefined;
|
|
955
|
+
if (invocation?.kind !== J.Kind.MethodInvocation || !ELEMENT_CALLBACKS.has(invocation.name.simpleName) ||
|
|
956
|
+
invocation.arguments.elements[0]?.element !== owner || !invocation.select) return undefined;
|
|
957
|
+
const receiver = expressionRoot(invocation.select.element, call!);
|
|
958
|
+
return receiver && {component: receiver.component, path: joinPath(`${receiver.path}[]`, bound ? `.${bound}` : "")};
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/** {@link propRoot} of an expression `holder` holds: an identifier, a property chain, or an element-preserving array call. */
|
|
962
|
+
function expressionRoot(expression: J, holder: Cursor): {component: string, path: string} | undefined {
|
|
963
|
+
if (isIdentifier(expression)) return propRoot(expression, holder);
|
|
964
|
+
const cursor = new Cursor(expression, holder);
|
|
965
|
+
if (expression.kind === J.Kind.FieldAccess) {
|
|
966
|
+
const chain = memberChain(expression as J.FieldAccess, cursor);
|
|
967
|
+
const root = chain && propRoot(chain.root, chain.holder);
|
|
968
|
+
return root && {component: root.component, path: joinPath(root.path, chain!.names.map(name => `.${name}`).join(""))};
|
|
969
|
+
}
|
|
970
|
+
const call = expression as J.MethodInvocation;
|
|
971
|
+
return call.kind === J.Kind.MethodInvocation && ELEMENT_PRESERVING.has(call.name.simpleName) && call.select ? expressionRoot(call.select.element, cursor) : undefined;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/** The name or pattern a function's first parameter declares. */
|
|
975
|
+
function firstParameter(fn: J): J | undefined {
|
|
976
|
+
const parameters = fn.kind === J.Kind.MethodDeclaration ? (fn as J.MethodDeclaration).parameters.elements :
|
|
977
|
+
fn.kind === JS.Kind.ArrowFunction ? (fn as JS.ArrowFunction).lambda.parameters.parameters :
|
|
978
|
+
fn.kind === J.Kind.Lambda ? (fn as J.Lambda).parameters.parameters : [];
|
|
979
|
+
const first = parameters[0]?.element as J | undefined;
|
|
980
|
+
return first?.kind === J.Kind.VariableDeclarations ? (first as J.VariableDeclarations).variables[0]?.element.name : first;
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/** The path into a parameter that `name` binds: `""` for the parameter itself, the property for a destructured one. */
|
|
984
|
+
function parameterPath(parameter: J | undefined, name: string): string | undefined {
|
|
985
|
+
if (!parameter) return undefined;
|
|
986
|
+
if (isIdentifier(parameter)) return parameter.simpleName === name ? "" : undefined;
|
|
987
|
+
// Only a property the pattern takes directly is a prop; a nested or rest name holds something else
|
|
988
|
+
return bindingNames(parameter).find(binding => binding.name === name)?.member;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/** Object and array keys as one path, such as `[].title` for `[{title}]`. */
|
|
992
|
+
function joinKeys(keys: readonly string[]): string {
|
|
993
|
+
return keys.reduce((path, key) => key === "[]" ? `${path}[]` : path ? `${path}.${key}` : key, "");
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/** `path` followed by `rest`, which is empty or starts with `.` or `[`. */
|
|
997
|
+
function joinPath(path: string, rest: string): string {
|
|
998
|
+
return path ? path + rest : rest.replace(/^\./, "");
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** What follows `prefix` in `path`, starting with `.` or `[`, or undefined where `path` does not start with it. */
|
|
1002
|
+
function pathAfter(path: string, prefix: string): string | undefined {
|
|
1003
|
+
if (path === prefix) return "";
|
|
1004
|
+
if (!prefix) return path.startsWith("[") ? path : `.${path}`;
|
|
1005
|
+
return path.startsWith(`${prefix}.`) || path.startsWith(`${prefix}[`) ? path.slice(prefix.length) : undefined;
|
|
1006
|
+
}
|