@openrewrite/recipes-react 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/dist/index.d.ts.map +1 -1
  2. package/dist/index.js +1 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
  6. package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
  7. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
  8. package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
  9. package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
  10. package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
  11. package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
  12. package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
  13. package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
  14. package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
  15. package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
  16. package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
  17. package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
  18. package/dist/migration/cra-to-vite/cra-script.js +82 -0
  19. package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
  20. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
  21. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
  22. package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
  23. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
  24. package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
  25. package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
  26. package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
  27. package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
  28. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  29. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +2 -1
  30. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  31. package/dist/migration/cra-to-vite/index.d.ts +8 -2
  32. package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
  33. package/dist/migration/cra-to-vite/index.js +17 -2
  34. package/dist/migration/cra-to-vite/index.js.map +1 -1
  35. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
  36. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
  37. package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
  38. package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
  39. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
  40. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
  41. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
  42. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
  43. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
  44. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
  45. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
  46. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
  47. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
  48. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
  49. package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
  50. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
  51. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
  52. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
  53. package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
  54. package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
  55. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
  56. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
  57. package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
  58. package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
  59. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
  60. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
  61. package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
  62. package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
  63. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
  64. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
  65. package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
  66. package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
  67. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
  68. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
  69. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
  70. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
  71. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
  72. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
  73. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
  74. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -30
  75. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
  76. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
  77. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
  78. package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
  79. package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
  80. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
  81. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
  82. package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
  83. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
  84. package/dist/migration/cra-to-vite/shared.d.ts +1 -1
  85. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  86. package/dist/migration/cra-to-vite/shared.js +19 -4
  87. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  88. package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
  89. package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
  90. package/dist/migration/cra-to-vite/svg-component.js +60 -0
  91. package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
  92. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  93. package/dist/migration/cra-to-vite/update-react-app-env-types.js +8 -2
  94. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  95. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
  96. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
  97. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +18 -14
  98. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
  99. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  100. package/dist/react18/replace-reactdom-render.js +16 -8
  101. package/dist/react18/replace-reactdom-render.js.map +1 -1
  102. package/dist/testing/enzyme-constant-strings.d.ts +12 -0
  103. package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
  104. package/dist/testing/enzyme-constant-strings.js +101 -0
  105. package/dist/testing/enzyme-constant-strings.js.map +1 -0
  106. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  107. package/dist/testing/enzyme-host-components.js +5 -2
  108. package/dist/testing/enzyme-host-components.js.map +1 -1
  109. package/dist/testing/enzyme-portals.d.ts +38 -0
  110. package/dist/testing/enzyme-portals.d.ts.map +1 -0
  111. package/dist/testing/enzyme-portals.js +226 -0
  112. package/dist/testing/enzyme-portals.js.map +1 -0
  113. package/dist/testing/enzyme-selector-names.d.ts +9 -0
  114. package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
  115. package/dist/testing/enzyme-selector-names.js +50 -0
  116. package/dist/testing/enzyme-selector-names.js.map +1 -0
  117. package/dist/testing/enzyme-to-react-testing-library.d.ts +71 -8
  118. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  119. package/dist/testing/enzyme-to-react-testing-library.js +321 -34
  120. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  121. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  122. package/dist/testing/enzyme-usage.js +27 -4
  123. package/dist/testing/enzyme-usage.js.map +1 -1
  124. package/dist/testing/enzyme-wrapper-scope.d.ts +12 -6
  125. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  126. package/dist/testing/enzyme-wrapper-scope.js +140 -16
  127. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  128. package/dist/util/java-recipe-proxy.d.ts +16 -0
  129. package/dist/util/java-recipe-proxy.d.ts.map +1 -0
  130. package/dist/util/java-recipe-proxy.js +85 -0
  131. package/dist/util/java-recipe-proxy.js.map +1 -0
  132. package/dist/util/module-imports.d.ts +1 -0
  133. package/dist/util/module-imports.d.ts.map +1 -1
  134. package/dist/util/module-imports.js +5 -1
  135. package/dist/util/module-imports.js.map +1 -1
  136. package/package.json +2 -2
  137. package/src/index.ts +2 -1
  138. package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
  139. package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
  140. package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
  141. package/src/migration/cra-to-vite/cra-script.ts +61 -0
  142. package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
  143. package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
  144. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +2 -1
  145. package/src/migration/cra-to-vite/index.ts +10 -2
  146. package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
  147. package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
  148. package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
  149. package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
  150. package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
  151. package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
  152. package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
  153. package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
  154. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
  155. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
  156. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +52 -33
  157. package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
  158. package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
  159. package/src/migration/cra-to-vite/shared.ts +20 -10
  160. package/src/migration/cra-to-vite/svg-component.ts +39 -0
  161. package/src/migration/cra-to-vite/update-react-app-env-types.ts +11 -4
  162. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +22 -28
  163. package/src/react18/replace-reactdom-render.ts +17 -8
  164. package/src/testing/enzyme-constant-strings.ts +95 -0
  165. package/src/testing/enzyme-host-components.ts +6 -2
  166. package/src/testing/enzyme-portals.ts +279 -0
  167. package/src/testing/enzyme-selector-names.ts +59 -0
  168. package/src/testing/enzyme-to-react-testing-library.ts +425 -50
  169. package/src/testing/enzyme-usage.ts +29 -4
  170. package/src/testing/enzyme-wrapper-scope.ts +181 -30
  171. package/src/util/java-recipe-proxy.ts +81 -0
  172. package/src/util/module-imports.ts +6 -1
