@openrewrite/recipes-react 0.20.0 → 0.22.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 +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +37 -1
- package/dist/index.js.map +1 -1
- package/dist/mui/adapt-v4-theme.d.ts +8 -0
- package/dist/mui/adapt-v4-theme.d.ts.map +1 -0
- package/dist/mui/adapt-v4-theme.js +65 -0
- package/dist/mui/adapt-v4-theme.js.map +1 -0
- package/dist/mui/add-component-prop.d.ts +18 -0
- package/dist/mui/add-component-prop.d.ts.map +1 -0
- package/dist/mui/add-component-prop.js +53 -0
- package/dist/mui/add-component-prop.js.map +1 -0
- package/dist/mui/add-emotion-prepend.d.ts +8 -0
- package/dist/mui/add-emotion-prepend.d.ts.map +1 -0
- package/dist/mui/add-emotion-prepend.js +71 -0
- package/dist/mui/add-emotion-prepend.js.map +1 -0
- package/dist/mui/change-module-specifier.d.ts +14 -0
- package/dist/mui/change-module-specifier.d.ts.map +1 -0
- package/dist/mui/change-module-specifier.js +95 -0
- package/dist/mui/change-module-specifier.js.map +1 -0
- package/dist/mui/convert-mui-imports.d.ts +14 -0
- package/dist/mui/convert-mui-imports.d.ts.map +1 -0
- package/dist/mui/convert-mui-imports.js +195 -0
- package/dist/mui/convert-mui-imports.js.map +1 -0
- package/dist/mui/convert-prop-to-sx.d.ts +22 -0
- package/dist/mui/convert-prop-to-sx.d.ts.map +1 -0
- package/dist/mui/convert-prop-to-sx.js +99 -0
- package/dist/mui/convert-prop-to-sx.js.map +1 -0
- package/dist/mui/index.d.ts +32 -0
- package/dist/mui/index.d.ts.map +1 -0
- package/dist/mui/index.js +67 -0
- package/dist/mui/index.js.map +1 -0
- package/dist/mui/jsx-attributes.d.ts +27 -0
- package/dist/mui/jsx-attributes.d.ts.map +1 -0
- package/dist/mui/jsx-attributes.js +140 -0
- package/dist/mui/jsx-attributes.js.map +1 -0
- package/dist/mui/mark-manual-migration.d.ts +16 -0
- package/dist/mui/mark-manual-migration.d.ts.map +1 -0
- package/dist/mui/mark-manual-migration.js +73 -0
- package/dist/mui/mark-manual-migration.js.map +1 -0
- package/dist/mui/mark-palette-mode-usage.d.ts +12 -0
- package/dist/mui/mark-palette-mode-usage.d.ts.map +1 -0
- package/dist/mui/mark-palette-mode-usage.js +50 -0
- package/dist/mui/mark-palette-mode-usage.js.map +1 -0
- package/dist/mui/move-component-prop-to-slot.d.ts +22 -0
- package/dist/mui/move-component-prop-to-slot.d.ts.map +1 -0
- package/dist/mui/move-component-prop-to-slot.js +87 -0
- package/dist/mui/move-component-prop-to-slot.js.map +1 -0
- package/dist/mui/move-primary-text-to-children.d.ts +12 -0
- package/dist/mui/move-primary-text-to-children.d.ts.map +1 -0
- package/dist/mui/move-primary-text-to-children.js +52 -0
- package/dist/mui/move-primary-text-to-children.js.map +1 -0
- package/dist/mui/move-system-props-to-sx.d.ts +16 -0
- package/dist/mui/move-system-props-to-sx.d.ts.map +1 -0
- package/dist/mui/move-system-props-to-sx.js +122 -0
- package/dist/mui/move-system-props-to-sx.js.map +1 -0
- package/dist/mui/mui-components.d.ts +8 -0
- package/dist/mui/mui-components.d.ts.map +1 -0
- package/dist/mui/mui-components.js +41 -0
- package/dist/mui/mui-components.js.map +1 -0
- package/dist/mui/mui-tag-visitor.d.ts +5 -0
- package/dist/mui/mui-tag-visitor.d.ts.map +1 -0
- package/dist/mui/mui-tag-visitor.js +54 -0
- package/dist/mui/mui-tag-visitor.js.map +1 -0
- package/dist/mui/pre-v5-recipe.d.ts +14 -0
- package/dist/mui/pre-v5-recipe.d.ts.map +1 -0
- package/dist/mui/pre-v5-recipe.js +88 -0
- package/dist/mui/pre-v5-recipe.js.map +1 -0
- package/dist/mui/remove-component-prop.d.ts +18 -0
- package/dist/mui/remove-component-prop.d.ts.map +1 -0
- package/dist/mui/remove-component-prop.js +55 -0
- package/dist/mui/remove-component-prop.js.map +1 -0
- package/dist/mui/remove-root-ref.d.ts +8 -0
- package/dist/mui/remove-root-ref.d.ts.map +1 -0
- package/dist/mui/remove-root-ref.js +61 -0
- package/dist/mui/remove-root-ref.js.map +1 -0
- package/dist/mui/remove-spacing-px-suffix.d.ts +8 -0
- package/dist/mui/remove-spacing-px-suffix.d.ts.map +1 -0
- package/dist/mui/remove-spacing-px-suffix.js +62 -0
- package/dist/mui/remove-spacing-px-suffix.js.map +1 -0
- package/dist/mui/rename-component-prop.d.ts +20 -0
- package/dist/mui/rename-component-prop.d.ts.map +1 -0
- package/dist/mui/rename-component-prop.js +66 -0
- package/dist/mui/rename-component-prop.js.map +1 -0
- package/dist/mui/rename-joy-css-variables.d.ts +8 -0
- package/dist/mui/rename-joy-css-variables.d.ts.map +1 -0
- package/dist/mui/rename-joy-css-variables.js +51 -0
- package/dist/mui/rename-joy-css-variables.js.map +1 -0
- package/dist/mui/rename-theme-palette-type.d.ts +8 -0
- package/dist/mui/rename-theme-palette-type.d.ts.map +1 -0
- package/dist/mui/rename-theme-palette-type.js +61 -0
- package/dist/mui/rename-theme-palette-type.js.map +1 -0
- package/dist/mui/replace-box-border-radius.d.ts +10 -0
- package/dist/mui/replace-box-border-radius.d.ts.map +1 -0
- package/dist/mui/replace-box-border-radius.js +50 -0
- package/dist/mui/replace-box-border-radius.js.map +1 -0
- package/dist/mui/replace-breakpoints-width.d.ts +8 -0
- package/dist/mui/replace-breakpoints-width.d.ts.map +1 -0
- package/dist/mui/replace-breakpoints-width.js +46 -0
- package/dist/mui/replace-breakpoints-width.js.map +1 -0
- package/dist/mui/replace-component-class.d.ts +18 -0
- package/dist/mui/replace-component-class.d.ts.map +1 -0
- package/dist/mui/replace-component-class.js +126 -0
- package/dist/mui/replace-component-class.js.map +1 -0
- package/dist/mui/replace-components-with-slots.d.ts +14 -0
- package/dist/mui/replace-components-with-slots.d.ts.map +1 -0
- package/dist/mui/replace-components-with-slots.js +69 -0
- package/dist/mui/replace-components-with-slots.js.map +1 -0
- package/dist/mui/replace-import-paths.d.ts +14 -0
- package/dist/mui/replace-import-paths.d.ts.map +1 -0
- package/dist/mui/replace-import-paths.js +101 -0
- package/dist/mui/replace-import-paths.js.map +1 -0
- package/dist/mui/replace-in-string-literals.d.ts +15 -0
- package/dist/mui/replace-in-string-literals.d.ts.map +1 -0
- package/dist/mui/replace-in-string-literals.js +62 -0
- package/dist/mui/replace-in-string-literals.js.map +1 -0
- package/dist/mui/replace-list-item-button-prop.d.ts +12 -0
- package/dist/mui/replace-list-item-button-prop.d.ts.map +1 -0
- package/dist/mui/replace-list-item-button-prop.js +80 -0
- package/dist/mui/replace-list-item-button-prop.js.map +1 -0
- package/dist/mui/replace-tabs-scroll-buttons.d.ts +8 -0
- package/dist/mui/replace-tabs-scroll-buttons.d.ts.map +1 -0
- package/dist/mui/replace-tabs-scroll-buttons.js +41 -0
- package/dist/mui/replace-tabs-scroll-buttons.js.map +1 -0
- package/dist/mui/replace-theme-color-functions.d.ts +8 -0
- package/dist/mui/replace-theme-color-functions.d.ts.map +1 -0
- package/dist/mui/replace-theme-color-functions.js +72 -0
- package/dist/mui/replace-theme-color-functions.js.map +1 -0
- package/dist/mui/replace-theme-spacing-unit.d.ts +8 -0
- package/dist/mui/replace-theme-spacing-unit.d.ts.map +1 -0
- package/dist/mui/replace-theme-spacing-unit.js +77 -0
- package/dist/mui/replace-theme-spacing-unit.js.map +1 -0
- package/dist/mui/replace-typography-round.d.ts +8 -0
- package/dist/mui/replace-typography-round.d.ts.map +1 -0
- package/dist/mui/replace-typography-round.js +44 -0
- package/dist/mui/replace-typography-round.js.map +1 -0
- package/dist/mui/shift-hidden-down-props.d.ts +10 -0
- package/dist/mui/shift-hidden-down-props.d.ts.map +1 -0
- package/dist/mui/shift-hidden-down-props.js +49 -0
- package/dist/mui/shift-hidden-down-props.js.map +1 -0
- package/dist/mui/theme-access.d.ts +5 -0
- package/dist/mui/theme-access.d.ts.map +1 -0
- package/dist/mui/theme-access.js +21 -0
- package/dist/mui/theme-access.js.map +1 -0
- package/dist/mui/update-theme-breakpoints.d.ts +10 -0
- package/dist/mui/update-theme-breakpoints.d.ts.map +1 -0
- package/dist/mui/update-theme-breakpoints.js +58 -0
- package/dist/mui/update-theme-breakpoints.js.map +1 -0
- package/dist/mui/upgrade-grid-props.d.ts +16 -0
- package/dist/mui/upgrade-grid-props.d.ts.map +1 -0
- package/dist/mui/upgrade-grid-props.js +90 -0
- package/dist/mui/upgrade-grid-props.js.map +1 -0
- package/dist/search/find-enzyme-usage.d.ts +8 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +119 -8
- 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-host-components.d.ts +12 -0
- package/dist/testing/enzyme-host-components.d.ts.map +1 -1
- package/dist/testing/enzyme-host-components.js +100 -0
- package/dist/testing/enzyme-host-components.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 +19 -0
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
- package/dist/testing/enzyme-render-blockers.js +275 -0
- package/dist/testing/enzyme-render-blockers.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +17 -3
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +237 -27
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +9 -0
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +36 -3
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +8 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +26 -5
- 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 +7 -4
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +128 -11
- 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 +147 -46
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +14 -5
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +226 -52
- 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 +17 -0
- package/src/mui/adapt-v4-theme.ts +43 -0
- package/src/mui/add-component-prop.ts +43 -0
- package/src/mui/add-emotion-prepend.ts +48 -0
- package/src/mui/change-module-specifier.ts +71 -0
- package/src/mui/convert-mui-imports.ts +184 -0
- package/src/mui/convert-prop-to-sx.ts +89 -0
- package/src/mui/index.ts +31 -0
- package/src/mui/jsx-attributes.ts +133 -0
- package/src/mui/mark-manual-migration.ts +53 -0
- package/src/mui/mark-palette-mode-usage.ts +36 -0
- package/src/mui/move-component-prop-to-slot.ts +84 -0
- package/src/mui/move-primary-text-to-children.ts +41 -0
- package/src/mui/move-system-props-to-sx.ts +118 -0
- package/src/mui/mui-components.ts +40 -0
- package/src/mui/mui-tag-visitor.ts +36 -0
- package/src/mui/pre-v5-recipe.ts +82 -0
- package/src/mui/remove-component-prop.ts +43 -0
- package/src/mui/remove-root-ref.ts +41 -0
- package/src/mui/remove-spacing-px-suffix.ts +43 -0
- package/src/mui/rename-component-prop.ts +55 -0
- package/src/mui/rename-joy-css-variables.ts +41 -0
- package/src/mui/rename-theme-palette-type.ts +42 -0
- package/src/mui/replace-box-border-radius.ts +42 -0
- package/src/mui/replace-breakpoints-width.ts +28 -0
- package/src/mui/replace-component-class.ts +97 -0
- package/src/mui/replace-components-with-slots.ts +61 -0
- package/src/mui/replace-import-paths.ts +100 -0
- package/src/mui/replace-in-string-literals.ts +44 -0
- package/src/mui/replace-list-item-button-prop.ts +59 -0
- package/src/mui/replace-tabs-scroll-buttons.ts +31 -0
- package/src/mui/replace-theme-color-functions.ts +55 -0
- package/src/mui/replace-theme-spacing-unit.ts +59 -0
- package/src/mui/replace-typography-round.ts +29 -0
- package/src/mui/shift-hidden-down-props.ts +44 -0
- package/src/mui/theme-access.ts +18 -0
- package/src/mui/update-theme-breakpoints.ts +47 -0
- package/src/mui/upgrade-grid-props.ts +82 -0
- package/src/search/find-enzyme-usage.ts +109 -12
- 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-host-components.ts +110 -0
- package/src/testing/enzyme-portals.ts +4 -44
- package/src/testing/enzyme-render-blockers.ts +278 -0
- package/src/testing/enzyme-to-react-testing-library.ts +240 -34
- package/src/testing/enzyme-usage.ts +48 -2
- package/src/testing/enzyme-wrapper-scope.ts +35 -3
- 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 +131 -12
- package/src/zustand/redux-to-zustand.ts +179 -52
- package/src/zustand/zustand-plan.ts +256 -49
|
@@ -401,8 +401,19 @@ export function wrapperDeclaration<R>(statement: J | undefined, classify: (rende
|
|
|
401
401
|
* admits `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()`, whose
|
|
402
402
|
* snapshot RTL records as the DOM rather than Enzyme's tree. `hostNames` decides the selectors {@link selectorLiteral} accepts.
|
|
403
403
|
*/
|
|
404
|
+
/** A reference that keeps a wrapper on Enzyme, with the `toMatchSnapshot` call where it is a snapshot assertion the snapshot recipe converts. */
|
|
405
|
+
export interface BlockingReference {
|
|
406
|
+
cursor: Cursor;
|
|
407
|
+
unmounted: boolean;
|
|
408
|
+
snapshot?: J.MethodInvocation;
|
|
409
|
+
}
|
|
410
|
+
|
|
404
411
|
export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperDeclaration,
|
|
405
|
-
{events, html, untaggedPositions, hostNames, snapshots = false, optionalChaining = true, constant = () => undefined}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean,
|
|
412
|
+
{events, html, untaggedPositions, hostNames, snapshots = false, optInSnapshots = false, optionalChaining = true, constant = () => undefined, blocked}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean,
|
|
413
|
+
/** Whether the snapshot recipe would convert the snapshot assertions this analysis rejects. */
|
|
414
|
+
optInSnapshots?: boolean, optionalChaining?: boolean, constant?: (node: J) => string | undefined,
|
|
415
|
+
/** Told every reference that rejects the scope, whether it comes after an unmount, and the snapshot assertion it is the subject of. */
|
|
416
|
+
blocked?: (references: BlockingReference[]) => void}): WrapperScope | undefined {
|
|
406
417
|
let serializers: ReadonlySet<string> | undefined;
|
|
407
418
|
const uses = new Map<string, WrapperRead>();
|
|
408
419
|
const removedStatements = new Set<string>();
|
|
@@ -436,9 +447,14 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
436
447
|
return undefined;
|
|
437
448
|
};
|
|
438
449
|
|
|
439
|
-
const
|
|
450
|
+
const ancestorsOf = (reference: Cursor): Cursor[] => {
|
|
440
451
|
const ancestors: Cursor[] = [];
|
|
441
452
|
for (let c: Cursor | undefined = reference.parentTree(); c && ancestors.length < 5; c = c.parentTree()) ancestors.push(c);
|
|
453
|
+
return ancestors;
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
const use = (identifier: J.Identifier, reference: Cursor): boolean => {
|
|
457
|
+
const ancestors = ancestorsOf(reference);
|
|
442
458
|
const first = ancestors[0]?.value as J | undefined;
|
|
443
459
|
if (snapshots) {
|
|
444
460
|
serializers ??= snapshotSerializers(block);
|
|
@@ -543,9 +559,25 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
543
559
|
const declared = new Cursor(variable.name, variableCursor(block, declaration));
|
|
544
560
|
const references = referencesOf(declared, name, "value");
|
|
545
561
|
if (!references.some(reference => reference.identifier === variable.name)) return undefined;
|
|
562
|
+
const rejected: BlockingReference[] = [];
|
|
546
563
|
for (const reference of references) {
|
|
547
564
|
if (reference.identifier === variable.name) continue;
|
|
548
|
-
|
|
565
|
+
const after = unmounted;
|
|
566
|
+
if (reference.declares || after || !use(reference.identifier, reference.cursor)) {
|
|
567
|
+
if (!blocked) return undefined;
|
|
568
|
+
let snapshot: J.MethodInvocation | undefined;
|
|
569
|
+
if (optInSnapshots && !after && !reference.declares) {
|
|
570
|
+
serializers ??= snapshotSerializers(block);
|
|
571
|
+
const ancestors = ancestorsOf(reference.cursor);
|
|
572
|
+
const expectCall = snapshotAssertion(reference.identifier, ancestors, serializers);
|
|
573
|
+
snapshot = expectCall && ancestors.find(c => c.value.kind === J.Kind.MethodInvocation && (c.value as J.MethodInvocation).select?.element === expectCall)?.value;
|
|
574
|
+
}
|
|
575
|
+
rejected.push({cursor: reference.cursor, unmounted: after, snapshot});
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (rejected.length > 0) {
|
|
579
|
+
blocked!(rejected);
|
|
580
|
+
return undefined;
|
|
549
581
|
}
|
|
550
582
|
return {declaration, name, uses, removedStatements, unmounts};
|
|
551
583
|
}
|
|
@@ -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
|
+
}
|