@openrewrite/recipes-react 0.19.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 +64 -4
- 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-shared-wrapper.d.ts +26 -0
- package/dist/testing/enzyme-shared-wrapper.d.ts.map +1 -0
- package/dist/testing/enzyme-shared-wrapper.js +213 -0
- package/dist/testing/enzyme-shared-wrapper.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 +355 -16
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +5 -1
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +48 -6
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +7 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +24 -9
- 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 +15 -4
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +155 -10
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts +29 -5
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +629 -42
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +31 -6
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +320 -31
- 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 +59 -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-shared-wrapper.ts +224 -0
- package/src/testing/enzyme-to-react-testing-library.ts +354 -19
- package/src/testing/enzyme-usage.ts +62 -5
- package/src/testing/enzyme-wrapper-scope.ts +24 -6
- 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 +171 -11
- package/src/zustand/redux-to-zustand.ts +689 -48
- package/src/zustand/zustand-plan.ts +350 -29
|
@@ -133,6 +133,11 @@ export const SIMULATED_EVENTS: ReadonlySet<string> = new Set(["click", "doubleCl
|
|
|
133
133
|
"touchMove", "touchEnd", "wheel"]);
|
|
134
134
|
// Enzyme also accepts the DOM's lowercase names of these events, and `dblclick` for a double click
|
|
135
135
|
const NATIVE_EVENT_NAMES = new Map([...[...SIMULATED_EVENTS].map(event => [event.toLowerCase(), event] as const), ["dblclick", "doubleClick"]]);
|
|
136
|
+
/** The React event a `simulate` name stands for, where `fireEvent` can dispatch it. */
|
|
137
|
+
export function simulatedEvent(name: string): string | undefined {
|
|
138
|
+
return SIMULATED_EVENTS.has(name) ? name : NATIVE_EVENT_NAMES.get(name);
|
|
139
|
+
}
|
|
140
|
+
|
|
136
141
|
const CLICK_DEFAULT_ACTIONS = new Set(["a", "input", "label", "option", "select", "summary", "textarea"]);
|
|
137
142
|
|
|
138
143
|
export function simpleChain(node: Expression): boolean {
|
|
@@ -282,7 +287,7 @@ function stringLiteral(node: J | undefined): node is J.Literal {
|
|
|
282
287
|
return node?.kind === J.Kind.Literal && typeof (node as J.Literal).value === "string";
|
|
283
288
|
}
|
|
284
289
|
|
|
285
|
-
function objectProperties(node: J | undefined): Map<string, Expression> | undefined {
|
|
290
|
+
export function objectProperties(node: J | undefined): Map<string, Expression> | undefined {
|
|
286
291
|
if (!node || !isObjectLiteral(node) || !node.body) return undefined;
|
|
287
292
|
const properties = new Map<string, Expression>();
|
|
288
293
|
for (const statement of node.body.statements) {
|
|
@@ -397,7 +402,9 @@ export function wrapperDeclaration<R>(statement: J | undefined, classify: (rende
|
|
|
397
402
|
* snapshot RTL records as the DOM rather than Enzyme's tree. `hostNames` decides the selectors {@link selectorLiteral} accepts.
|
|
398
403
|
*/
|
|
399
404
|
export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperDeclaration,
|
|
400
|
-
{events, html, untaggedPositions, hostNames, snapshots = false, optionalChaining = true, constant = () => undefined}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean, optionalChaining?: boolean, constant?: (node: J) => string | undefined
|
|
405
|
+
{events, html, untaggedPositions, hostNames, snapshots = false, optionalChaining = true, constant = () => undefined, blocked}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean, optionalChaining?: boolean, constant?: (node: J) => string | undefined,
|
|
406
|
+
/** Told every reference that rejects the scope, and whether it comes after an unmount. */
|
|
407
|
+
blocked?: (references: {cursor: Cursor, unmounted: boolean}[]) => void}): WrapperScope | undefined {
|
|
401
408
|
let serializers: ReadonlySet<string> | undefined;
|
|
402
409
|
const uses = new Map<string, WrapperRead>();
|
|
403
410
|
const removedStatements = new Set<string>();
|
|
@@ -502,10 +509,12 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
502
509
|
const name = terminalArgs[0].value as string;
|
|
503
510
|
const event = SIMULATED_EVENTS.has(name) ? name : NATIVE_EVENT_NAMES.get(name);
|
|
504
511
|
if (!event || !events.has(event)) return false;
|
|
505
|
-
|
|
506
|
-
|
|
512
|
+
// Enzyme assigns an empty mock's properties to the event, which are none
|
|
513
|
+
const init = objectProperties(terminalArgs[1])?.size === 0 ? undefined : terminalArgs[1];
|
|
514
|
+
const nativeEvent = nativeEventInit(event, init);
|
|
515
|
+
if (!nativeEvent && !eventInit(event, init)) return false;
|
|
507
516
|
if (event === "click" && CLICK_DEFAULT_ACTIONS.has(selectorTag(selectorText) ?? "")) return false;
|
|
508
|
-
return record(terminal, {...read, use: "simulate", event, ...nativeEvent ? {nativeEvent} : {eventInit:
|
|
517
|
+
return record(terminal, {...read, use: "simulate", event, ...nativeEvent ? {nativeEvent} : {eventInit: init}});
|
|
509
518
|
}
|
|
510
519
|
return false;
|
|
511
520
|
}
|
|
@@ -536,9 +545,18 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
536
545
|
const declared = new Cursor(variable.name, variableCursor(block, declaration));
|
|
537
546
|
const references = referencesOf(declared, name, "value");
|
|
538
547
|
if (!references.some(reference => reference.identifier === variable.name)) return undefined;
|
|
548
|
+
const rejected: {cursor: Cursor, unmounted: boolean}[] = [];
|
|
539
549
|
for (const reference of references) {
|
|
540
550
|
if (reference.identifier === variable.name) continue;
|
|
541
|
-
|
|
551
|
+
const after = unmounted;
|
|
552
|
+
if (reference.declares || after || !use(reference.identifier, reference.cursor)) {
|
|
553
|
+
if (!blocked) return undefined;
|
|
554
|
+
rejected.push({cursor: reference.cursor, unmounted: after});
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
if (rejected.length > 0) {
|
|
558
|
+
blocked!(rejected);
|
|
559
|
+
return undefined;
|
|
542
560
|
}
|
|
543
561
|
return {declaration, name, uses, removedStatements, unmounts};
|
|
544
562
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import {check, Cursor, ExecutionContext, or, SourceFile, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
4
|
+
import {treesOfType} from "./java-recipe-proxy";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One visitor of JSON documents and JavaScript sources, such as `package.json` files and the code they
|
|
8
|
+
* describe. With `discard`, the JavaScript visitor only gathers: the sources stay as they were.
|
|
9
|
+
*/
|
|
10
|
+
export function jsonAndJavaScript(json: JsonVisitor<ExecutionContext>, javascript: TreeVisitor<any, ExecutionContext>, discard = false): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
11
|
+
const visitor = new class extends TreeVisitor<any, ExecutionContext> {
|
|
12
|
+
override async isAcceptable(sourceFile: SourceFile, ctx: ExecutionContext): Promise<boolean> {
|
|
13
|
+
return await json.isAcceptable(sourceFile) || await javascript.isAcceptable(sourceFile, ctx);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
|
|
17
|
+
if (tree.kind === Json.Kind.Document) return await json.visit(tree, ctx, parent) as R | undefined;
|
|
18
|
+
if (tree.kind !== JS.Kind.CompilationUnit) return tree as R;
|
|
19
|
+
const visited = await javascript.visit(tree, ctx, parent) as R | undefined;
|
|
20
|
+
return discard ? tree as R : visited;
|
|
21
|
+
}
|
|
22
|
+
}();
|
|
23
|
+
// The host infers which trees to send only from a JsonVisitor or JavaScriptVisitor, and sends a plain
|
|
24
|
+
// TreeVisitor every tree, including ones the TypeScript side has no codec for
|
|
25
|
+
return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), visitor);
|
|
26
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import {TreePrinters} from "@openrewrite/rewrite";
|
|
1
2
|
import {JS, moduleNameOf} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Json} from "@openrewrite/rewrite/json";
|
|
2
4
|
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
3
5
|
import {posix} from "path";
|
|
4
6
|
|
|
@@ -34,6 +36,21 @@ export function importBindings(cu: JS.CompilationUnit): ImportBinding[] {
|
|
|
34
36
|
return bindings;
|
|
35
37
|
}
|
|
36
38
|
|
|
39
|
+
/** The modules a source's namespace imports, `import * as name`, bind, by local name. */
|
|
40
|
+
export function namespaceImportModules(cu: JS.CompilationUnit): Map<string, string> {
|
|
41
|
+
const modules = new Map<string, string>();
|
|
42
|
+
for (const {element} of cu.statements) {
|
|
43
|
+
if (element.kind !== JS.Kind.Import) continue;
|
|
44
|
+
const declaration = element as JS.Import;
|
|
45
|
+
const bindings = declaration.importClause?.namedBindings;
|
|
46
|
+
const specifier = declaration.moduleSpecifier?.element;
|
|
47
|
+
if (bindings?.kind === JS.Kind.Alias && isIdentifier((bindings as JS.Alias).alias) && specifier?.kind === J.Kind.Literal) {
|
|
48
|
+
modules.set(((bindings as JS.Alias).alias as J.Identifier).simpleName, moduleNameOf(specifier as J.Literal));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return modules;
|
|
52
|
+
}
|
|
53
|
+
|
|
37
54
|
/** The local names of a source's namespace imports, `import * as name`, which bind a whole module. */
|
|
38
55
|
export function namespaceImports(cu: JS.CompilationUnit): string[] {
|
|
39
56
|
const names: string[] = [];
|
|
@@ -52,9 +69,215 @@ export function isRelativeSpecifier(specifier: string): boolean {
|
|
|
52
69
|
return /^\.\.?(?:\/|$)/.test(specifier);
|
|
53
70
|
}
|
|
54
71
|
|
|
72
|
+
/** Resolves a module specifier from the source at the first path to the source it names, if it names one. */
|
|
73
|
+
export type Resolve = (from: string, specifier: string) => string | undefined;
|
|
74
|
+
|
|
75
|
+
/** The `compilerOptions.paths` of a `jsconfig.json` or `tsconfig.json`, and the directory its targets resolve from. */
|
|
76
|
+
export interface PathsConfig {
|
|
77
|
+
readonly base: string;
|
|
78
|
+
readonly paths: readonly (readonly [string, readonly string[]])[];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Whether a module specifier is one that no npm package can have, such as `@/store` or `~/store`, which only a project's alias resolves. */
|
|
82
|
+
export function isAliasSpecifier(specifier: string): boolean {
|
|
83
|
+
return /^[@~]\//.test(specifier);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The source a specifier resolves to from the source at `from`: a relative one as Node resolves it, and an alias specifier
|
|
88
|
+
* through the `paths` of the nearest `configs`, by directory, as TypeScript resolves it.
|
|
89
|
+
*/
|
|
90
|
+
export function resolveModule(from: string, specifier: string, sources: {has(path: string): boolean}, configs: ReadonlyMap<string, PathsConfig>): string | undefined {
|
|
91
|
+
if (!isAliasSpecifier(specifier)) return resolveRelative(from, specifier, sources);
|
|
92
|
+
const directory = [...configs.keys()].filter(dir => from.startsWith(dir)).sort((a, b) => b.length - a.length)[0];
|
|
93
|
+
const config = directory !== undefined ? configs.get(directory) : undefined;
|
|
94
|
+
if (!config) return undefined;
|
|
95
|
+
// TypeScript takes the pattern with the longest prefix before its `*`, so an exact pattern comes first
|
|
96
|
+
const matches = config.paths.flatMap(([pattern, targets]) => {
|
|
97
|
+
const star = pattern.indexOf("*");
|
|
98
|
+
if (star < 0) return pattern === specifier ? [{prefix: pattern.length, rest: "", targets}] : [];
|
|
99
|
+
const prefix = pattern.slice(0, star), suffix = pattern.slice(star + 1);
|
|
100
|
+
return specifier.length >= prefix.length + suffix.length && specifier.startsWith(prefix) && specifier.endsWith(suffix) ?
|
|
101
|
+
[{prefix: prefix.length, rest: specifier.slice(prefix.length, specifier.length - suffix.length), targets}] : [];
|
|
102
|
+
}).sort((a, b) => b.prefix - a.prefix);
|
|
103
|
+
for (const {rest, targets} of matches) {
|
|
104
|
+
for (const target of targets) {
|
|
105
|
+
const base = posix.normalize(posix.join(config.base || ".", target.replace("*", rest)));
|
|
106
|
+
const found = RESOLVED.map(suffix => base + suffix).find(path => sources.has(path));
|
|
107
|
+
if (found) return found;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
55
113
|
/** The source a relative module specifier resolves to from the source at `from`, as Node resolves it among `sources`. */
|
|
56
114
|
export function resolveRelative(from: string, specifier: string, sources: {has(path: string): boolean}): string | undefined {
|
|
57
115
|
if (!isRelativeSpecifier(specifier)) return undefined;
|
|
58
116
|
const base = posix.normalize(posix.join(posix.dirname(from), specifier));
|
|
59
117
|
return RESOLVED.map(suffix => base + suffix).find(path => sources.has(path));
|
|
60
118
|
}
|
|
119
|
+
|
|
120
|
+
/** Where module specifiers of a source resolve: relative ones as Node resolves them, bare ones through a `baseUrl` alias. */
|
|
121
|
+
export interface Resolver {
|
|
122
|
+
(from: string, specifier: string): string | undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The package a bare module specifier names, such as `@scope/name` for `@scope/name/sub`. */
|
|
126
|
+
export function packageName(specifier: string): string {
|
|
127
|
+
const parts = specifier.split("/");
|
|
128
|
+
return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Resolves relative specifiers among the scanned sources, and a bare one that no enclosing package
|
|
133
|
+
* declares from each of `roots`, the way a `baseUrl` of the package or the repository resolves it.
|
|
134
|
+
*/
|
|
135
|
+
export function resolver(modules: {has(path: string): boolean}, roots: readonly string[], declares: (name: string) => boolean): Resolver {
|
|
136
|
+
return (from, specifier) => {
|
|
137
|
+
const relative = resolveRelative(from, specifier, modules);
|
|
138
|
+
if (relative || isRelativeSpecifier(specifier) || specifier.startsWith("node:") || declares(packageName(specifier))) return relative;
|
|
139
|
+
for (const root of roots) {
|
|
140
|
+
const aliased = resolveRelative(posix.join(root || ".", "_"), `./${specifier}`, modules);
|
|
141
|
+
if (aliased) return aliased;
|
|
142
|
+
}
|
|
143
|
+
return undefined;
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Each name a named export clause exports, to the name it has in the module it comes from. */
|
|
148
|
+
export function exportedNames(clause: JS.NamedExports): Map<string, string> {
|
|
149
|
+
const names = new Map<string, string>();
|
|
150
|
+
for (const {element: exported} of clause.elements.elements) {
|
|
151
|
+
if (exported.kind !== JS.Kind.ExportSpecifier) continue;
|
|
152
|
+
const named = (exported as JS.ExportSpecifier).specifier;
|
|
153
|
+
if (isIdentifier(named)) names.set(named.simpleName, named.simpleName);
|
|
154
|
+
if (named.kind === JS.Kind.Alias && isIdentifier((named as JS.Alias).alias)) {
|
|
155
|
+
const property = (named as JS.Alias).propertyName.element;
|
|
156
|
+
names.set(((named as JS.Alias).alias as J.Identifier).simpleName,
|
|
157
|
+
isIdentifier(property) ? property.simpleName : String((property as J.Literal).value));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return names;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* {@link resolver}, and also a `@/` or `~/` path alias, onto the nearest of `roots` that holds a match, at the
|
|
165
|
+
* root or in its `src` directory. Where both hold one the alias is ambiguous and stays unresolved.
|
|
166
|
+
*/
|
|
167
|
+
export function aliasResolver(modules: {has(path: string): boolean}, roots: readonly string[], declares: (name: string) => boolean): Resolver {
|
|
168
|
+
const resolve = resolver(modules, roots, declares);
|
|
169
|
+
return (from, specifier) => {
|
|
170
|
+
if (!/^[@~]\//.test(specifier)) return resolve(from, specifier);
|
|
171
|
+
for (const root of roots) {
|
|
172
|
+
const found = [root, `${root}src/`]
|
|
173
|
+
.map(base => resolveRelative(posix.join(base || ".", "_"), `.${specifier.slice(1)}`, modules))
|
|
174
|
+
.filter((path): path is string => path !== undefined);
|
|
175
|
+
if (found.length > 0) return found.length === 1 ? found[0] : undefined;
|
|
176
|
+
}
|
|
177
|
+
return undefined;
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** A source's own exports, each exported name to the local name it exports, and its `export ... from` re-exports. */
|
|
182
|
+
export interface ModuleExports {
|
|
183
|
+
locals: ReadonlyMap<string, string>;
|
|
184
|
+
reExports: readonly {module: string, names: ReadonlyMap<string, string> | "*"}[];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function moduleExports(cu: JS.CompilationUnit): ModuleExports {
|
|
188
|
+
const locals = new Map<string, string>();
|
|
189
|
+
const reExports: {module: string, names: ReadonlyMap<string, string> | "*"}[] = [];
|
|
190
|
+
for (const {element} of cu.statements) {
|
|
191
|
+
if (element.kind === J.Kind.VariableDeclarations && (element as J.VariableDeclarations).modifiers.some(m => m.keyword === "export")) {
|
|
192
|
+
for (const {element: variable} of (element as J.VariableDeclarations).variables) {
|
|
193
|
+
if (isIdentifier(variable.name)) locals.set(variable.name.simpleName, variable.name.simpleName);
|
|
194
|
+
}
|
|
195
|
+
} else if (element.kind === J.Kind.MethodDeclaration || element.kind === J.Kind.ClassDeclaration) {
|
|
196
|
+
const declaration = element as J.MethodDeclaration | J.ClassDeclaration;
|
|
197
|
+
const keywords = declaration.modifiers.map(modifier => modifier.keyword);
|
|
198
|
+
if (keywords.includes("export")) locals.set(keywords.includes("default") ? "default" : declaration.name.simpleName, declaration.name.simpleName);
|
|
199
|
+
} else if (element.kind === JS.Kind.ExportAssignment) {
|
|
200
|
+
const value = (element as JS.ExportAssignment).expression.element;
|
|
201
|
+
if (isIdentifier(value) && !(element as JS.ExportAssignment).exportEquals) locals.set("default", value.simpleName);
|
|
202
|
+
} else if (element.kind === JS.Kind.ExportDeclaration) {
|
|
203
|
+
const {exportClause, moduleSpecifier, typeOnly} = element as JS.ExportDeclaration;
|
|
204
|
+
if (typeOnly.element) continue;
|
|
205
|
+
const specifier = moduleSpecifier?.element;
|
|
206
|
+
if (!specifier) {
|
|
207
|
+
if (exportClause?.kind === JS.Kind.NamedExports) exportedNames(exportClause as JS.NamedExports).forEach((local, exported) => locals.set(exported, local));
|
|
208
|
+
} else if (specifier.kind === J.Kind.Literal) {
|
|
209
|
+
const module = moduleNameOf(specifier as J.Literal);
|
|
210
|
+
if (exportClause?.kind === JS.Kind.NamedExports) reExports.push({module, names: exportedNames(exportClause as JS.NamedExports)});
|
|
211
|
+
// `export * as name from` binds a namespace, not the module's names
|
|
212
|
+
else if (exportClause?.kind !== JS.Kind.Alias) reExports.push({module, names: "*"});
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return {locals, reExports};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The directory of a `jsconfig.json` or `tsconfig.json`, as a prefix of the paths of the sources below it. */
|
|
220
|
+
export function configDirectory(sourcePath: string): string | undefined {
|
|
221
|
+
const match = /^(.*\/)?(?:jsconfig|tsconfig)\.json$/.exec(sourcePath);
|
|
222
|
+
return match ? match[1] ?? "" : undefined;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* The `paths` of a `jsconfig.json` or `tsconfig.json` at `sourcePath`, which may have comments and trailing commas, with
|
|
227
|
+
* targets resolving from its `baseUrl`, or from its directory without one. No `paths` where it `extends` another config and
|
|
228
|
+
* has no `paths` and `baseUrl` of its own, since the other one's, which this doesn't read, may set either.
|
|
229
|
+
*/
|
|
230
|
+
export function pathsConfig(sourcePath: string, text: string): PathsConfig | undefined {
|
|
231
|
+
const directory = configDirectory(sourcePath);
|
|
232
|
+
if (directory === undefined) return undefined;
|
|
233
|
+
let config: any;
|
|
234
|
+
try {
|
|
235
|
+
config = JSON.parse(withoutComments(text).replace(/,(\s*[}\]])/g, "$1"));
|
|
236
|
+
} catch {
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
const options = config?.compilerOptions;
|
|
240
|
+
if (typeof options?.paths !== "object" || options.paths === null || config.extends !== undefined && typeof options.baseUrl !== "string") return {base: directory, paths: []};
|
|
241
|
+
const base = posix.normalize(posix.join(directory || ".", typeof options.baseUrl === "string" ? options.baseUrl : "."));
|
|
242
|
+
const paths = Object.entries(options.paths)
|
|
243
|
+
.filter((entry): entry is [string, string[]] => Array.isArray(entry[1]) && entry[1].every(target => typeof target === "string"));
|
|
244
|
+
return {base: base === "." ? "" : base, paths};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Each directory's `paths`, keyed as {@link configDirectory} gives them. */
|
|
248
|
+
export type PathsConfigs = Map<string, PathsConfig & {typescript: boolean}>;
|
|
249
|
+
|
|
250
|
+
/** Adds the `paths` of `doc` to `configs` where it is a `jsconfig.json` or `tsconfig.json`. */
|
|
251
|
+
export async function addPathsConfig(configs: PathsConfigs, doc: Json.Document): Promise<void> {
|
|
252
|
+
const directory = configDirectory(doc.sourcePath);
|
|
253
|
+
if (directory === undefined) return;
|
|
254
|
+
const config = pathsConfig(doc.sourcePath, await TreePrinters.print(doc));
|
|
255
|
+
const typescript = doc.sourcePath.endsWith("tsconfig.json");
|
|
256
|
+
// As bundlers read them, a directory's `tsconfig.json` is its config, and its `jsconfig.json` only without one
|
|
257
|
+
if (config && (typescript || !configs.get(directory)?.typescript)) configs.set(directory, {...config, typescript});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** JSON text without the `//` and `/* *\/` comments outside its strings. */
|
|
261
|
+
function withoutComments(text: string): string {
|
|
262
|
+
let out = "";
|
|
263
|
+
for (let i = 0; i < text.length; i++) {
|
|
264
|
+
const c = text[i];
|
|
265
|
+
if (c === '"') {
|
|
266
|
+
const end = /"((?:[^"\\]|\\.)*)"/y;
|
|
267
|
+
end.lastIndex = i;
|
|
268
|
+
const string = end.exec(text);
|
|
269
|
+
if (!string) return out + text.slice(i);
|
|
270
|
+
out += string[0];
|
|
271
|
+
i += string[0].length - 1;
|
|
272
|
+
} else if (c === "/" && text[i + 1] === "/") {
|
|
273
|
+
while (i < text.length && text[i] !== "\n") i++;
|
|
274
|
+
out += "\n";
|
|
275
|
+
} else if (c === "/" && text[i + 1] === "*") {
|
|
276
|
+
const close = text.indexOf("*/", i + 2);
|
|
277
|
+
i = close < 0 ? text.length : close + 1;
|
|
278
|
+
} else {
|
|
279
|
+
out += c;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
283
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import {ExecutionContext, TreePrinters} from "@openrewrite/rewrite";
|
|
2
|
+
import {J, isIdentifier} from "@openrewrite/rewrite/java";
|
|
3
|
+
import {JavaScriptParser, JS, namesReferencedWithin} from "@openrewrite/rewrite/javascript";
|
|
4
|
+
import {importBindings} from "../util/module-imports";
|
|
5
|
+
import {storeFunctions} from "./redux-stores";
|
|
6
|
+
|
|
7
|
+
/** The module, beside the source that creates a store it doesn't export, that the store moves to. */
|
|
8
|
+
export const ENTRY_STORE_MODULE = "appStore";
|
|
9
|
+
|
|
10
|
+
/** A source that creates a store it doesn't export, split into the module the store moves to and what the source keeps. */
|
|
11
|
+
export interface EntrySplit {
|
|
12
|
+
/** The source as it is once the store has moved, importing it back. */
|
|
13
|
+
readonly entry: JS.CompilationUnit;
|
|
14
|
+
/** The new module: the store, exported, with the declarations and imports that only it uses. */
|
|
15
|
+
readonly module: JS.CompilationUnit;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Splits `cu`, which creates the store `name` in a top-level `const` or `let` it doesn't export, so that the store
|
|
20
|
+
* moves to `modulePath` with the top-level declarations and imports that only it uses, and `cu` imports it back from
|
|
21
|
+
* there. Undefined where the store isn't declared so, or where what moves is used by what stays.
|
|
22
|
+
*/
|
|
23
|
+
export async function splitEntryStore(cu: JS.CompilationUnit, name: string, modulePath: string, ctx: ExecutionContext): Promise<EntrySplit | undefined> {
|
|
24
|
+
const statements = cu.statements.map(s => s.element);
|
|
25
|
+
const functions = storeFunctions(cu);
|
|
26
|
+
const index = statements.findIndex(statement => {
|
|
27
|
+
if (statement.kind !== J.Kind.VariableDeclarations) return false;
|
|
28
|
+
const declarations = statement as J.VariableDeclarations;
|
|
29
|
+
const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
|
|
30
|
+
const call = variable?.initializer?.element;
|
|
31
|
+
return !!variable && isIdentifier(variable.name) && variable.name.simpleName === name &&
|
|
32
|
+
!declarations.modifiers.some(m => m.keyword === "export") && call?.kind === J.Kind.MethodInvocation &&
|
|
33
|
+
!(call as J.MethodInvocation).select && (functions.legacy.has((call as J.MethodInvocation).name.simpleName) || functions.configure.has((call as J.MethodInvocation).name.simpleName));
|
|
34
|
+
});
|
|
35
|
+
if (index < 0) return undefined;
|
|
36
|
+
// What each top-level statement declares: its variables, or the local names of its imports
|
|
37
|
+
const declared = statements.map((statement, i) => {
|
|
38
|
+
if (statement.kind === JS.Kind.Import) return new Set(importBindings({...cu, statements: [cu.statements[i]]}).map(b => b.local));
|
|
39
|
+
if (statement.kind === J.Kind.VariableDeclarations) {
|
|
40
|
+
const variables = (statement as J.VariableDeclarations).variables.map(v => v.element.name);
|
|
41
|
+
return variables.every(isIdentifier) ? new Set(variables.map(v => (v as J.Identifier).simpleName)) : undefined;
|
|
42
|
+
}
|
|
43
|
+
if (statement.kind === J.Kind.MethodDeclaration) return new Set([(statement as J.MethodDeclaration).name.simpleName]);
|
|
44
|
+
if (statement.kind === J.Kind.ClassDeclaration) return new Set([(statement as J.ClassDeclaration).name.simpleName]);
|
|
45
|
+
return new Set<string>();
|
|
46
|
+
});
|
|
47
|
+
// The store's declaration, and the declarations and imports of the names it refers to, and of those they refer to
|
|
48
|
+
const moved = new Set([index]);
|
|
49
|
+
const pending = [index];
|
|
50
|
+
while (pending.length > 0) {
|
|
51
|
+
const referenced = namesReferencedWithin(statements[pending.pop()!]);
|
|
52
|
+
for (let i = 0; i < statements.length; i++) {
|
|
53
|
+
if (moved.has(i) || ![...referenced].some(n => declared[i]?.has(n))) continue;
|
|
54
|
+
// A function or class moves with what it may close over, which the store's source doesn't say
|
|
55
|
+
if (declared[i] === undefined || statements[i].kind !== JS.Kind.Import && statements[i].kind !== J.Kind.VariableDeclarations) return undefined;
|
|
56
|
+
moved.add(i);
|
|
57
|
+
pending.push(i);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// What stays may refer to the store, which it imports back, and to nothing else that moves
|
|
61
|
+
const movedNames = new Set([...moved].flatMap(i => [...declared[i]!]).filter(n => n !== name));
|
|
62
|
+
for (let i = 0; i < statements.length; i++) {
|
|
63
|
+
if (!moved.has(i) && [...namesReferencedWithin(statements[i])].some(n => movedNames.has(n))) return undefined;
|
|
64
|
+
}
|
|
65
|
+
// The source's own prefix, such as a license header, prints once, at the top of what the source keeps
|
|
66
|
+
const nothing = {...cu.prefix, whitespace: "", comments: []};
|
|
67
|
+
const printed = async (statement: J.RightPadded<J>) => await TreePrinters.print({...cu, prefix: nothing, statements: [statement], eof: {...cu.eof, whitespace: ""}} as JS.CompilationUnit);
|
|
68
|
+
const print = async (i: number) => await printed(cu.statements[i]);
|
|
69
|
+
const bare = async (i: number) => await printed({...cu.statements[i], element: {...statements[i], prefix: {...statements[i].prefix, whitespace: "", comments: []}}});
|
|
70
|
+
const header = await TreePrinters.print({...cu, statements: [], eof: {...cu.eof, whitespace: ""}} as JS.CompilationUnit);
|
|
71
|
+
// So does what comes before the first statement, where that statement moves
|
|
72
|
+
const lead = moved.has(0) ? (await print(0)).slice(0, (await print(0)).length - (await bare(0)).length) : "";
|
|
73
|
+
const order = [...moved].sort((a, b) => a - b);
|
|
74
|
+
let module = "";
|
|
75
|
+
for (const i of order) {
|
|
76
|
+
const text = i === 0 ? await bare(0) : await print(i);
|
|
77
|
+
if (i !== index) {
|
|
78
|
+
module += text;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
const stripped = await bare(i);
|
|
82
|
+
module += text.slice(0, text.length - stripped.length) + "export " + stripped;
|
|
83
|
+
}
|
|
84
|
+
module = module.replace(/^\s+/, "") + "\n";
|
|
85
|
+
// The store comes back where the first import that moved was, or after the imports
|
|
86
|
+
const firstImport = order.find(i => statements[i].kind === JS.Kind.Import);
|
|
87
|
+
const lastImport = statements.reduce((last, s, i) => s.kind === JS.Kind.Import && !moved.has(i) ? i : last, -1);
|
|
88
|
+
const at = firstImport ?? lastImport + 1;
|
|
89
|
+
const quote = quoteOf(statements) ?? "'";
|
|
90
|
+
const imports = statements.map((_, i) => i).filter(i => statements[i].kind === JS.Kind.Import);
|
|
91
|
+
const semicolon = imports.length === 0 || (await print(imports[0])).trimEnd().endsWith(";");
|
|
92
|
+
const specifier = `./${modulePath.slice(modulePath.lastIndexOf("/") + 1).replace(/\.[^.]+$/, "")}`;
|
|
93
|
+
const back = `import {${name}} from ${quote}${specifier}${quote}${semicolon ? ";" : ""}`;
|
|
94
|
+
let entry = header + lead;
|
|
95
|
+
// What follows statements that moved keeps the blank lines before the first of them
|
|
96
|
+
let gap: string | undefined;
|
|
97
|
+
for (let i = 0; i < statements.length; i++) {
|
|
98
|
+
if (i === at) entry += (i === 0 ? "" : "\n") + back;
|
|
99
|
+
if (moved.has(i)) {
|
|
100
|
+
gap ??= statements[i].prefix.whitespace;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
let text = await print(i);
|
|
104
|
+
const space = text.match(/^\s*/)![0];
|
|
105
|
+
if (gap !== undefined && i !== at && newlines(gap) > newlines(space)) text = gap + text.slice(space.length);
|
|
106
|
+
gap = undefined;
|
|
107
|
+
entry += text;
|
|
108
|
+
}
|
|
109
|
+
if (at >= statements.length) entry += "\n" + back;
|
|
110
|
+
entry += cu.eof.whitespace;
|
|
111
|
+
const parser = new JavaScriptParser({ctx});
|
|
112
|
+
const parsed = await parser.parseOne({text: entry, sourcePath: cu.sourcePath}) as JS.CompilationUnit;
|
|
113
|
+
const generated = await parser.parseOne({text: module, sourcePath: modulePath}) as JS.CompilationUnit;
|
|
114
|
+
return {
|
|
115
|
+
// The source stays the file it was, which the host matches by id and writes in its charset
|
|
116
|
+
entry: {...parsed, id: cu.id, markers: cu.markers, charsetName: cu.charsetName, charsetBomMarked: cu.charsetBomMarked, checksum: cu.checksum, fileAttributes: cu.fileAttributes},
|
|
117
|
+
module: {...generated, charsetName: generated.charsetName ?? cu.charsetName ?? "UTF-8", charsetBomMarked: false}
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const newlines = (whitespace: string) => whitespace.split("\n").length - 1;
|
|
122
|
+
|
|
123
|
+
function quoteOf(statements: readonly J[]): "'" | '"' | undefined {
|
|
124
|
+
for (const element of statements) {
|
|
125
|
+
const specifier = element.kind === JS.Kind.Import ? (element as JS.Import).moduleSpecifier?.element : undefined;
|
|
126
|
+
const source = specifier?.kind === J.Kind.Literal ? (specifier as J.Literal).valueSource : undefined;
|
|
127
|
+
if (source?.startsWith("'")) return "'";
|
|
128
|
+
if (source?.startsWith('"')) return '"';
|
|
129
|
+
}
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|