@@ -1,61 +1,55 @@
1
- import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {craScript} from './cra-script';
2
+ import {ExecutionContext, Parsers, SourceFile, TreeVisitor} from "@openrewrite/rewrite";
2
3
  import {getMemberKeyName, isObject, Json, jsonLiteral, JsonVisitor, membersOf, removeAt, setAt} from "@openrewrite/rewrite/json";
3
4
  import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
4
- import {dirName, isPackageJson, memberObject, runsOnVite, stringValue} from "./shared";
5
-
6
- /** Only an exact match is rewritten: extra flags or environment prefixes need a human. */
7
- const SCRIPT_REPLACEMENTS = new Map<string, string>([
8
- ["react-scripts start", "vite"],
9
- ["react-scripts build", "vite build"],
10
- ]);
11
-
12
- /** `react-scripts build` fails the build on type errors; `vite build` does not type-check, so a project with a tsconfig keeps the check. */
13
- const TYPE_CHECKED_BUILD = "tsc --noEmit && vite build";
5
+ import {dirName, isPackageJson, joinPath, memberObject, stringValue} from "./shared";
6
+ import {CRA_TYPECHECK_PATH, CRA_TYPECHECK_SCRIPT} from './cra-typecheck';
14
7
 
15
8
  /**
16
- * Rewrites scripts whose command is exactly `react-scripts start` and `react-scripts build`.
9
+ * Rewrites CRA start/build commands and literal HOST, PORT, PUBLIC_URL and BUILD_PATH controls.
17
10
  *
18
11
  * ```json
19
12
  * "start": "react-scripts start" -> "start": "vite"
20
13
  * "build": "react-scripts build" -> "build": "vite build"
21
- * "build": "react-scripts build" -> "build": "tsc --noEmit && vite build" (when there is a tsconfig.json)
14
+ * "build": "react-scripts build" -> "build": "node scripts/vite-typecheck.cjs && vite build" (when there is a tsconfig.json)
22
15
  * "eject": "react-scripts eject" -> (removed)
23
16
  * ```
24
17
  *
25
18
  * `react-scripts build` failed on type errors and `vite build` does not type-check, so a package with a `tsconfig.json`
26
- * keeps the check. `--noEmit` rather than `tsc -b`, because the CRA tsconfig sets `noEmit` and `tsc -b` rejects that before TypeScript 5.6.
19
+ * keeps a checker that reports production diagnostics under `src/`, matching CRA's scope.
27
20
  *
28
- * Only packages that depend on `react-scripts` change; in a workspace that hoists it the scripts are left alone. A package
29
- * with a script that wraps `react-scripts start|build` or runs `craco` is not edited at all, because a half-migrated
30
- * package has no working `start`. Scripts with extra flags (`cross-env PORT=4000 react-scripts start`) and `test` are left for
31
- * `FindCraToViteBlockers` to flag.
21
+ * Custom shell commands, HTTPS configuration, unknown flags and wrapper tools require manual review.
22
+ * Tests are left for the separate Vitest migration.
32
23
  *
33
24
  * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
34
25
  */
35
26
  export class UpdateReactScriptsScripts extends CraScanningRecipe {
36
27
  readonly name = "org.openrewrite.react.cra-to-vite.update-package-scripts";
37
28
  readonly displayName = "Replace `react-scripts` start and build scripts with Vite";
38
- readonly description = "Rewrites `package.json` scripts that are exactly `react-scripts start` or `react-scripts build` to `vite` and `vite build` (`tsc --noEmit && vite build` when there is a `tsconfig.json`), and removes the `react-scripts eject` script, in packages that depend on `react-scripts`. Packages with `craco`, `react-app-rewired` or wrapped `start` or `build` scripts are left unchanged, as is the `test` script.";
29
+ readonly description = "Replaces CRA start/build scripts with Vite, preserving literal HOST, PORT, PUBLIC_URL and BUILD_PATH settings as CLI options and retaining production TypeScript checking. Removes eject. Custom wrappers, unknown shell syntax and test scripts are left unchanged.";
30
+
31
+ override async generate(acc: CraProjects, ctx: ExecutionContext): Promise<SourceFile[]> {
32
+ const parser = Parsers.createParser('plainText', {ctx});
33
+ return Promise.all([...acc.viteRoots].filter(root => acc.mayMigrate(root) && acc.has(root, 'tsconfig.json') && !acc.has(root, CRA_TYPECHECK_PATH))
34
+ .map(root => parser.parseOne({text: CRA_TYPECHECK_SCRIPT, sourcePath: joinPath(root, CRA_TYPECHECK_PATH)})));
35
+ }
39
36
 
40
37
  async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
41
38
  return new class extends JsonVisitor<ExecutionContext> {
42
39
  protected override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
43
- if (!isPackageJson(doc.sourcePath) || !isObject(doc.value) || !runsOnVite(doc.value)) return doc;
40
+ if (!isPackageJson(doc.sourcePath) || !isObject(doc.value) || !acc.isViteFile(doc.sourcePath)) return doc;
41
+ if (acc.has(dirName(doc.sourcePath), 'tsconfig.json') && acc.has(dirName(doc.sourcePath), CRA_TYPECHECK_PATH)) return doc;
44
42
  const scripts = memberObject(doc.value, "scripts");
45
43
  if (!scripts) return doc;
46
- const build = acc.has(dirName(doc.sourcePath), "tsconfig.json") ? TYPE_CHECKED_BUILD : "vite build";
47
44
  let updated = doc;
48
45
  for (const m of membersOf(scripts)) {
49
46
  const name = getMemberKeyName(m);
50
47
  const command = stringValue(m.value)?.trim();
51
48
  if (name === undefined || command === undefined) continue;
52
- // `eject` has no Vite equivalent and is the last thing that keeps react-scripts installed.
53
- if (command === "react-scripts eject") {
54
- updated = removeAt(updated, ["scripts", name]);
55
- continue;
56
- }
57
- const replacement = SCRIPT_REPLACEMENTS.get(command);
58
- if (replacement) updated = setAt(updated, ["scripts", name], jsonLiteral(replacement === "vite build" ? build : replacement));
49
+ const migrated = craScript(command, acc.has(dirName(doc.sourcePath), 'tsconfig.json'));
50
+ if (!migrated || migrated.operation === 'test') continue;
51
+ updated = migrated.replacement === null ? removeAt(updated, ['scripts', name]) :
52
+ setAt(updated, ['scripts', name], jsonLiteral(migrated.replacement));
59
53
  }
60
54
  return updated;
61
55
  }
@@ -1,6 +1,7 @@
1
- import {check, ExecutionContext, foundSearchResult, not, printer, Recipe, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {check, ExecutionContext, foundSearchResult, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
2
  import {
3
3
  capture,
4
+ isEqual,
4
5
  isVendoredOrBundled,
5
6
  JavaScriptVisitor,
6
7
  JS,
@@ -27,6 +28,7 @@ const RESULT_IS_USED = `\`root.render()\` returns \`void\`, not the component in
27
28
  * statement that renders a container once is rewritten. A call inside a function (it may run again
28
29
  * and would create a second root), a call whose result is used (`root.render()` returns `void`),
29
30
  * a container rendered twice, and a file that already uses the name `root` are marked instead.
31
+ * Only the first container in a file is rewritten, as the next one would redeclare `root`.
30
32
  *
31
33
  * Before:
32
34
  * ```tsx
@@ -46,7 +48,7 @@ const RESULT_IS_USED = `\`root.render()\` returns \`void\`, not the component in
46
48
  export class ReplaceReactDomRender extends Recipe {
47
49
  readonly name = "org.openrewrite.react.18.replace-reactdom-render";
48
50
  readonly displayName: string = "Replace `ReactDOM.render` with `createRoot`";
49
- readonly description: string = "Migrates a top-level `ReactDOM.render()` call to the `createRoot()` API from `react-dom/client` introduced in React 18, creating the root once. Calls inside functions, calls whose result is used and containers that are rendered more than once are marked for manual migration.";
51
+ readonly description: string = "Migrates a top-level `ReactDOM.render()` call to the `createRoot()` API from `react-dom/client` introduced in React 18, creating the root once. Calls inside functions, calls whose result is used and containers that are rendered more than once are marked for manual migration, as is every container after the first in a file, since each would redeclare `root`.";
50
52
 
51
53
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
52
54
  const element = capture<Expression>();
@@ -69,12 +71,12 @@ export class ReplaceReactDomRender extends Recipe {
69
71
  }));
70
72
 
71
73
  return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
72
- private containerCounts = new Map<string, number>();
74
+ private containers: Expression[] = [];
73
75
  private rootNameTaken = false;
74
76
  private inlinedBlocks = new Set<string>();
75
77
 
76
78
  override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
77
- this.containerCounts = new Map();
79
+ this.containers = [];
78
80
  this.rootNameTaken = false;
79
81
  this.inlinedBlocks = new Set();
80
82
  await this.survey(cu);
@@ -94,8 +96,7 @@ export class ReplaceReactDomRender extends Recipe {
94
96
  if (position === "used") {
95
97
  return foundSearchResult(m, RESULT_IS_USED);
96
98
  }
97
- const containerSource = (await printer(this.cursor).print(match.get(container)!)).trim();
98
- if (position === "nested" || this.rootNameTaken || this.containerCounts.get(containerSource)! > 1) {
99
+ if (position === "nested" || this.rootNameTaken || await this.rendersInto(match.get(container)!) > 1) {
99
100
  return foundSearchResult(m, ONE_ROOT_PER_CONTAINER);
100
101
  }
101
102
 
@@ -104,6 +105,7 @@ export class ReplaceReactDomRender extends Recipe {
104
105
  return m;
105
106
  }
106
107
  maybeRemoveImport(this, "react-dom", "render");
108
+ this.rootNameTaken = true;
107
109
  this.inlinedBlocks.add(result.id);
108
110
  return result;
109
111
  }
@@ -134,6 +136,14 @@ export class ReplaceReactDomRender extends Recipe {
134
136
  return "used";
135
137
  }
136
138
 
139
+ private async rendersInto(target: Expression): Promise<number> {
140
+ let count = 0;
141
+ for (const c of this.containers) {
142
+ if (await isEqual(c, target)) count++;
143
+ }
144
+ return count;
145
+ }
146
+
137
147
  private async survey(cu: JS.CompilationUnit): Promise<void> {
138
148
  const outer = this;
139
149
  await new class extends JavaScriptVisitor<void> {
@@ -147,8 +157,7 @@ export class ReplaceReactDomRender extends Recipe {
147
157
  override async visitMethodInvocation(m: J.MethodInvocation, q: void): Promise<J | undefined> {
148
158
  const match = await renderPattern.match(m, this.cursor);
149
159
  if (match) {
150
- const source = (await printer(this.cursor).print(match.get(container)!)).trim();
151
- outer.containerCounts.set(source, (outer.containerCounts.get(source) ?? 0) + 1);
160
+ outer.containers.push(match.get(container)!);
152
161
  }
153
162
  return super.visitMethodInvocation(m, q);
154
163
  }
@@ -0,0 +1,95 @@
1
+ import {JS} from "@openrewrite/rewrite/javascript";
2
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
3
+ import {Modules, Resolver} from "./enzyme-portals";
4
+
5
+ /** A string a `const` holds, as literal text and the names whose strings its template interpolates. */
6
+ export type ConstantParts = readonly ({text: string} | {name: string})[];
7
+
8
+ /** The `const` declarations of a source's top level that hold a string literal or a template of other names. */
9
+ export function constantStrings(cu: JS.CompilationUnit): Map<string, ConstantParts> {
10
+ const strings = new Map<string, ConstantParts>();
11
+ for (const {element} of cu.statements) {
12
+ const declarations = (element.kind === JS.Kind.ExportDeclaration ? (element as JS.ExportDeclaration).exportClause : element) as J | undefined;
13
+ if (declarations?.kind !== J.Kind.VariableDeclarations) continue;
14
+ const variables = declarations as J.VariableDeclarations;
15
+ if (!variables.modifiers.some(modifier => modifier.keyword === "const")) continue;
16
+ for (const {element: variable} of variables.variables) {
17
+ const name = variable.name;
18
+ const parts = variable.initializer && isIdentifier(name) ? stringParts(variable.initializer.element) : undefined;
19
+ if (parts && isIdentifier(name)) strings.set(name.simpleName, parts);
20
+ }
21
+ }
22
+ return strings;
23
+ }
24
+
25
+ /** A string literal, or a template whose every interpolation is a bare name, as parts; anything else is not constant. */
26
+ export function stringParts(node: J): ConstantParts | undefined {
27
+ if (node.kind === J.Kind.Literal) return typeof (node as J.Literal).value === "string" ? [{text: (node as J.Literal).value as string}] : undefined;
28
+ if (node.kind !== JS.Kind.TemplateExpression) return undefined;
29
+ const template = node as JS.TemplateExpression;
30
+ const parts: ({text: string} | {name: string})[] = [];
31
+ const text = (literal: J.Literal) => typeof literal.value === "string" ? literal.value : undefined;
32
+ const head = text(template.head);
33
+ if (head === undefined) return undefined;
34
+ parts.push({text: head});
35
+ for (const {element: span} of template.spans) {
36
+ const tail = text(span.tail);
37
+ if (!isIdentifier(span.expression) || tail === undefined) return undefined;
38
+ parts.push({name: span.expression.simpleName}, {text: tail});
39
+ }
40
+ return parts;
41
+ }
42
+
43
+ /**
44
+ * The string `parts` evaluate to in the source at `path`, following each name to a `const` of that source, or
45
+ * through its imports and re-exports to one of the module it names, as {@link resolve} finds the module.
46
+ */
47
+ export function evaluate(parts: ConstantParts, path: string, modules: Modules, resolve: Resolver, seen = new Set<string>()): string | undefined {
48
+ let value = "";
49
+ for (const part of parts) {
50
+ if ("text" in part) {
51
+ value += part.text;
52
+ continue;
53
+ }
54
+ const named = constantOf(path, part.name, modules, resolve, seen);
55
+ if (named === undefined) return undefined;
56
+ value += named;
57
+ }
58
+ return value;
59
+ }
60
+
61
+ /** The string the binding `name` of the source at `path` holds, where it is a constant one. */
62
+ function constantOf(path: string, name: string, modules: Modules, resolve: Resolver, seen: Set<string>): string | undefined {
63
+ const key = `${path}#${name}`;
64
+ if (seen.has(key)) return undefined;
65
+ seen.add(key);
66
+ try {
67
+ const facts = modules.get(path);
68
+ if (!facts) return undefined;
69
+ const own = facts.strings.get(name);
70
+ if (own) return evaluate(own, path, modules, resolve, seen);
71
+ const imported = facts.imports.get(name) ?? facts.forwards.get(name);
72
+ if (imported) {
73
+ const target = resolve(path, imported.module);
74
+ return target === undefined ? undefined : exportedConstant(target, imported.name, modules, resolve, seen);
75
+ }
76
+ return undefined;
77
+ } finally {
78
+ seen.delete(key);
79
+ }
80
+ }
81
+
82
+ /** The string the export `name` of the source at `path` holds, through the names it forwards or re-exports. */
83
+ function exportedConstant(path: string, name: string, modules: Modules, resolve: Resolver, seen: Set<string>): string | undefined {
84
+ const facts = modules.get(path);
85
+ if (!facts) return undefined;
86
+ if (facts.strings.has(name) || facts.forwards.has(name)) return constantOf(path, name, modules, resolve, seen);
87
+ for (const {module, names} of facts.reExports) {
88
+ const exported = names === "*" ? name : names.get(name);
89
+ if (exported === undefined) continue;
90
+ const target = resolve(path, module);
91
+ const value = target === undefined ? undefined : exportedConstant(target, exported, modules, resolve, seen);
92
+ if (value !== undefined) return value;
93
+ }
94
+ return undefined;
95
+ }
@@ -223,7 +223,7 @@ export function hostComponentExports(cu: JS.CompilationUnit): ReadonlySet<string
223
223
  const bindings = importBindings(cu);
224
224
  // A hook React declares behaves alike only where it is React's own
225
225
  if (bindings.some(({local, module}) => HOOK.test(local) && module !== "react")) return NONE;
226
- const imports = new Set([...bindings.map(({local}) => local), ...namespaceImports(cu)]);
226
+ const imports = localNames(bindings, cu);
227
227
  if (!hostElementsOnly(cu, imports)) return NONE;
228
228
  // What a component returns is checked as a child is, since a helper may return any element
229
229
  const exported = [...candidates].filter(([, renders]) => returnsAsHost(renders, imports)).map(([name]) => name);
@@ -232,7 +232,11 @@ export function hostComponentExports(cu: JS.CompilationUnit): ReadonlySet<string
232
232
 
233
233
  /** Each local name a source binds with an import, including namespace imports. */
234
234
  export function importedNames(cu: JS.CompilationUnit): ReadonlySet<string> {
235
- return new Set([...importBindings(cu).map(({local}) => local), ...namespaceImports(cu)]);
235
+ return localNames(importBindings(cu), cu);
236
+ }
237
+
238
+ function localNames(bindings: ReturnType<typeof importBindings>, cu: JS.CompilationUnit): ReadonlySet<string> {
239
+ return new Set([...bindings.map(({local}) => local), ...namespaceImports(cu)]);
236
240
  }
237
241
 
238
242
  /** Each local name a source binds to an export of another scanned source. */
@@ -0,0 +1,279 @@
1
+ import {JS, JSX, moduleNameOf, walk} from "@openrewrite/rewrite/javascript";
2
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
3
+ import {posix} from "path";
4
+ import {importBindings, isRelativeSpecifier, resolveRelative} from "../util/module-imports";
5
+ import {ConstantParts, constantStrings} from "./enzyme-constant-strings";
6
+
7
+ /** An import a source renders: the module, and the export of it that a JSX tag in the source names. */
8
+ export interface RenderedImport {
9
+ module: string;
10
+ name: string;
11
+ }
12
+
13
+ /** A re-export from another module: each exported name to the name it has there, or every name for `export *`. */
14
+ export interface ReExport {
15
+ module: string;
16
+ names: ReadonlyMap<string, string> | "*";
17
+ }
18
+
19
+ /** What the scanner keeps of each JavaScript or TypeScript source to decide whether a component it exports renders into a portal. */
20
+ export interface ModuleFacts {
21
+ /** Whether the source calls `createPortal`. */
22
+ portal: boolean;
23
+ rendered: readonly RenderedImport[];
24
+ reExports: readonly ReExport[];
25
+ /** The names the source declares itself, as opposed to re-exporting. */
26
+ declares: ReadonlySet<string>;
27
+ /** Exports of an imported binding, such as `export default Tooltip` after `import Tooltip from './tooltip'`. */
28
+ forwards: ReadonlyMap<string, RenderedImport>;
29
+ /** Each imported binding by its local name, with the module and the export of it the binding names. */
30
+ imports: ReadonlyMap<string, RenderedImport>;
31
+ /** The top-level `const` strings, which a selector built from them can be read through. */
32
+ strings: ReadonlyMap<string, ConstantParts>;
33
+ }
34
+
35
+ /** Each scanned source by path. */
36
+ export type Modules = Map<string, ModuleFacts>;
37
+
38
+ export function moduleFacts(cu: JS.CompilationUnit): ModuleFacts {
39
+ const tags = tagNames(cu);
40
+ const bindings = importBindings(cu);
41
+ const imported = new Map(bindings.map(({local, module, name}) => [local, {module, name}]));
42
+ const rendered = bindings.filter(({local}) => tags.has(local)).map(({module, name}) => ({module, name}));
43
+ const reExports: ReExport[] = [];
44
+ const forwards = new Map<string, RenderedImport>();
45
+ for (const {element} of cu.statements) {
46
+ if (element.kind === JS.Kind.ExportAssignment) {
47
+ const value = withoutTypeAssertions((element as JS.ExportAssignment).expression.element);
48
+ const binding = isIdentifier(value) ? imported.get(value.simpleName) : undefined;
49
+ if (binding) forwards.set("default", binding);
50
+ continue;
51
+ }
52
+ if (element.kind !== JS.Kind.ExportDeclaration) continue;
53
+ const declaration = element as JS.ExportDeclaration;
54
+ const specifier = declaration.moduleSpecifier?.element;
55
+ if (declaration.typeOnly.element) continue;
56
+ if (!specifier && declaration.exportClause?.kind === JS.Kind.NamedExports) {
57
+ for (const [exported, local] of exportedNames(declaration.exportClause as JS.NamedExports)) {
58
+ const binding = imported.get(local);
59
+ if (binding) forwards.set(exported, binding);
60
+ }
61
+ continue;
62
+ }
63
+ if (specifier?.kind !== J.Kind.Literal) continue;
64
+ const module = moduleNameOf(specifier as J.Literal);
65
+ const clause = declaration.exportClause;
66
+ if (clause?.kind !== JS.Kind.NamedExports) {
67
+ reExports.push({module, names: "*"});
68
+ continue;
69
+ }
70
+ reExports.push({module, names: exportedNames(clause as JS.NamedExports)});
71
+ }
72
+ const reExported = new Set(reExports.flatMap(({names}) => names === "*" ? [] : [...names.keys()]));
73
+ const declares = new Set([...localDeclarations(cu).keys(), "default"].filter(name => !reExported.has(name) && !forwards.has(name)));
74
+ return {portal: callsCreatePortal(cu), rendered, reExports, declares, forwards, imports: imported, strings: constantStrings(cu)};
75
+ }
76
+
77
+ /** Each name a named export clause exports, to the name it has in the module it comes from. */
78
+ function exportedNames(clause: JS.NamedExports): Map<string, string> {
79
+ const names = new Map<string, string>();
80
+ for (const {element: exported} of clause.elements.elements) {
81
+ if (exported.kind !== JS.Kind.ExportSpecifier) continue;
82
+ const named = (exported as JS.ExportSpecifier).specifier;
83
+ if (isIdentifier(named)) names.set(named.simpleName, named.simpleName);
84
+ if (named.kind === JS.Kind.Alias && isIdentifier((named as JS.Alias).alias)) {
85
+ const property = (named as JS.Alias).propertyName.element;
86
+ names.set(((named as JS.Alias).alias as J.Identifier).simpleName,
87
+ isIdentifier(property) ? property.simpleName : String((property as J.Literal).value));
88
+ }
89
+ }
90
+ return names;
91
+ }
92
+
93
+ /** Where module specifiers of a source resolve: relative ones as Node resolves them, bare ones through a `baseUrl` alias. */
94
+ export interface Resolver {
95
+ (from: string, specifier: string): string | undefined;
96
+ }
97
+
98
+ /**
99
+ * Whether the export `name` of the source at `path` may render into a portal: the source calls
100
+ * `createPortal`, renders a component imported from a source whose export may, or re-exports `name`
101
+ * from one. Imports a source does not render, such as utilities, are not followed.
102
+ */
103
+ export function reachesPortal(path: string, name: string, modules: Modules, resolve: Resolver, memo = new Map<string, boolean>()): boolean {
104
+ const key = `${path}#${name}`;
105
+ const known = memo.get(key);
106
+ if (known !== undefined) return known;
107
+ // A cycle is decided by the sources outside it
108
+ memo.set(key, false);
109
+ const facts = modules.get(path);
110
+ const follow = (module: string, exported: string) => {
111
+ const target = resolve(path, module);
112
+ return target !== undefined ? reachesPortal(target, exported, modules, resolve, memo) : packagePortal(module, exported);
113
+ };
114
+ const forward = facts?.forwards.get(name);
115
+ const reaches = !!facts && (forward ? follow(forward.module, forward.name) : facts.declares.has(name) ?
116
+ facts.portal || facts.rendered.some(({module, name}) => follow(module, name)) :
117
+ facts.reExports.some(({module, names}) => names === "*" ? follow(module, name) : names.has(name) && follow(module, names.get(name)!)));
118
+ memo.set(key, reaches);
119
+ return reaches;
120
+ }
121
+
122
+ const MUI_PORTALS = ["Modal", "Dialog", "Drawer", "SwipeableDrawer", "Popover", "Popper", "Menu", "Tooltip", "Select", "Autocomplete", "Portal"];
123
+ const BLUEPRINT_POPOVERS = ["Select", "Suggest", "MultiSelect", "Omnibar"];
124
+
125
+ /**
126
+ * Components of UI packages that render into a portal, at least when open, by the name the package exports
127
+ * them as, and `default` for a package whose default export does. The scanner does not see a package's
128
+ * sources, so these stand for what its `createPortal` calls would show. `@material-ui/core/Dialog` names
129
+ * its export by the subpath.
130
+ */
131
+ const PACKAGE_PORTALS: ReadonlyMap<string, ReadonlySet<string>> = new Map(Object.entries({
132
+ "@patternfly/react-core": ["Modal", "AboutModal", "Popover", "Tooltip"],
133
+ "antd": ["Modal", "Drawer", "Tooltip", "Popover", "Popconfirm", "Dropdown", "Select", "DatePicker", "TimePicker",
134
+ "Cascader", "TreeSelect", "AutoComplete", "Mentions", "Tour", "Image", "ColorPicker"],
135
+ "@mui/material": MUI_PORTALS,
136
+ "@material-ui/core": MUI_PORTALS,
137
+ "react-bootstrap": ["Modal", "Offcanvas", "Overlay", "OverlayTrigger"],
138
+ "reactstrap": ["Modal", "Tooltip", "UncontrolledTooltip", "Popover", "UncontrolledPopover", "Offcanvas"],
139
+ "@blueprintjs/core": ["Overlay", "Overlay2", "Dialog", "MultistepDialog", "Drawer", "Alert", "Popover", "Tooltip",
140
+ "Portal", "Toaster", "OverlayToaster", "ContextMenu"],
141
+ "@blueprintjs/select": BLUEPRINT_POPOVERS,
142
+ "semantic-ui-react": ["Modal", "Popup", "Portal", "Confirm", "TransitionablePortal"],
143
+ "@headlessui/react": ["Dialog", "Portal"],
144
+ "@reach/dialog": ["Dialog", "DialogOverlay", "default"],
145
+ "@reach/portal": ["default"],
146
+ "react-portal": ["Portal", "PortalWithState"],
147
+ "react-modal": ["default"],
148
+ "rc-dialog": ["default"],
149
+ "rc-drawer": ["default"],
150
+ "rc-tooltip": ["default"],
151
+ "rc-trigger": ["default"]
152
+ }).map(([name, exports]) => [name, new Set(exports)]));
153
+
154
+ /** Whether the export `name` of a package module, as {@link PACKAGE_PORTALS} lists it, renders into a portal. */
155
+ export function packagePortal(module: string, name: string): boolean {
156
+ if (isRelativeSpecifier(module)) return false;
157
+ const pkg = packageName(module);
158
+ const exports = PACKAGE_PORTALS.get(pkg);
159
+ if (!exports) return false;
160
+ const subpath = module.slice(pkg.length + 1);
161
+ // `import Dialog from '@material-ui/core/Dialog'` names the component by its subpath
162
+ return exports.has(subpath !== "" && name === "default" ? subpath.split("/")[0] : name);
163
+ }
164
+
165
+ /** The package a bare module specifier names, such as `@scope/name` for `@scope/name/sub`. */
166
+ export function packageName(specifier: string): string {
167
+ const parts = specifier.split("/");
168
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
169
+ }
170
+
171
+ /**
172
+ * Resolves relative specifiers among the scanned sources, and a bare one that no enclosing package
173
+ * declares from each of `roots`, the way a `baseUrl` of the package or the repository resolves it.
174
+ */
175
+ export function resolver(modules: Modules, roots: readonly string[], declares: (name: string) => boolean): Resolver {
176
+ return (from, specifier) => {
177
+ const relative = resolveRelative(from, specifier, modules);
178
+ if (relative || isRelativeSpecifier(specifier) || specifier.startsWith("node:") || declares(packageName(specifier))) return relative;
179
+ for (const root of roots) {
180
+ const aliased = resolveRelative(posix.join(root || ".", "_"), `./${specifier}`, modules);
181
+ if (aliased) return aliased;
182
+ }
183
+ return undefined;
184
+ };
185
+ }
186
+
187
+ export interface PortalContext {
188
+ /** The test source. */
189
+ sourcePath: string;
190
+ modules: Modules;
191
+ resolve: Resolver;
192
+ /** Whether a package enclosing the test declares a dependency on the named package. */
193
+ declares(name: string): boolean;
194
+ /** Whether a source in the test's package, other than a test, calls `createPortal`. */
195
+ packagePortals(): boolean;
196
+ }
197
+
198
+ /**
199
+ * Whether a component that `element` renders may render into a portal, whose content Enzyme's `mount`
200
+ * finds but a query of RTL's container does not. A component imported from the repository, by a relative
201
+ * path or a `baseUrl` alias, is followed through the components each source renders and the names it
202
+ * re-exports. One imported by a bare specifier that no enclosing package declares and that does not
203
+ * resolve counts as a portal when its package has one. A component of a declared dependency counts as one
204
+ * where {@link PACKAGE_PORTALS} lists it. A component the test declares is followed through its own body.
205
+ */
206
+ export function rendersPortal(element: J, cu: JS.CompilationUnit, context: PortalContext): boolean {
207
+ const bindings = importBindings(cu);
208
+ const local = localDeclarations(cu);
209
+ const memo = new Map<string, boolean>();
210
+ const followed = new Set<string>();
211
+ const reaches = (node: J): boolean => [...tagNames(node)].some(tag => {
212
+ const declaration = local.get(tag);
213
+ if (declaration) {
214
+ if (followed.has(tag)) return false;
215
+ followed.add(tag);
216
+ return callsCreatePortal(declaration) || reaches(declaration);
217
+ }
218
+ return bindings.some(({local, name, module}) => {
219
+ if (local !== tag) return false;
220
+ const target = context.resolve(context.sourcePath, module);
221
+ if (target) return reachesPortal(target, name, context.modules, context.resolve, memo);
222
+ if (packagePortal(module, name)) return true;
223
+ if (isRelativeSpecifier(module) || module.startsWith("node:") || context.declares(packageName(module))) return false;
224
+ return context.packagePortals();
225
+ });
226
+ });
227
+ return reaches(element);
228
+ }
229
+
230
+ /** The names of the components, and their namespaces, that the JSX tags within `node` name. */
231
+ function tagNames(node: J): Set<string> {
232
+ const names = new Set<string>();
233
+ walk(node, tree => {
234
+ if (tree.kind === JS.Kind.JsxTag) {
235
+ let name: J = (tree as JSX.Tag).openName.element;
236
+ while (name.kind === J.Kind.FieldAccess) name = (name as J.FieldAccess).target;
237
+ if (isIdentifier(name) && /^[A-Z_$]/.test(name.simpleName)) names.add(name.simpleName);
238
+ }
239
+ return true;
240
+ });
241
+ return names;
242
+ }
243
+
244
+ /** The functions, classes, and variables a source declares at its top level, exported or not, by name. */
245
+ function localDeclarations(cu: JS.CompilationUnit): Map<string, J> {
246
+ const declarations = new Map<string, J>();
247
+ for (const {element} of cu.statements) {
248
+ const statement = element as J;
249
+ if (statement.kind === JS.Kind.ExportDeclaration) continue;
250
+ if (statement.kind === J.Kind.MethodDeclaration) declarations.set((statement as J.MethodDeclaration).name.simpleName, statement);
251
+ if (statement.kind === J.Kind.ClassDeclaration) declarations.set((statement as J.ClassDeclaration).name.simpleName, statement);
252
+ if (statement.kind === J.Kind.VariableDeclarations) {
253
+ for (const {element: variable} of (statement as J.VariableDeclarations).variables) {
254
+ if (isIdentifier(variable.name)) declarations.set(variable.name.simpleName, variable);
255
+ }
256
+ }
257
+ }
258
+ return declarations;
259
+ }
260
+
261
+ function callsCreatePortal(node: J): boolean {
262
+ let portal = false;
263
+ walk(node, tree => {
264
+ if (tree.kind === J.Kind.MethodInvocation && (tree as J.MethodInvocation).name.simpleName === "createPortal") portal = true;
265
+ return !portal;
266
+ });
267
+ return portal;
268
+ }
269
+
270
+ /** `value` without the type assertions and parentheses around it, as in `export default (Tabs as TabsComponent)`. */
271
+ function withoutTypeAssertions(value: J): J {
272
+ for (;;) {
273
+ if (value.kind === JS.Kind.As) value = (value as JS.As).left.element;
274
+ else if (value.kind === JS.Kind.SatisfiesExpression) value = (value as JS.SatisfiesExpression).expression;
275
+ else if (value.kind === J.Kind.TypeCast) value = (value as J.TypeCast).expression;
276
+ else if (value.kind === J.Kind.Parentheses) value = (value as J.Parentheses<J>).tree.element;
277
+ else return value;
278
+ }
279
+ }
@@ -0,0 +1,59 @@
1
+ import {JS, JSX, walk} from "@openrewrite/rewrite/javascript";
2
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
3
+
4
+ /** The whitespace-separated words of a source's strings, and those of the props it passes to host and to composite elements. */
5
+ export interface SelectorNames {
6
+ strings: ReadonlySet<string>;
7
+ host: ReadonlySet<string>;
8
+ composite: ReadonlySet<string>;
9
+ }
10
+
11
+ export function selectorNames(cu: JS.CompilationUnit): SelectorNames {
12
+ const strings = new Set<string>();
13
+ const host = new Set<string>();
14
+ const composite = new Set<string>();
15
+ const words = (node: J, into: Set<string>) => walk(node, tree => {
16
+ for (const text of texts(tree as J)) text.split(/\s+/).filter(word => word !== "").forEach(word => into.add(word));
17
+ return true;
18
+ });
19
+ words(cu, strings);
20
+ walk(cu, tree => {
21
+ if (tree.kind === JS.Kind.JsxTag) {
22
+ const into = compositeTag(tree as JSX.Tag) ? composite : host;
23
+ (tree as JSX.Tag).attributes.forEach(({element}) => words(element, into));
24
+ }
25
+ return true;
26
+ });
27
+ return {strings, host, composite};
28
+ }
29
+
30
+ function texts(tree: J): string[] {
31
+ if (tree.kind === J.Kind.Literal) return typeof (tree as J.Literal).value === "string" ? [(tree as J.Literal).value as string] : [];
32
+ if (tree.kind !== JS.Kind.TemplateExpression) return [];
33
+ const template = tree as JS.TemplateExpression;
34
+ return [template.head, ...template.spans.map(({element}) => element.tail)].flatMap(texts);
35
+ }
36
+
37
+ function compositeTag(tag: JSX.Tag): boolean {
38
+ const name = tag.openName.element;
39
+ return name.kind === J.Kind.FieldAccess || (isIdentifier(name) && !/^[a-z]/.test(name.simpleName));
40
+ }
41
+
42
+ const TEST_SOURCE = /(^|\/)__tests?__\/|\.(test|spec)\.[cm]?[jt]sx?$/;
43
+
44
+ /**
45
+ * Whether each of `names` is one the repository's own sources write, as a host element's prop or a string
46
+ * outside the tests, and none passes to a composite element, so that only host elements carry it: a class
47
+ * or attribute that a package's components set, or one a component receives as a prop, may sit on the very
48
+ * element a descendant compound matches. The strings of tests are left out, as their selectors name it too.
49
+ */
50
+ export function hostOnlyNames(names: readonly string[], sources: ReadonlyMap<string, SelectorNames>): boolean {
51
+ return names.every(name => {
52
+ let written = false;
53
+ for (const [path, {strings, host, composite}] of sources) {
54
+ if (composite.has(name)) return false;
55
+ written ||= host.has(name) || strings.has(name) && !TEST_SOURCE.test(path);
56
+ }
57
+ return written;
58
+ });
59
+ }